babylon.no-module.max.js 5.5 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059111060111061111062111063111064111065111066111067111068111069111070111071111072111073111074111075111076111077111078111079111080111081111082111083111084111085111086111087111088111089111090111091111092111093111094111095111096111097111098111099111100111101111102111103111104111105111106111107111108111109111110111111111112111113111114111115111116111117111118111119111120111121111122111123111124111125111126111127111128111129111130111131111132111133111134111135111136111137111138111139111140111141111142111143111144111145111146111147111148111149111150111151111152111153111154111155111156111157111158111159111160111161111162111163111164111165111166111167111168111169111170111171111172111173111174111175111176111177111178111179111180111181111182111183111184111185111186111187111188111189111190111191111192111193111194111195111196111197111198111199111200111201111202111203111204111205111206111207111208111209111210111211111212111213111214111215111216111217111218111219111220111221111222111223111224111225111226111227111228111229111230111231111232111233111234111235111236111237111238111239111240111241111242111243111244111245111246111247111248111249111250111251111252111253111254111255111256111257111258111259111260111261111262111263111264111265111266111267111268111269111270111271111272111273111274111275111276111277111278111279111280111281111282111283111284111285111286111287111288111289111290111291111292111293111294111295111296111297111298111299111300111301111302111303111304111305111306111307111308111309111310111311111312111313111314111315111316111317111318111319111320111321111322111323111324111325111326111327111328111329111330111331111332111333111334111335111336111337111338111339111340111341111342111343111344111345111346111347111348111349111350111351111352111353111354111355111356111357111358111359111360111361111362111363111364111365111366111367111368111369111370111371111372111373111374111375111376111377111378111379111380111381111382111383111384111385111386111387111388111389111390111391111392111393111394111395111396111397111398111399111400111401111402111403111404111405111406111407111408111409111410111411111412111413111414111415111416111417111418111419111420111421111422111423111424111425111426111427111428111429111430111431111432111433111434111435111436111437111438111439111440111441111442111443111444111445111446111447111448111449111450111451111452111453111454111455111456111457111458111459111460111461111462111463111464111465111466111467111468111469111470111471111472111473111474111475111476111477111478111479111480111481111482111483111484111485111486111487111488111489111490111491111492111493111494111495111496111497111498111499111500111501111502111503111504111505111506111507111508111509111510111511111512111513111514111515111516111517111518111519111520111521111522111523111524111525111526111527111528111529111530111531111532111533111534111535111536111537111538111539111540111541111542111543111544111545111546111547111548111549111550111551111552111553111554111555111556111557111558111559111560111561111562111563111564111565111566111567111568111569111570111571111572111573111574111575111576111577111578111579111580111581111582111583111584111585111586111587111588111589111590111591111592111593111594111595111596111597111598111599111600111601111602111603111604111605111606111607111608111609111610111611111612111613111614111615111616111617111618111619111620111621111622111623111624111625111626111627111628111629111630111631111632111633111634111635111636111637111638111639111640111641111642111643111644111645111646111647111648111649111650111651111652111653111654111655111656111657111658111659111660111661111662111663111664111665111666111667111668111669111670111671111672111673111674111675111676111677111678111679111680111681111682111683111684111685111686111687111688111689111690111691111692111693111694111695111696111697111698111699111700111701111702111703111704111705111706111707111708111709111710111711111712111713111714111715111716111717111718111719111720111721111722111723111724111725111726111727111728111729111730111731111732111733111734111735111736111737111738111739111740111741111742111743111744111745111746111747111748111749111750111751111752111753111754111755111756111757111758111759111760111761111762111763111764111765111766111767111768111769111770111771111772111773111774111775111776111777111778111779111780111781111782111783111784111785111786111787111788111789111790111791111792111793111794111795111796111797111798111799111800111801111802111803111804111805111806111807111808111809111810111811111812111813111814111815111816111817111818111819111820111821111822111823111824111825111826111827111828111829111830111831111832111833111834111835111836111837111838111839111840111841111842111843111844111845111846111847111848111849111850111851111852111853111854111855111856111857111858111859111860111861111862111863111864111865111866111867111868111869111870111871111872111873111874111875111876111877111878111879111880111881111882111883111884111885111886111887111888111889111890111891111892111893111894111895111896111897111898111899111900111901111902111903111904111905111906111907111908111909111910111911111912111913111914111915111916111917111918111919111920111921111922111923111924111925111926111927111928111929111930111931111932111933111934111935111936111937111938111939111940111941111942111943111944111945111946111947111948111949111950111951111952111953111954111955111956111957111958111959111960111961111962111963111964111965111966111967111968111969111970111971111972111973111974111975111976111977111978111979111980111981111982111983111984111985111986111987111988111989111990111991111992111993111994111995111996111997111998111999112000112001112002112003112004112005112006112007112008112009112010112011112012112013112014112015112016112017112018112019112020112021112022112023112024112025112026112027112028112029112030112031112032112033112034112035112036112037112038112039112040112041112042112043112044112045112046112047112048112049112050112051112052112053112054112055112056112057112058112059112060112061112062112063112064112065112066112067112068112069112070112071112072112073112074112075112076112077112078112079112080112081112082112083112084112085112086112087112088112089112090112091112092112093112094112095112096112097112098112099112100112101112102112103112104112105112106112107112108112109112110112111112112112113112114112115112116112117112118112119112120112121112122112123112124112125112126112127112128112129112130112131112132112133112134112135112136112137112138112139112140112141112142112143112144112145112146112147112148112149112150112151112152112153112154112155112156112157112158112159112160112161112162112163112164112165112166112167112168112169112170112171112172112173112174112175112176112177112178112179112180112181112182112183112184112185112186112187112188112189112190112191112192112193112194112195112196112197112198112199112200112201112202112203112204112205112206112207112208112209112210112211112212112213112214112215112216112217112218112219112220112221112222112223112224112225112226112227112228112229112230112231112232112233112234112235112236112237112238112239112240112241112242112243112244112245112246112247112248112249112250112251112252112253112254112255112256112257112258112259112260112261112262112263112264112265112266112267112268112269112270112271112272112273112274112275112276112277112278112279112280112281112282112283112284112285112286112287112288112289112290112291112292112293112294112295112296112297112298112299112300112301112302112303112304112305112306112307112308112309112310112311112312112313112314112315112316112317112318112319112320112321112322112323112324112325112326112327112328112329112330112331112332112333112334112335112336112337112338112339112340112341112342112343112344112345112346112347112348112349112350112351112352112353112354112355112356112357112358112359112360112361112362112363112364112365112366112367112368112369112370112371112372112373112374112375112376112377112378112379112380112381112382112383112384112385112386112387112388112389112390112391112392112393112394112395112396112397112398112399112400112401112402112403112404112405112406112407112408112409112410112411112412112413112414112415112416112417112418112419112420112421112422112423112424112425112426112427112428112429112430112431112432112433112434112435112436112437112438112439112440112441112442112443112444112445112446112447112448112449112450112451112452112453112454112455112456112457112458112459112460112461112462112463112464112465112466112467112468112469112470112471112472112473112474112475112476112477112478112479112480112481112482112483112484112485112486112487112488112489112490112491112492112493112494112495112496112497112498112499112500112501112502112503112504112505112506112507112508112509112510112511112512112513112514112515112516112517112518112519112520112521112522112523112524112525112526112527112528112529112530112531112532112533112534112535112536112537112538112539112540112541112542112543112544112545112546112547112548112549112550112551112552112553112554112555112556112557112558112559112560112561112562112563112564112565112566112567112568112569112570112571112572112573112574112575112576112577112578112579112580112581112582112583112584112585112586112587112588112589112590112591112592112593112594112595112596112597112598112599112600112601112602112603112604112605112606112607112608112609112610112611112612112613112614112615112616112617112618112619112620112621112622112623112624112625112626112627112628112629112630112631112632112633112634112635112636112637112638112639112640112641112642112643112644112645112646112647112648112649112650112651112652112653112654112655112656112657112658112659112660112661112662112663112664112665112666112667112668112669112670112671112672112673112674112675112676112677112678112679112680112681112682112683112684112685112686112687112688112689112690112691112692112693112694112695112696112697112698112699112700112701112702112703112704112705112706112707112708112709112710112711112712112713112714112715112716112717112718112719112720112721112722112723112724112725112726112727112728112729112730112731112732112733112734112735112736112737112738112739112740112741112742112743112744112745112746112747112748112749112750112751112752112753112754112755112756112757112758112759112760112761112762112763112764112765112766112767112768112769112770112771112772112773112774112775112776112777112778112779112780112781112782112783112784112785112786112787112788112789112790112791112792112793112794112795112796112797112798112799112800112801112802112803112804112805112806112807112808112809112810112811112812112813112814112815112816112817112818112819112820112821112822112823112824112825112826112827112828112829112830112831112832112833112834112835112836112837112838112839112840112841112842112843112844112845112846112847112848112849112850112851112852112853112854112855112856112857112858112859112860112861112862112863112864112865112866112867112868112869112870112871112872112873112874112875112876112877112878112879112880112881112882112883112884112885112886112887112888112889112890112891112892112893112894112895112896112897112898112899112900112901112902112903112904112905112906112907112908112909112910112911112912112913112914112915112916112917112918112919112920112921112922112923112924112925112926112927112928112929112930112931112932112933112934112935112936112937112938112939112940112941112942112943112944112945112946112947112948112949112950112951112952112953112954112955112956112957112958112959112960112961112962112963112964112965112966112967112968112969112970112971112972112973112974112975112976112977112978112979112980112981112982112983112984112985112986112987112988112989112990112991112992112993112994112995112996112997112998112999113000113001113002113003113004113005113006113007113008113009113010113011113012113013113014113015113016113017113018113019113020113021113022113023113024113025113026113027113028113029113030113031113032113033113034113035113036113037113038113039113040113041113042113043113044113045113046113047113048113049113050113051113052113053113054113055113056113057113058113059113060113061113062113063113064113065113066113067113068113069113070113071113072113073113074113075113076113077113078113079113080113081113082113083113084113085113086113087113088113089113090113091113092113093113094113095113096113097113098113099113100113101113102113103113104113105113106113107113108113109113110113111113112113113113114113115113116113117113118113119113120113121113122113123113124113125113126113127113128113129113130113131113132113133113134113135113136113137113138113139113140113141113142113143113144113145113146113147113148113149113150113151113152113153113154113155113156113157113158113159113160113161113162113163113164113165113166113167113168113169113170113171113172113173113174113175113176113177113178113179113180113181113182113183113184113185113186113187113188113189113190113191113192113193113194113195113196113197113198113199113200113201113202113203113204113205113206113207113208113209113210113211113212113213113214113215113216113217113218113219113220113221113222113223113224113225113226113227113228113229113230113231113232113233113234113235113236113237113238113239113240113241113242113243113244113245113246113247113248113249113250113251113252113253113254113255113256113257113258113259113260113261113262113263113264113265113266113267113268113269113270113271113272113273113274113275113276113277113278113279113280113281113282113283113284113285113286113287113288113289113290113291113292113293113294113295113296113297113298113299113300113301113302113303113304113305113306113307113308113309113310113311113312113313113314113315113316113317113318113319113320113321113322113323113324113325113326113327113328113329113330113331113332113333113334113335113336113337113338113339113340113341113342113343113344113345113346113347113348113349113350113351113352113353113354113355113356113357113358113359113360113361113362113363113364113365113366113367113368113369113370113371113372113373113374113375113376113377113378113379113380113381113382113383113384113385113386113387113388113389113390113391113392113393113394113395113396113397113398113399113400113401113402113403113404113405113406113407113408113409113410113411113412113413113414113415113416113417113418113419113420113421113422113423113424113425113426113427113428113429113430113431113432113433113434113435113436113437113438113439113440113441113442113443113444113445113446113447113448113449113450113451113452113453113454113455113456113457113458113459113460113461113462113463113464113465113466113467113468113469113470113471113472113473113474113475113476113477113478113479113480113481113482113483113484113485113486113487113488113489113490113491113492113493113494113495113496113497113498113499113500113501113502113503113504113505113506113507113508113509113510113511113512113513113514113515113516113517113518113519113520113521113522113523113524113525113526113527113528113529113530113531113532113533113534113535113536113537113538113539113540113541113542113543113544113545113546113547113548113549113550113551113552113553113554113555113556113557113558113559113560113561113562113563113564113565113566113567113568113569113570113571113572113573113574113575113576113577113578113579113580113581113582113583113584113585113586113587113588113589113590113591113592113593113594113595113596113597113598113599113600113601113602113603113604113605113606113607113608113609113610113611113612113613113614113615113616113617113618113619113620113621113622113623113624113625113626113627113628113629113630113631113632113633113634113635113636113637113638113639113640113641113642113643113644113645113646113647113648113649113650113651113652113653113654113655113656113657113658113659113660113661113662113663113664113665113666113667113668113669113670113671113672113673113674113675113676113677113678113679113680113681113682113683113684113685113686113687113688113689113690113691113692113693113694113695113696113697113698113699113700113701113702113703113704113705113706113707113708113709113710113711113712113713113714113715113716113717113718113719113720113721113722113723113724113725113726113727113728113729113730113731113732113733113734113735113736113737113738113739113740113741113742113743113744113745113746113747113748113749113750113751113752113753113754113755113756113757113758113759113760113761113762113763113764113765113766113767113768113769113770113771113772113773113774113775113776113777113778113779113780113781113782113783113784113785113786113787113788113789113790113791113792113793113794113795113796113797113798113799113800113801113802113803113804113805113806113807113808113809113810113811113812113813113814113815113816113817113818113819113820113821113822113823113824113825113826113827113828113829113830113831113832113833113834113835113836113837113838113839113840113841113842113843113844113845113846113847113848113849113850113851113852113853113854113855113856113857113858113859113860113861113862113863113864113865113866113867113868113869113870113871113872113873113874113875113876113877113878113879113880113881113882113883113884113885113886113887113888113889113890113891113892113893113894113895113896113897113898113899113900113901113902113903113904113905113906113907113908113909113910113911113912113913113914113915113916113917113918113919113920113921113922113923113924113925113926113927113928113929113930113931113932113933113934113935113936113937113938113939113940113941113942113943113944113945113946113947113948113949113950113951113952113953113954113955113956113957113958113959113960113961113962113963113964113965113966113967113968113969113970113971113972113973113974113975113976113977113978113979113980113981113982113983113984113985113986113987113988113989113990113991113992113993113994113995113996113997113998113999114000114001114002114003114004114005114006114007114008114009114010114011114012114013114014114015114016114017114018114019114020114021114022114023114024114025114026114027114028114029114030114031114032114033114034114035114036114037114038114039114040114041114042114043114044114045114046114047114048114049114050114051114052114053114054114055114056114057114058114059114060114061114062114063114064114065114066114067114068114069114070114071114072114073114074114075114076114077114078114079114080114081114082114083114084114085114086114087114088114089114090114091114092114093114094114095114096114097114098114099114100114101114102114103114104114105114106114107114108114109114110114111114112114113114114114115114116114117114118114119114120114121114122114123114124114125114126114127114128114129114130114131114132114133114134114135114136114137114138114139114140114141114142114143114144114145114146114147114148114149114150114151114152114153114154114155114156114157114158114159114160114161114162114163114164114165114166114167114168114169114170114171114172114173114174114175114176114177114178114179114180114181114182114183114184114185114186114187114188114189114190114191114192114193114194114195114196114197114198114199114200114201114202114203114204114205114206114207114208114209114210114211114212114213114214114215114216114217114218114219114220114221114222114223114224114225114226114227114228114229114230114231114232114233114234114235114236114237114238114239114240114241114242114243114244114245114246114247114248114249114250114251114252114253114254114255114256114257114258114259114260114261114262114263114264114265114266114267114268114269114270114271114272114273114274114275114276114277114278114279114280114281114282114283114284114285114286114287114288114289114290114291114292114293114294114295114296114297114298114299114300114301114302114303114304114305114306114307114308114309114310114311114312114313114314114315114316114317114318114319114320114321114322114323114324114325114326114327114328114329114330114331114332114333114334114335114336114337114338114339114340114341114342114343114344114345114346114347114348114349114350114351114352114353114354114355114356114357114358114359114360114361114362114363114364114365114366114367114368114369114370114371114372114373114374114375114376114377114378114379114380114381114382114383114384114385114386114387114388114389114390114391114392114393114394114395114396114397114398114399114400114401114402114403114404114405114406114407114408114409114410114411114412114413114414114415114416114417114418114419114420114421114422114423114424114425114426114427114428114429114430114431114432114433114434114435114436114437114438114439114440114441114442114443114444114445114446114447114448114449114450114451114452114453114454114455114456114457114458114459114460114461114462114463114464114465114466114467114468114469114470114471114472114473114474114475114476114477114478114479114480114481114482114483114484114485114486114487114488114489114490114491114492114493114494114495114496114497114498114499114500114501114502114503114504114505114506114507114508114509114510114511114512114513114514114515114516114517114518114519114520114521114522114523114524114525114526114527114528114529114530114531114532114533114534114535114536114537114538114539114540114541114542114543114544114545114546114547114548114549114550114551114552114553114554114555114556114557114558114559114560114561114562114563114564114565114566114567114568114569114570114571114572114573114574114575114576114577114578114579114580114581114582114583114584114585114586114587114588114589114590114591114592114593114594114595114596114597114598114599114600114601114602114603114604114605114606114607114608114609114610114611114612114613114614114615114616114617114618114619114620114621114622114623114624114625114626114627114628114629114630114631114632114633114634114635114636114637114638114639114640114641114642114643114644114645114646114647114648114649114650114651114652114653114654114655114656114657114658114659114660114661114662114663114664114665114666114667114668114669114670114671114672114673114674114675114676114677114678114679114680114681114682114683114684114685114686114687114688114689114690114691114692114693114694114695114696114697114698114699114700114701114702114703114704114705114706114707114708114709114710114711114712114713114714114715114716114717114718114719114720114721114722114723114724114725114726114727114728114729114730114731114732114733114734114735114736114737114738114739114740114741114742114743114744114745114746114747114748114749114750114751114752114753114754114755114756114757114758114759114760114761114762114763114764114765114766114767114768114769114770114771114772114773114774114775114776114777114778114779114780114781114782114783114784114785114786114787114788114789114790114791114792114793114794114795114796114797114798114799114800114801114802114803114804114805114806114807114808114809114810114811114812114813114814114815114816114817114818114819114820114821114822114823114824114825114826114827114828114829114830114831114832114833114834114835114836114837114838114839114840114841114842114843114844114845114846114847114848114849114850114851114852114853114854114855114856114857114858114859114860114861114862114863114864114865114866114867114868114869114870114871114872114873114874114875114876114877114878114879114880114881114882114883114884114885114886114887114888114889114890114891114892114893114894114895114896114897114898114899114900114901114902114903114904114905114906114907114908114909114910114911114912114913114914114915114916114917114918114919114920114921114922114923114924114925114926114927114928114929114930114931114932114933114934114935114936114937114938114939114940114941114942114943114944114945114946114947114948114949114950114951114952114953114954114955114956114957114958114959114960114961114962114963114964114965114966114967114968114969114970114971114972114973114974114975114976114977114978114979114980114981114982114983114984114985114986114987114988114989114990114991114992114993114994114995114996114997114998114999115000115001115002115003115004115005115006115007115008115009115010115011115012115013115014115015115016115017115018115019115020115021115022115023115024115025115026115027115028115029115030115031115032115033115034115035115036115037115038115039115040115041115042115043115044115045115046115047115048115049115050115051115052115053115054115055115056115057115058115059115060115061115062115063115064115065115066115067115068115069115070115071115072115073115074115075115076115077115078115079115080115081115082115083115084115085115086115087115088115089115090115091115092115093115094115095115096115097115098115099115100115101115102115103115104115105115106115107115108115109115110115111115112115113115114115115115116115117115118115119115120115121115122115123115124115125115126115127115128115129115130115131115132115133115134115135115136115137115138115139115140115141115142115143115144115145115146115147115148115149115150115151115152115153115154115155115156115157115158115159115160115161115162115163115164115165115166115167115168115169115170115171115172115173115174115175115176115177115178115179115180115181115182115183115184115185115186115187115188115189115190115191115192115193115194115195115196115197115198115199115200115201115202115203115204115205115206115207115208115209115210115211115212115213115214115215115216115217115218115219115220115221115222115223115224115225115226115227115228115229115230115231115232115233115234115235115236115237115238115239115240115241115242115243115244115245115246115247115248115249115250115251115252115253115254115255115256115257115258115259115260115261115262115263115264115265115266115267115268115269115270115271115272115273115274115275115276115277115278115279115280115281115282115283115284115285115286115287115288115289115290115291115292115293115294115295115296115297115298115299115300115301115302115303115304115305115306115307115308115309115310115311115312115313115314115315115316115317115318115319115320115321115322115323115324115325115326115327115328115329115330115331115332115333115334115335115336115337115338115339115340115341115342115343115344115345115346115347115348115349115350115351115352115353115354115355115356115357115358115359115360115361115362115363115364115365115366115367115368115369115370115371115372115373115374115375115376115377115378115379115380115381115382115383115384115385115386115387115388115389115390115391115392115393115394115395115396115397115398115399115400115401115402115403115404115405115406115407115408115409115410115411115412115413115414115415115416115417115418115419115420115421115422115423115424115425115426115427115428115429115430115431115432115433115434115435115436115437115438115439115440115441115442115443115444115445115446115447115448115449115450115451115452115453115454115455115456115457115458115459115460115461115462115463115464115465115466115467115468115469115470115471115472115473115474115475115476115477115478115479115480115481115482115483115484115485115486115487115488115489115490115491115492115493115494115495115496115497115498115499115500115501115502115503115504115505115506115507115508115509115510115511115512115513115514115515115516115517115518115519115520115521115522115523115524115525115526115527115528115529115530115531115532115533115534115535115536115537115538115539115540115541115542115543115544115545115546115547115548115549115550115551115552115553115554115555115556115557115558115559115560115561115562115563115564115565115566115567115568115569115570115571115572115573115574115575115576115577115578115579115580115581115582115583115584115585115586115587115588115589115590115591115592115593115594115595115596115597115598115599115600115601115602115603115604115605115606115607115608115609115610115611115612115613115614115615115616115617115618115619115620115621115622115623115624115625115626115627115628115629115630115631115632115633115634115635115636115637115638115639115640115641115642115643115644115645115646115647115648115649115650115651115652115653115654115655115656115657115658115659115660115661115662115663115664115665115666115667115668115669115670115671115672115673115674115675115676115677115678115679115680115681115682115683115684115685115686115687115688115689115690115691115692115693115694115695115696115697115698115699115700115701115702115703115704115705115706115707115708115709115710115711115712115713115714115715115716115717115718115719115720115721115722115723115724115725115726115727115728115729115730115731115732115733115734115735115736115737115738115739115740115741115742115743115744115745115746115747115748115749115750115751115752115753115754115755115756115757115758115759115760115761115762115763115764115765115766115767115768115769115770115771115772115773115774115775115776115777115778115779115780115781115782115783115784115785115786115787115788115789115790115791115792115793115794115795115796115797115798115799115800115801115802115803115804115805115806115807115808115809115810115811115812115813115814115815115816115817115818115819115820115821115822115823115824115825115826115827115828115829115830115831115832115833115834115835115836115837115838115839115840115841115842115843115844115845115846115847115848115849115850115851115852115853115854115855115856115857115858115859115860115861115862115863115864115865115866115867115868115869115870115871115872115873115874115875115876115877115878115879115880115881115882115883115884115885115886115887115888115889115890115891115892115893115894115895115896115897115898115899115900115901115902115903115904115905115906115907115908115909115910115911115912115913115914115915115916115917115918115919115920115921115922115923115924115925115926115927115928115929115930115931115932115933115934115935115936115937115938115939115940115941115942115943115944115945115946115947115948115949115950115951115952115953115954115955115956115957115958115959115960115961115962115963115964115965115966115967115968115969115970115971115972115973115974115975115976115977115978115979115980115981115982115983115984115985115986115987115988115989115990115991115992115993115994115995115996115997115998115999116000116001116002116003116004116005116006116007116008116009116010116011116012116013116014116015116016116017116018116019116020116021116022116023116024116025116026116027116028116029116030116031116032116033116034116035116036116037116038116039116040116041116042116043116044116045116046116047116048116049116050116051116052116053116054116055116056116057116058116059116060116061116062116063116064116065116066116067116068116069116070116071116072116073116074116075116076116077116078116079116080116081116082116083116084116085116086116087116088116089116090116091116092116093116094116095116096116097116098116099116100116101116102116103116104116105116106116107116108116109116110116111116112116113116114116115116116116117116118116119116120116121116122116123116124116125116126116127116128116129116130116131116132116133116134116135116136116137116138116139116140116141116142116143116144116145116146116147116148116149116150116151116152116153116154116155116156116157116158116159116160116161116162116163116164116165116166116167116168116169116170116171116172116173116174116175116176116177116178116179116180116181116182116183116184116185116186116187116188116189116190116191116192116193116194116195116196116197116198116199116200116201116202116203116204116205116206116207116208116209116210116211116212116213116214116215116216116217116218116219116220116221116222116223116224116225116226116227116228116229116230116231116232116233116234116235116236116237116238116239116240116241116242116243116244116245116246116247116248116249116250116251116252116253116254116255116256116257116258116259116260116261116262116263116264116265116266116267116268116269116270116271116272116273116274116275116276116277116278116279116280116281116282116283116284116285116286116287116288116289116290116291116292116293116294116295116296116297116298116299116300116301116302116303116304116305116306116307116308116309116310116311116312116313116314116315116316116317116318116319116320116321116322116323116324116325116326116327116328116329116330116331116332116333116334116335116336116337116338116339116340116341116342116343116344116345116346116347116348116349116350116351116352116353116354116355116356116357116358116359116360116361116362116363116364116365116366116367116368116369116370116371116372116373116374116375116376116377116378116379116380116381116382116383116384116385116386116387116388116389116390116391116392116393116394116395116396116397116398116399116400116401116402116403116404116405116406116407116408116409116410116411116412116413116414116415116416116417116418116419116420116421116422116423116424116425116426116427116428116429116430116431116432116433116434116435116436116437116438116439116440116441116442116443116444116445116446116447116448116449116450116451116452116453116454116455116456116457116458116459116460116461116462116463116464116465116466116467116468116469116470116471116472116473116474116475116476116477116478116479116480116481116482116483116484116485116486116487116488116489116490116491116492116493116494116495116496116497116498116499116500116501116502116503116504116505116506116507116508116509116510116511116512116513116514116515116516116517116518116519116520116521116522116523116524116525116526116527116528116529116530116531116532116533116534116535116536116537116538116539116540116541116542116543116544116545116546116547116548116549116550116551116552116553116554116555116556116557116558116559116560116561116562116563116564116565116566116567116568116569116570116571116572116573116574116575116576116577116578116579116580116581116582116583116584116585116586116587116588116589116590116591116592116593116594116595116596116597116598116599116600116601116602116603116604116605116606116607116608116609116610116611116612116613116614116615116616116617116618116619116620116621116622116623116624116625116626116627116628116629116630116631116632116633116634116635116636116637116638116639116640116641116642116643116644116645116646116647116648116649116650116651116652116653116654116655116656116657116658116659116660116661116662116663116664116665116666116667116668116669116670116671116672116673116674116675116676116677116678116679116680116681116682116683116684116685116686116687116688116689116690116691116692116693116694116695116696116697116698116699116700116701116702116703116704116705116706116707116708116709116710116711116712116713116714116715116716116717116718116719116720116721116722116723116724116725116726116727116728116729116730116731116732116733116734116735116736116737116738116739116740116741116742116743116744116745116746116747116748116749116750116751116752116753116754116755116756116757116758116759116760116761116762116763116764116765116766116767116768116769116770116771116772116773116774116775116776116777116778116779116780116781116782116783116784116785116786116787116788116789116790116791116792116793116794116795116796116797116798116799116800116801116802116803116804116805116806116807116808116809116810116811116812116813116814116815116816116817116818116819116820116821116822116823116824116825116826116827116828116829116830116831116832116833116834116835116836116837116838116839116840116841116842116843116844116845116846116847116848116849116850116851116852116853116854116855116856116857116858116859116860116861116862116863116864116865116866116867116868116869116870116871116872116873116874116875116876116877116878116879116880116881116882116883116884116885116886116887116888116889116890116891116892116893116894116895116896116897116898116899116900116901116902116903116904116905116906116907116908116909116910116911116912116913116914116915116916116917116918116919116920116921116922116923116924116925116926116927116928116929116930116931116932116933116934116935116936116937116938116939116940116941116942116943116944116945116946116947116948116949116950116951116952116953116954116955116956116957116958116959116960116961116962116963116964116965116966116967116968116969116970116971116972116973116974116975116976116977116978116979116980116981116982116983116984116985116986116987116988116989116990116991116992116993116994116995116996116997116998116999117000117001117002117003117004117005117006117007117008117009117010117011117012117013117014117015117016117017117018117019117020117021117022117023117024117025117026117027117028117029117030117031117032117033117034117035117036117037117038117039117040117041117042117043117044117045117046117047117048117049117050117051117052117053117054117055117056117057117058117059117060117061117062117063117064117065117066117067117068117069117070117071117072117073117074117075117076117077117078117079117080117081117082117083117084117085117086117087117088117089117090117091117092117093117094117095117096117097117098117099117100117101117102117103117104117105117106117107117108117109117110117111117112117113117114117115117116117117117118117119117120117121117122117123117124117125117126117127117128117129117130117131117132117133117134117135117136117137117138117139117140117141117142117143117144117145117146117147117148117149117150117151117152117153117154117155117156117157117158117159117160117161117162117163117164117165117166117167117168117169117170117171117172117173117174117175117176117177117178117179117180117181117182117183117184117185117186117187117188117189117190117191117192117193117194117195117196117197117198117199117200117201117202117203117204117205117206117207117208117209117210117211117212117213117214117215117216117217117218117219117220117221117222117223117224117225117226117227117228117229117230117231117232117233117234117235117236117237117238117239117240117241117242117243117244117245117246117247117248117249117250117251117252117253117254117255117256117257117258117259117260117261117262117263117264117265117266117267117268117269117270117271117272117273117274117275117276117277117278117279117280117281117282117283117284117285117286117287117288117289117290117291117292117293117294117295117296117297117298117299117300117301117302117303117304117305117306117307117308117309117310117311117312117313117314117315117316117317117318117319117320117321117322117323117324117325117326117327117328117329117330117331117332117333117334117335117336117337117338117339117340117341117342117343117344117345117346117347117348117349117350117351117352117353117354117355117356117357117358117359117360117361117362117363117364117365117366117367117368117369117370117371117372117373117374117375117376117377117378117379117380117381117382117383117384117385117386117387117388117389117390117391117392117393117394117395117396117397117398117399117400117401117402117403117404117405117406117407117408117409117410117411117412117413117414117415117416117417117418117419117420117421117422117423117424117425117426117427117428117429117430117431117432117433117434117435117436117437117438117439117440117441117442117443117444117445117446117447117448117449117450117451117452117453117454117455117456117457117458117459117460117461117462117463117464117465117466117467117468117469117470117471117472117473117474117475117476117477117478117479117480117481117482117483117484117485117486117487117488117489117490117491117492117493117494117495117496117497117498117499117500117501117502117503117504117505117506117507117508117509117510117511117512117513117514117515117516117517117518117519117520117521117522117523117524117525117526117527117528117529117530117531117532117533117534117535117536117537117538117539117540117541117542117543117544117545117546117547117548117549117550117551117552117553117554117555117556117557117558117559117560117561117562117563117564117565117566117567117568117569117570117571117572117573117574117575117576117577117578117579117580117581117582117583117584117585117586117587117588117589117590117591117592117593117594117595117596117597117598117599117600117601117602117603117604117605117606117607117608117609117610117611117612117613117614117615117616117617117618117619117620117621117622117623117624117625117626117627117628117629117630117631117632117633117634117635117636117637117638117639117640117641117642117643117644117645117646
  1. var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};
  2. var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();
  3. var BABYLON;
  4. (function (BABYLON) {
  5. /**
  6. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  7. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  8. */
  9. var EffectFallbacks = /** @class */ (function () {
  10. function EffectFallbacks() {
  11. this._defines = {};
  12. this._currentRank = 32;
  13. this._maxRank = -1;
  14. }
  15. /**
  16. * Removes the fallback from the bound mesh.
  17. */
  18. EffectFallbacks.prototype.unBindMesh = function () {
  19. this._mesh = null;
  20. };
  21. /**
  22. * Adds a fallback on the specified property.
  23. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  24. * @param define The name of the define in the shader
  25. */
  26. EffectFallbacks.prototype.addFallback = function (rank, define) {
  27. if (!this._defines[rank]) {
  28. if (rank < this._currentRank) {
  29. this._currentRank = rank;
  30. }
  31. if (rank > this._maxRank) {
  32. this._maxRank = rank;
  33. }
  34. this._defines[rank] = new Array();
  35. }
  36. this._defines[rank].push(define);
  37. };
  38. /**
  39. * Sets the mesh to use CPU skinning when needing to fallback.
  40. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  41. * @param mesh The mesh to use the fallbacks.
  42. */
  43. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  44. this._mesh = mesh;
  45. if (rank < this._currentRank) {
  46. this._currentRank = rank;
  47. }
  48. if (rank > this._maxRank) {
  49. this._maxRank = rank;
  50. }
  51. };
  52. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  53. /**
  54. * Checks to see if more fallbacks are still availible.
  55. */
  56. get: function () {
  57. return this._currentRank <= this._maxRank;
  58. },
  59. enumerable: true,
  60. configurable: true
  61. });
  62. /**
  63. * Removes the defines that shoould be removed when falling back.
  64. * @param currentDefines defines the current define statements for the shader.
  65. * @param effect defines the current effect we try to compile
  66. * @returns The resulting defines with defines of the current rank removed.
  67. */
  68. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  69. // First we try to switch to CPU skinning
  70. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  71. this._mesh.computeBonesUsingShaders = false;
  72. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  73. effect._bonesComputationForcedToCPU = true;
  74. var scene = this._mesh.getScene();
  75. for (var index = 0; index < scene.meshes.length; index++) {
  76. var otherMesh = scene.meshes[index];
  77. if (!otherMesh.material) {
  78. continue;
  79. }
  80. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  81. continue;
  82. }
  83. if (otherMesh.material.getEffect() === effect) {
  84. otherMesh.computeBonesUsingShaders = false;
  85. }
  86. else if (otherMesh.subMeshes) {
  87. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  88. var subMesh = _a[_i];
  89. var subMeshEffect = subMesh.effect;
  90. if (subMeshEffect === effect) {
  91. otherMesh.computeBonesUsingShaders = false;
  92. break;
  93. }
  94. }
  95. }
  96. }
  97. }
  98. else {
  99. var currentFallbacks = this._defines[this._currentRank];
  100. if (currentFallbacks) {
  101. for (var index = 0; index < currentFallbacks.length; index++) {
  102. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  103. }
  104. }
  105. this._currentRank++;
  106. }
  107. return currentDefines;
  108. };
  109. return EffectFallbacks;
  110. }());
  111. BABYLON.EffectFallbacks = EffectFallbacks;
  112. /**
  113. * Options to be used when creating an effect.
  114. */
  115. var EffectCreationOptions = /** @class */ (function () {
  116. function EffectCreationOptions() {
  117. }
  118. return EffectCreationOptions;
  119. }());
  120. BABYLON.EffectCreationOptions = EffectCreationOptions;
  121. /**
  122. * Effect containing vertex and fragment shader that can be executed on an object.
  123. */
  124. var Effect = /** @class */ (function () {
  125. /**
  126. * Instantiates an effect.
  127. * An effect can be used to create/manage/execute vertex and fragment shaders.
  128. * @param baseName Name of the effect.
  129. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  130. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  131. * @param samplers List of sampler variables that will be passed to the shader.
  132. * @param engine Engine to be used to render the effect
  133. * @param defines Define statements to be added to the shader.
  134. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  135. * @param onCompiled Callback that will be called when the shader is compiled.
  136. * @param onError Callback that will be called if an error occurs during shader compilation.
  137. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  138. */
  139. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  140. if (samplers === void 0) { samplers = null; }
  141. if (defines === void 0) { defines = null; }
  142. if (fallbacks === void 0) { fallbacks = null; }
  143. if (onCompiled === void 0) { onCompiled = null; }
  144. if (onError === void 0) { onError = null; }
  145. var _this = this;
  146. /**
  147. * Unique ID of the effect.
  148. */
  149. this.uniqueId = 0;
  150. /**
  151. * Observable that will be called when the shader is compiled.
  152. */
  153. this.onCompileObservable = new BABYLON.Observable();
  154. /**
  155. * Observable that will be called if an error occurs during shader compilation.
  156. */
  157. this.onErrorObservable = new BABYLON.Observable();
  158. /** @hidden */
  159. this._bonesComputationForcedToCPU = false;
  160. this._uniformBuffersNames = {};
  161. this._isReady = false;
  162. this._compilationError = "";
  163. this.name = baseName;
  164. if (attributesNamesOrOptions.attributes) {
  165. var options = attributesNamesOrOptions;
  166. this._engine = uniformsNamesOrEngine;
  167. this._attributesNames = options.attributes;
  168. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  169. this._samplers = options.samplers.slice();
  170. this.defines = options.defines;
  171. this.onError = options.onError;
  172. this.onCompiled = options.onCompiled;
  173. this._fallbacks = options.fallbacks;
  174. this._indexParameters = options.indexParameters;
  175. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  176. if (options.uniformBuffersNames) {
  177. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  178. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  179. }
  180. }
  181. }
  182. else {
  183. this._engine = engine;
  184. this.defines = defines;
  185. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  186. this._samplers = samplers ? samplers.slice() : [];
  187. this._attributesNames = attributesNamesOrOptions;
  188. this.onError = onError;
  189. this.onCompiled = onCompiled;
  190. this._indexParameters = indexParameters;
  191. this._fallbacks = fallbacks;
  192. }
  193. this.uniqueId = Effect._uniqueIdSeed++;
  194. var vertexSource;
  195. var fragmentSource;
  196. if (baseName.vertexElement) {
  197. vertexSource = document.getElementById(baseName.vertexElement);
  198. if (!vertexSource) {
  199. vertexSource = baseName.vertexElement;
  200. }
  201. }
  202. else {
  203. vertexSource = baseName.vertex || baseName;
  204. }
  205. if (baseName.fragmentElement) {
  206. fragmentSource = document.getElementById(baseName.fragmentElement);
  207. if (!fragmentSource) {
  208. fragmentSource = baseName.fragmentElement;
  209. }
  210. }
  211. else {
  212. fragmentSource = baseName.fragment || baseName;
  213. }
  214. this._loadVertexShader(vertexSource, function (vertexCode) {
  215. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  216. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  217. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  218. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  219. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  220. if (baseName) {
  221. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  222. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  223. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  224. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  225. }
  226. else {
  227. _this._vertexSourceCode = migratedVertexCode;
  228. _this._fragmentSourceCode = migratedFragmentCode;
  229. }
  230. _this._prepareEffect();
  231. });
  232. });
  233. });
  234. });
  235. });
  236. });
  237. }
  238. Object.defineProperty(Effect.prototype, "onBindObservable", {
  239. /**
  240. * Observable that will be called when effect is bound.
  241. */
  242. get: function () {
  243. if (!this._onBindObservable) {
  244. this._onBindObservable = new BABYLON.Observable();
  245. }
  246. return this._onBindObservable;
  247. },
  248. enumerable: true,
  249. configurable: true
  250. });
  251. Object.defineProperty(Effect.prototype, "key", {
  252. /**
  253. * Unique key for this effect
  254. */
  255. get: function () {
  256. return this._key;
  257. },
  258. enumerable: true,
  259. configurable: true
  260. });
  261. /**
  262. * If the effect has been compiled and prepared.
  263. * @returns if the effect is compiled and prepared.
  264. */
  265. Effect.prototype.isReady = function () {
  266. return this._isReady;
  267. };
  268. /**
  269. * The engine the effect was initialized with.
  270. * @returns the engine.
  271. */
  272. Effect.prototype.getEngine = function () {
  273. return this._engine;
  274. };
  275. /**
  276. * The compiled webGL program for the effect
  277. * @returns the webGL program.
  278. */
  279. Effect.prototype.getProgram = function () {
  280. return this._program;
  281. };
  282. /**
  283. * The set of names of attribute variables for the shader.
  284. * @returns An array of attribute names.
  285. */
  286. Effect.prototype.getAttributesNames = function () {
  287. return this._attributesNames;
  288. };
  289. /**
  290. * Returns the attribute at the given index.
  291. * @param index The index of the attribute.
  292. * @returns The location of the attribute.
  293. */
  294. Effect.prototype.getAttributeLocation = function (index) {
  295. return this._attributes[index];
  296. };
  297. /**
  298. * Returns the attribute based on the name of the variable.
  299. * @param name of the attribute to look up.
  300. * @returns the attribute location.
  301. */
  302. Effect.prototype.getAttributeLocationByName = function (name) {
  303. var index = this._attributesNames.indexOf(name);
  304. return this._attributes[index];
  305. };
  306. /**
  307. * The number of attributes.
  308. * @returns the numnber of attributes.
  309. */
  310. Effect.prototype.getAttributesCount = function () {
  311. return this._attributes.length;
  312. };
  313. /**
  314. * Gets the index of a uniform variable.
  315. * @param uniformName of the uniform to look up.
  316. * @returns the index.
  317. */
  318. Effect.prototype.getUniformIndex = function (uniformName) {
  319. return this._uniformsNames.indexOf(uniformName);
  320. };
  321. /**
  322. * Returns the attribute based on the name of the variable.
  323. * @param uniformName of the uniform to look up.
  324. * @returns the location of the uniform.
  325. */
  326. Effect.prototype.getUniform = function (uniformName) {
  327. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  328. };
  329. /**
  330. * Returns an array of sampler variable names
  331. * @returns The array of sampler variable neames.
  332. */
  333. Effect.prototype.getSamplers = function () {
  334. return this._samplers;
  335. };
  336. /**
  337. * The error from the last compilation.
  338. * @returns the error string.
  339. */
  340. Effect.prototype.getCompilationError = function () {
  341. return this._compilationError;
  342. };
  343. /**
  344. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  345. * @param func The callback to be used.
  346. */
  347. Effect.prototype.executeWhenCompiled = function (func) {
  348. if (this.isReady()) {
  349. func(this);
  350. return;
  351. }
  352. this.onCompileObservable.add(function (effect) {
  353. func(effect);
  354. });
  355. };
  356. /** @hidden */
  357. Effect.prototype._loadVertexShader = function (vertex, callback) {
  358. if (BABYLON.Tools.IsWindowObjectExist()) {
  359. // DOM element ?
  360. if (vertex instanceof HTMLElement) {
  361. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  362. callback(vertexCode);
  363. return;
  364. }
  365. }
  366. // Base64 encoded ?
  367. if (vertex.substr(0, 7) === "base64:") {
  368. var vertexBinary = window.atob(vertex.substr(7));
  369. callback(vertexBinary);
  370. return;
  371. }
  372. // Is in local store ?
  373. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  374. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  375. return;
  376. }
  377. var vertexShaderUrl;
  378. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  379. vertexShaderUrl = vertex;
  380. }
  381. else {
  382. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  383. }
  384. // Vertex shader
  385. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  386. };
  387. /** @hidden */
  388. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  389. if (BABYLON.Tools.IsWindowObjectExist()) {
  390. // DOM element ?
  391. if (fragment instanceof HTMLElement) {
  392. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  393. callback(fragmentCode);
  394. return;
  395. }
  396. }
  397. // Base64 encoded ?
  398. if (fragment.substr(0, 7) === "base64:") {
  399. var fragmentBinary = window.atob(fragment.substr(7));
  400. callback(fragmentBinary);
  401. return;
  402. }
  403. // Is in local store ?
  404. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  405. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  406. return;
  407. }
  408. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  409. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  410. return;
  411. }
  412. var fragmentShaderUrl;
  413. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  414. fragmentShaderUrl = fragment;
  415. }
  416. else {
  417. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  418. }
  419. // Fragment shader
  420. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  421. };
  422. /** @hidden */
  423. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  424. // Rebuild shaders source code
  425. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  426. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  427. vertexCode = prefix + vertexCode;
  428. fragmentCode = prefix + fragmentCode;
  429. // Number lines of shaders source code
  430. var i = 2;
  431. var regex = /\n/gm;
  432. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  433. i = 2;
  434. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  435. // Dump shaders name and formatted source code
  436. if (this.name.vertexElement) {
  437. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  438. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  439. }
  440. else if (this.name.vertex) {
  441. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  442. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  443. }
  444. else {
  445. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  446. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  447. }
  448. };
  449. ;
  450. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  451. var preparedSourceCode = this._processPrecision(sourceCode);
  452. if (this._engine.webGLVersion == 1) {
  453. callback(preparedSourceCode);
  454. return;
  455. }
  456. // Already converted
  457. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  458. callback(preparedSourceCode.replace("#version 300 es", ""));
  459. return;
  460. }
  461. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  462. // Remove extensions
  463. // #extension GL_OES_standard_derivatives : enable
  464. // #extension GL_EXT_shader_texture_lod : enable
  465. // #extension GL_EXT_frag_depth : enable
  466. // #extension GL_EXT_draw_buffers : require
  467. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  468. var result = preparedSourceCode.replace(regex, "");
  469. // Migrate to GLSL v300
  470. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  471. result = result.replace(/attribute[ \t]/g, "in ");
  472. result = result.replace(/[ \t]attribute/g, " in");
  473. if (isFragment) {
  474. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  475. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  476. result = result.replace(/texture2D\s*\(/g, "texture(");
  477. result = result.replace(/textureCube\s*\(/g, "texture(");
  478. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  479. result = result.replace(/gl_FragColor/g, "glFragColor");
  480. result = result.replace(/gl_FragData/g, "glFragData");
  481. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  482. }
  483. callback(result);
  484. };
  485. Effect.prototype._processIncludes = function (sourceCode, callback) {
  486. var _this = this;
  487. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  488. var match = regex.exec(sourceCode);
  489. var returnValue = new String(sourceCode);
  490. while (match != null) {
  491. var includeFile = match[1];
  492. // Uniform declaration
  493. if (includeFile.indexOf("__decl__") !== -1) {
  494. includeFile = includeFile.replace(/__decl__/, "");
  495. if (this._engine.supportsUniformBuffers) {
  496. includeFile = includeFile.replace(/Vertex/, "Ubo");
  497. includeFile = includeFile.replace(/Fragment/, "Ubo");
  498. }
  499. includeFile = includeFile + "Declaration";
  500. }
  501. if (Effect.IncludesShadersStore[includeFile]) {
  502. // Substitution
  503. var includeContent = Effect.IncludesShadersStore[includeFile];
  504. if (match[2]) {
  505. var splits = match[3].split(",");
  506. for (var index = 0; index < splits.length; index += 2) {
  507. var source = new RegExp(splits[index], "g");
  508. var dest = splits[index + 1];
  509. includeContent = includeContent.replace(source, dest);
  510. }
  511. }
  512. if (match[4]) {
  513. var indexString = match[5];
  514. if (indexString.indexOf("..") !== -1) {
  515. var indexSplits = indexString.split("..");
  516. var minIndex = parseInt(indexSplits[0]);
  517. var maxIndex = parseInt(indexSplits[1]);
  518. var sourceIncludeContent = includeContent.slice(0);
  519. includeContent = "";
  520. if (isNaN(maxIndex)) {
  521. maxIndex = this._indexParameters[indexSplits[1]];
  522. }
  523. for (var i = minIndex; i < maxIndex; i++) {
  524. if (!this._engine.supportsUniformBuffers) {
  525. // Ubo replacement
  526. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  527. return p1 + "{X}";
  528. });
  529. }
  530. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  531. }
  532. }
  533. else {
  534. if (!this._engine.supportsUniformBuffers) {
  535. // Ubo replacement
  536. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  537. return p1 + "{X}";
  538. });
  539. }
  540. includeContent = includeContent.replace(/\{X\}/g, indexString);
  541. }
  542. }
  543. // Replace
  544. returnValue = returnValue.replace(match[0], includeContent);
  545. }
  546. else {
  547. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  548. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  549. Effect.IncludesShadersStore[includeFile] = fileContent;
  550. _this._processIncludes(returnValue, callback);
  551. });
  552. return;
  553. }
  554. match = regex.exec(sourceCode);
  555. }
  556. callback(returnValue);
  557. };
  558. Effect.prototype._processPrecision = function (source) {
  559. if (source.indexOf("precision highp float") === -1) {
  560. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  561. source = "precision mediump float;\n" + source;
  562. }
  563. else {
  564. source = "precision highp float;\n" + source;
  565. }
  566. }
  567. else {
  568. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  569. source = source.replace("precision highp float", "precision mediump float");
  570. }
  571. }
  572. return source;
  573. };
  574. /**
  575. * Recompiles the webGL program
  576. * @param vertexSourceCode The source code for the vertex shader.
  577. * @param fragmentSourceCode The source code for the fragment shader.
  578. * @param onCompiled Callback called when completed.
  579. * @param onError Callback called on error.
  580. * @hidden
  581. */
  582. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  583. var _this = this;
  584. this._isReady = false;
  585. this._vertexSourceCodeOverride = vertexSourceCode;
  586. this._fragmentSourceCodeOverride = fragmentSourceCode;
  587. this.onError = function (effect, error) {
  588. if (onError) {
  589. onError(error);
  590. }
  591. };
  592. this.onCompiled = function () {
  593. var scenes = _this.getEngine().scenes;
  594. for (var i = 0; i < scenes.length; i++) {
  595. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  596. }
  597. if (onCompiled) {
  598. onCompiled(_this._program);
  599. }
  600. };
  601. this._fallbacks = null;
  602. this._prepareEffect();
  603. };
  604. /**
  605. * Gets the uniform locations of the the specified variable names
  606. * @param names THe names of the variables to lookup.
  607. * @returns Array of locations in the same order as variable names.
  608. */
  609. Effect.prototype.getSpecificUniformLocations = function (names) {
  610. var engine = this._engine;
  611. return engine.getUniforms(this._program, names);
  612. };
  613. /**
  614. * Prepares the effect
  615. * @hidden
  616. */
  617. Effect.prototype._prepareEffect = function () {
  618. var attributesNames = this._attributesNames;
  619. var defines = this.defines;
  620. var fallbacks = this._fallbacks;
  621. this._valueCache = {};
  622. var previousProgram = this._program;
  623. try {
  624. var engine = this._engine;
  625. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  626. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  627. }
  628. else {
  629. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  630. }
  631. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  632. if (engine.supportsUniformBuffers) {
  633. for (var name in this._uniformBuffersNames) {
  634. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  635. }
  636. }
  637. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  638. this._attributes = engine.getAttributes(this._program, attributesNames);
  639. var index;
  640. for (index = 0; index < this._samplers.length; index++) {
  641. var sampler = this.getUniform(this._samplers[index]);
  642. if (sampler == null) {
  643. this._samplers.splice(index, 1);
  644. index--;
  645. }
  646. }
  647. engine.bindSamplers(this);
  648. this._compilationError = "";
  649. this._isReady = true;
  650. if (this.onCompiled) {
  651. this.onCompiled(this);
  652. }
  653. this.onCompileObservable.notifyObservers(this);
  654. this.onCompileObservable.clear();
  655. // Unbind mesh reference in fallbacks
  656. if (this._fallbacks) {
  657. this._fallbacks.unBindMesh();
  658. }
  659. if (previousProgram) {
  660. this.getEngine()._deleteProgram(previousProgram);
  661. }
  662. }
  663. catch (e) {
  664. this._compilationError = e.message;
  665. // Let's go through fallbacks then
  666. BABYLON.Tools.Error("Unable to compile effect:");
  667. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  668. return " " + uniform;
  669. }));
  670. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  671. return " " + attribute;
  672. }));
  673. BABYLON.Tools.Error("Error: " + this._compilationError);
  674. if (previousProgram) {
  675. this._program = previousProgram;
  676. this._isReady = true;
  677. if (this.onError) {
  678. this.onError(this, this._compilationError);
  679. }
  680. this.onErrorObservable.notifyObservers(this);
  681. }
  682. if (fallbacks && fallbacks.isMoreFallbacks) {
  683. BABYLON.Tools.Error("Trying next fallback.");
  684. this.defines = fallbacks.reduce(this.defines, this);
  685. this._prepareEffect();
  686. }
  687. else { // Sorry we did everything we can
  688. if (this.onError) {
  689. this.onError(this, this._compilationError);
  690. }
  691. this.onErrorObservable.notifyObservers(this);
  692. this.onErrorObservable.clear();
  693. // Unbind mesh reference in fallbacks
  694. if (this._fallbacks) {
  695. this._fallbacks.unBindMesh();
  696. }
  697. }
  698. }
  699. };
  700. Object.defineProperty(Effect.prototype, "isSupported", {
  701. /**
  702. * Checks if the effect is supported. (Must be called after compilation)
  703. */
  704. get: function () {
  705. return this._compilationError === "";
  706. },
  707. enumerable: true,
  708. configurable: true
  709. });
  710. /**
  711. * Binds a texture to the engine to be used as output of the shader.
  712. * @param channel Name of the output variable.
  713. * @param texture Texture to bind.
  714. * @hidden
  715. */
  716. Effect.prototype._bindTexture = function (channel, texture) {
  717. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  718. };
  719. /**
  720. * Sets a texture on the engine to be used in the shader.
  721. * @param channel Name of the sampler variable.
  722. * @param texture Texture to set.
  723. */
  724. Effect.prototype.setTexture = function (channel, texture) {
  725. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  726. };
  727. /**
  728. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  729. * @param channel Name of the sampler variable.
  730. * @param texture Texture to set.
  731. */
  732. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  733. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  734. };
  735. /**
  736. * Sets an array of textures on the engine to be used in the shader.
  737. * @param channel Name of the variable.
  738. * @param textures Textures to set.
  739. */
  740. Effect.prototype.setTextureArray = function (channel, textures) {
  741. if (this._samplers.indexOf(channel + "Ex") === -1) {
  742. var initialPos = this._samplers.indexOf(channel);
  743. for (var index = 1; index < textures.length; index++) {
  744. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  745. }
  746. }
  747. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  748. };
  749. /**
  750. * Sets a texture to be the input of the specified post process. (To use the output, pass in the next post process in the pipeline)
  751. * @param channel Name of the sampler variable.
  752. * @param postProcess Post process to get the input texture from.
  753. */
  754. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  755. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  756. };
  757. /**
  758. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  759. * Sets the input texture of the passed in post process to be input of this effect. (To use the output of the passed in post process use setTextureFromPostProcessOutput)
  760. * @param channel Name of the sampler variable.
  761. * @param postProcess Post process to get the output texture from.
  762. */
  763. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  764. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  765. };
  766. /** @hidden */
  767. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  768. var cache = this._valueCache[uniformName];
  769. var flag = matrix.updateFlag;
  770. if (cache !== undefined && cache === flag) {
  771. return false;
  772. }
  773. this._valueCache[uniformName] = flag;
  774. return true;
  775. };
  776. /** @hidden */
  777. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  778. var cache = this._valueCache[uniformName];
  779. if (!cache) {
  780. cache = [x, y];
  781. this._valueCache[uniformName] = cache;
  782. return true;
  783. }
  784. var changed = false;
  785. if (cache[0] !== x) {
  786. cache[0] = x;
  787. changed = true;
  788. }
  789. if (cache[1] !== y) {
  790. cache[1] = y;
  791. changed = true;
  792. }
  793. return changed;
  794. };
  795. /** @hidden */
  796. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  797. var cache = this._valueCache[uniformName];
  798. if (!cache) {
  799. cache = [x, y, z];
  800. this._valueCache[uniformName] = cache;
  801. return true;
  802. }
  803. var changed = false;
  804. if (cache[0] !== x) {
  805. cache[0] = x;
  806. changed = true;
  807. }
  808. if (cache[1] !== y) {
  809. cache[1] = y;
  810. changed = true;
  811. }
  812. if (cache[2] !== z) {
  813. cache[2] = z;
  814. changed = true;
  815. }
  816. return changed;
  817. };
  818. /** @hidden */
  819. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  820. var cache = this._valueCache[uniformName];
  821. if (!cache) {
  822. cache = [x, y, z, w];
  823. this._valueCache[uniformName] = cache;
  824. return true;
  825. }
  826. var changed = false;
  827. if (cache[0] !== x) {
  828. cache[0] = x;
  829. changed = true;
  830. }
  831. if (cache[1] !== y) {
  832. cache[1] = y;
  833. changed = true;
  834. }
  835. if (cache[2] !== z) {
  836. cache[2] = z;
  837. changed = true;
  838. }
  839. if (cache[3] !== w) {
  840. cache[3] = w;
  841. changed = true;
  842. }
  843. return changed;
  844. };
  845. /**
  846. * Binds a buffer to a uniform.
  847. * @param buffer Buffer to bind.
  848. * @param name Name of the uniform variable to bind to.
  849. */
  850. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  851. var bufferName = this._uniformBuffersNames[name];
  852. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  853. return;
  854. }
  855. Effect._baseCache[bufferName] = buffer;
  856. this._engine.bindUniformBufferBase(buffer, bufferName);
  857. };
  858. /**
  859. * Binds block to a uniform.
  860. * @param blockName Name of the block to bind.
  861. * @param index Index to bind.
  862. */
  863. Effect.prototype.bindUniformBlock = function (blockName, index) {
  864. this._engine.bindUniformBlock(this._program, blockName, index);
  865. };
  866. /**
  867. * Sets an interger value on a uniform variable.
  868. * @param uniformName Name of the variable.
  869. * @param value Value to be set.
  870. * @returns this effect.
  871. */
  872. Effect.prototype.setInt = function (uniformName, value) {
  873. var cache = this._valueCache[uniformName];
  874. if (cache !== undefined && cache === value)
  875. return this;
  876. this._valueCache[uniformName] = value;
  877. this._engine.setInt(this.getUniform(uniformName), value);
  878. return this;
  879. };
  880. /**
  881. * Sets an int array on a uniform variable.
  882. * @param uniformName Name of the variable.
  883. * @param array array to be set.
  884. * @returns this effect.
  885. */
  886. Effect.prototype.setIntArray = function (uniformName, array) {
  887. this._valueCache[uniformName] = null;
  888. this._engine.setIntArray(this.getUniform(uniformName), array);
  889. return this;
  890. };
  891. /**
  892. * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  893. * @param uniformName Name of the variable.
  894. * @param array array to be set.
  895. * @returns this effect.
  896. */
  897. Effect.prototype.setIntArray2 = function (uniformName, array) {
  898. this._valueCache[uniformName] = null;
  899. this._engine.setIntArray2(this.getUniform(uniformName), array);
  900. return this;
  901. };
  902. /**
  903. * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  904. * @param uniformName Name of the variable.
  905. * @param array array to be set.
  906. * @returns this effect.
  907. */
  908. Effect.prototype.setIntArray3 = function (uniformName, array) {
  909. this._valueCache[uniformName] = null;
  910. this._engine.setIntArray3(this.getUniform(uniformName), array);
  911. return this;
  912. };
  913. /**
  914. * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  915. * @param uniformName Name of the variable.
  916. * @param array array to be set.
  917. * @returns this effect.
  918. */
  919. Effect.prototype.setIntArray4 = function (uniformName, array) {
  920. this._valueCache[uniformName] = null;
  921. this._engine.setIntArray4(this.getUniform(uniformName), array);
  922. return this;
  923. };
  924. /**
  925. * Sets an float array on a uniform variable.
  926. * @param uniformName Name of the variable.
  927. * @param array array to be set.
  928. * @returns this effect.
  929. */
  930. Effect.prototype.setFloatArray = function (uniformName, array) {
  931. this._valueCache[uniformName] = null;
  932. this._engine.setFloatArray(this.getUniform(uniformName), array);
  933. return this;
  934. };
  935. /**
  936. * Sets an float array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  937. * @param uniformName Name of the variable.
  938. * @param array array to be set.
  939. * @returns this effect.
  940. */
  941. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  942. this._valueCache[uniformName] = null;
  943. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  944. return this;
  945. };
  946. /**
  947. * Sets an float array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  948. * @param uniformName Name of the variable.
  949. * @param array array to be set.
  950. * @returns this effect.
  951. */
  952. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  953. this._valueCache[uniformName] = null;
  954. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  955. return this;
  956. };
  957. /**
  958. * Sets an float array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  959. * @param uniformName Name of the variable.
  960. * @param array array to be set.
  961. * @returns this effect.
  962. */
  963. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  964. this._valueCache[uniformName] = null;
  965. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  966. return this;
  967. };
  968. /**
  969. * Sets an array on a uniform variable.
  970. * @param uniformName Name of the variable.
  971. * @param array array to be set.
  972. * @returns this effect.
  973. */
  974. Effect.prototype.setArray = function (uniformName, array) {
  975. this._valueCache[uniformName] = null;
  976. this._engine.setArray(this.getUniform(uniformName), array);
  977. return this;
  978. };
  979. /**
  980. * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  981. * @param uniformName Name of the variable.
  982. * @param array array to be set.
  983. * @returns this effect.
  984. */
  985. Effect.prototype.setArray2 = function (uniformName, array) {
  986. this._valueCache[uniformName] = null;
  987. this._engine.setArray2(this.getUniform(uniformName), array);
  988. return this;
  989. };
  990. /**
  991. * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  992. * @param uniformName Name of the variable.
  993. * @param array array to be set.
  994. * @returns this effect.
  995. */
  996. Effect.prototype.setArray3 = function (uniformName, array) {
  997. this._valueCache[uniformName] = null;
  998. this._engine.setArray3(this.getUniform(uniformName), array);
  999. return this;
  1000. };
  1001. /**
  1002. * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  1003. * @param uniformName Name of the variable.
  1004. * @param array array to be set.
  1005. * @returns this effect.
  1006. */
  1007. Effect.prototype.setArray4 = function (uniformName, array) {
  1008. this._valueCache[uniformName] = null;
  1009. this._engine.setArray4(this.getUniform(uniformName), array);
  1010. return this;
  1011. };
  1012. /**
  1013. * Sets matrices on a uniform variable.
  1014. * @param uniformName Name of the variable.
  1015. * @param matrices matrices to be set.
  1016. * @returns this effect.
  1017. */
  1018. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1019. if (!matrices) {
  1020. return this;
  1021. }
  1022. this._valueCache[uniformName] = null;
  1023. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1024. return this;
  1025. };
  1026. /**
  1027. * Sets matrix on a uniform variable.
  1028. * @param uniformName Name of the variable.
  1029. * @param matrix matrix to be set.
  1030. * @returns this effect.
  1031. */
  1032. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1033. if (this._cacheMatrix(uniformName, matrix)) {
  1034. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1035. }
  1036. return this;
  1037. };
  1038. /**
  1039. * Sets a 3x3 matrix on a uniform variable. (Speicified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix)
  1040. * @param uniformName Name of the variable.
  1041. * @param matrix matrix to be set.
  1042. * @returns this effect.
  1043. */
  1044. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1045. this._valueCache[uniformName] = null;
  1046. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1047. return this;
  1048. };
  1049. /**
  1050. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1051. * @param uniformName Name of the variable.
  1052. * @param matrix matrix to be set.
  1053. * @returns this effect.
  1054. */
  1055. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1056. this._valueCache[uniformName] = null;
  1057. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1058. return this;
  1059. };
  1060. /**
  1061. * Sets a float on a uniform variable.
  1062. * @param uniformName Name of the variable.
  1063. * @param value value to be set.
  1064. * @returns this effect.
  1065. */
  1066. Effect.prototype.setFloat = function (uniformName, value) {
  1067. var cache = this._valueCache[uniformName];
  1068. if (cache !== undefined && cache === value)
  1069. return this;
  1070. this._valueCache[uniformName] = value;
  1071. this._engine.setFloat(this.getUniform(uniformName), value);
  1072. return this;
  1073. };
  1074. /**
  1075. * Sets a boolean on a uniform variable.
  1076. * @param uniformName Name of the variable.
  1077. * @param bool value to be set.
  1078. * @returns this effect.
  1079. */
  1080. Effect.prototype.setBool = function (uniformName, bool) {
  1081. var cache = this._valueCache[uniformName];
  1082. if (cache !== undefined && cache === bool)
  1083. return this;
  1084. this._valueCache[uniformName] = bool;
  1085. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1086. return this;
  1087. };
  1088. /**
  1089. * Sets a Vector2 on a uniform variable.
  1090. * @param uniformName Name of the variable.
  1091. * @param vector2 vector2 to be set.
  1092. * @returns this effect.
  1093. */
  1094. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1095. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1096. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1097. }
  1098. return this;
  1099. };
  1100. /**
  1101. * Sets a float2 on a uniform variable.
  1102. * @param uniformName Name of the variable.
  1103. * @param x First float in float2.
  1104. * @param y Second float in float2.
  1105. * @returns this effect.
  1106. */
  1107. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1108. if (this._cacheFloat2(uniformName, x, y)) {
  1109. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1110. }
  1111. return this;
  1112. };
  1113. /**
  1114. * Sets a Vector3 on a uniform variable.
  1115. * @param uniformName Name of the variable.
  1116. * @param vector3 Value to be set.
  1117. * @returns this effect.
  1118. */
  1119. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1120. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1121. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1122. }
  1123. return this;
  1124. };
  1125. /**
  1126. * Sets a float3 on a uniform variable.
  1127. * @param uniformName Name of the variable.
  1128. * @param x First float in float3.
  1129. * @param y Second float in float3.
  1130. * @param z Third float in float3.
  1131. * @returns this effect.
  1132. */
  1133. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1134. if (this._cacheFloat3(uniformName, x, y, z)) {
  1135. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1136. }
  1137. return this;
  1138. };
  1139. /**
  1140. * Sets a Vector4 on a uniform variable.
  1141. * @param uniformName Name of the variable.
  1142. * @param vector4 Value to be set.
  1143. * @returns this effect.
  1144. */
  1145. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1146. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1147. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1148. }
  1149. return this;
  1150. };
  1151. /**
  1152. * Sets a float4 on a uniform variable.
  1153. * @param uniformName Name of the variable.
  1154. * @param x First float in float4.
  1155. * @param y Second float in float4.
  1156. * @param z Third float in float4.
  1157. * @param w Fourth float in float4.
  1158. * @returns this effect.
  1159. */
  1160. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1161. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1162. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1163. }
  1164. return this;
  1165. };
  1166. /**
  1167. * Sets a Color3 on a uniform variable.
  1168. * @param uniformName Name of the variable.
  1169. * @param color3 Value to be set.
  1170. * @returns this effect.
  1171. */
  1172. Effect.prototype.setColor3 = function (uniformName, color3) {
  1173. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1174. this._engine.setColor3(this.getUniform(uniformName), color3);
  1175. }
  1176. return this;
  1177. };
  1178. /**
  1179. * Sets a Color4 on a uniform variable.
  1180. * @param uniformName Name of the variable.
  1181. * @param color3 Value to be set.
  1182. * @param alpha Alpha value to be set.
  1183. * @returns this effect.
  1184. */
  1185. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1186. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1187. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1188. }
  1189. return this;
  1190. };
  1191. /**
  1192. * Sets a Color4 on a uniform variable
  1193. * @param uniformName defines the name of the variable
  1194. * @param color4 defines the value to be set
  1195. * @returns this effect.
  1196. */
  1197. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1198. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1199. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1200. }
  1201. return this;
  1202. };
  1203. /**
  1204. * This function will add a new shader to the shader store
  1205. * @param name the name of the shader
  1206. * @param pixelShader optional pixel shader content
  1207. * @param vertexShader optional vertex shader content
  1208. */
  1209. Effect.RegisterShader = function (name, pixelShader, vertexShader) {
  1210. if (pixelShader) {
  1211. Effect.ShadersStore[name + "PixelShader"] = pixelShader;
  1212. }
  1213. if (vertexShader) {
  1214. Effect.ShadersStore[name + "VertexShader"] = vertexShader;
  1215. }
  1216. };
  1217. /**
  1218. * Resets the cache of effects.
  1219. */
  1220. Effect.ResetCache = function () {
  1221. Effect._baseCache = {};
  1222. };
  1223. Effect._uniqueIdSeed = 0;
  1224. Effect._baseCache = {};
  1225. /**
  1226. * Store of each shader (The can be looked up using effect.key)
  1227. */
  1228. Effect.ShadersStore = {};
  1229. /**
  1230. * Store of each included file for a shader (The can be looked up using effect.key)
  1231. */
  1232. Effect.IncludesShadersStore = {};
  1233. return Effect;
  1234. }());
  1235. BABYLON.Effect = Effect;
  1236. })(BABYLON || (BABYLON = {}));
  1237. //# sourceMappingURL=babylon.effect.js.map
  1238. //# sourceMappingURL=babylon.types.js.map
  1239. var BABYLON;
  1240. (function (BABYLON) {
  1241. /**
  1242. * Gather the list of keyboard event types as constants.
  1243. */
  1244. var KeyboardEventTypes = /** @class */ (function () {
  1245. function KeyboardEventTypes() {
  1246. }
  1247. /**
  1248. * The keydown event is fired when a key becomes active (pressed).
  1249. */
  1250. KeyboardEventTypes.KEYDOWN = 0x01;
  1251. /**
  1252. * The keyup event is fired when a key has been released.
  1253. */
  1254. KeyboardEventTypes.KEYUP = 0x02;
  1255. return KeyboardEventTypes;
  1256. }());
  1257. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1258. /**
  1259. * This class is used to store keyboard related info for the onKeyboardObservable event.
  1260. */
  1261. var KeyboardInfo = /** @class */ (function () {
  1262. /**
  1263. * Instantiates a new keyboard info.
  1264. * This class is used to store keyboard related info for the onKeyboardObservable event.
  1265. * @param type Defines the type of event (BABYLON.KeyboardEventTypes)
  1266. * @param event Defines the related dom event
  1267. */
  1268. function KeyboardInfo(
  1269. /**
  1270. * Defines the type of event (BABYLON.KeyboardEventTypes)
  1271. */
  1272. type,
  1273. /**
  1274. * Defines the related dom event
  1275. */
  1276. event) {
  1277. this.type = type;
  1278. this.event = event;
  1279. }
  1280. return KeyboardInfo;
  1281. }());
  1282. BABYLON.KeyboardInfo = KeyboardInfo;
  1283. /**
  1284. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1285. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1286. */
  1287. var KeyboardInfoPre = /** @class */ (function (_super) {
  1288. __extends(KeyboardInfoPre, _super);
  1289. /**
  1290. * Instantiates a new keyboard pre info.
  1291. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1292. * @param type Defines the type of event (BABYLON.KeyboardEventTypes)
  1293. * @param event Defines the related dom event
  1294. */
  1295. function KeyboardInfoPre(
  1296. /**
  1297. * Defines the type of event (BABYLON.KeyboardEventTypes)
  1298. */
  1299. type,
  1300. /**
  1301. * Defines the related dom event
  1302. */
  1303. event) {
  1304. var _this = _super.call(this, type, event) || this;
  1305. _this.type = type;
  1306. _this.event = event;
  1307. _this.skipOnPointerObservable = false;
  1308. return _this;
  1309. }
  1310. return KeyboardInfoPre;
  1311. }(KeyboardInfo));
  1312. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1313. })(BABYLON || (BABYLON = {}));
  1314. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1315. var BABYLON;
  1316. (function (BABYLON) {
  1317. /**
  1318. * Gather the list of pointer event types as constants.
  1319. */
  1320. var PointerEventTypes = /** @class */ (function () {
  1321. function PointerEventTypes() {
  1322. }
  1323. /**
  1324. * The pointerdown event is fired when a pointer becomes active. For mouse, it is fired when the device transitions from no buttons depressed to at least one button depressed. For touch, it is fired when physical contact is made with the digitizer. For pen, it is fired when the stylus makes physical contact with the digitizer.
  1325. */
  1326. PointerEventTypes.POINTERDOWN = 0x01;
  1327. /**
  1328. * The pointerup event is fired when a pointer is no longer active.
  1329. */
  1330. PointerEventTypes.POINTERUP = 0x02;
  1331. /**
  1332. * The pointermove event is fired when a pointer changes coordinates.
  1333. */
  1334. PointerEventTypes.POINTERMOVE = 0x04;
  1335. /**
  1336. * The pointerwheel event is fired when a mouse wheel has been rotated.
  1337. */
  1338. PointerEventTypes.POINTERWHEEL = 0x08;
  1339. /**
  1340. * The pointerpick event is fired when a mesh or sprite has been picked by the pointer.
  1341. */
  1342. PointerEventTypes.POINTERPICK = 0x10;
  1343. /**
  1344. * The pointertap event is fired when a the object has been touched and released without drag.
  1345. */
  1346. PointerEventTypes.POINTERTAP = 0x20;
  1347. /**
  1348. * The pointertap event is fired when a the object has been touched and released twice without drag.
  1349. */
  1350. PointerEventTypes.POINTERDOUBLETAP = 0x40;
  1351. return PointerEventTypes;
  1352. }());
  1353. BABYLON.PointerEventTypes = PointerEventTypes;
  1354. /**
  1355. * Base class of pointer info types.
  1356. */
  1357. var PointerInfoBase = /** @class */ (function () {
  1358. /**
  1359. * Instantiates the base class of pointers info.
  1360. * @param type Defines the type of event (BABYLON.PointerEventTypes)
  1361. * @param event Defines the related dom event
  1362. */
  1363. function PointerInfoBase(
  1364. /**
  1365. * Defines the type of event (BABYLON.PointerEventTypes)
  1366. */
  1367. type,
  1368. /**
  1369. * Defines the related dom event
  1370. */
  1371. event) {
  1372. this.type = type;
  1373. this.event = event;
  1374. }
  1375. return PointerInfoBase;
  1376. }());
  1377. BABYLON.PointerInfoBase = PointerInfoBase;
  1378. /**
  1379. * This class is used to store pointer related info for the onPrePointerObservable event.
  1380. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1381. */
  1382. var PointerInfoPre = /** @class */ (function (_super) {
  1383. __extends(PointerInfoPre, _super);
  1384. /**
  1385. * Instantiates a PointerInfoPre to store pointer related info to the onPrePointerObservable event.
  1386. * @param type Defines the type of event (BABYLON.PointerEventTypes)
  1387. * @param event Defines the related dom event
  1388. * @param localX Defines the local x coordinates of the pointer when the event occured
  1389. * @param localY Defines the local y coordinates of the pointer when the event occured
  1390. */
  1391. function PointerInfoPre(type, event, localX, localY) {
  1392. var _this = _super.call(this, type, event) || this;
  1393. /**
  1394. * Ray from a pointer if availible (eg. 6dof controller)
  1395. */
  1396. _this.ray = null;
  1397. _this.skipOnPointerObservable = false;
  1398. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1399. return _this;
  1400. }
  1401. return PointerInfoPre;
  1402. }(PointerInfoBase));
  1403. BABYLON.PointerInfoPre = PointerInfoPre;
  1404. /**
  1405. * This type contains all the data related to a pointer event in Babylon.js.
  1406. * 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.
  1407. */
  1408. var PointerInfo = /** @class */ (function (_super) {
  1409. __extends(PointerInfo, _super);
  1410. /**
  1411. * Instantiates a PointerInfo to store pointer related info to the onPointerObservable event.
  1412. * @param type Defines the type of event (BABYLON.PointerEventTypes)
  1413. * @param event Defines the related dom event
  1414. * @param pickInfo Defines the picking info associated to the info (if any)\
  1415. */
  1416. function PointerInfo(type, event,
  1417. /**
  1418. * Defines the picking info associated to the info (if any)\
  1419. */
  1420. pickInfo) {
  1421. var _this = _super.call(this, type, event) || this;
  1422. _this.pickInfo = pickInfo;
  1423. return _this;
  1424. }
  1425. return PointerInfo;
  1426. }(PointerInfoBase));
  1427. BABYLON.PointerInfo = PointerInfo;
  1428. })(BABYLON || (BABYLON = {}));
  1429. //# sourceMappingURL=babylon.pointerEvents.js.map
  1430. var BABYLON;
  1431. (function (BABYLON) {
  1432. /**
  1433. * Constant used to convert a value to gamma space
  1434. * @ignorenaming
  1435. */
  1436. BABYLON.ToGammaSpace = 1 / 2.2;
  1437. /**
  1438. * Constant used to convert a value to linear space
  1439. * @ignorenaming
  1440. */
  1441. BABYLON.ToLinearSpace = 2.2;
  1442. /**
  1443. * Constant used to define the minimal number value in Babylon.js
  1444. * @ignorenaming
  1445. */
  1446. BABYLON.Epsilon = 0.001;
  1447. /**
  1448. * Class used to hold a RBG color
  1449. */
  1450. var Color3 = /** @class */ (function () {
  1451. /**
  1452. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1453. * @param r defines the red component (between 0 and 1, default is 0)
  1454. * @param g defines the green component (between 0 and 1, default is 0)
  1455. * @param b defines the blue component (between 0 and 1, default is 0)
  1456. */
  1457. function Color3(
  1458. /**
  1459. * Defines the red component (between 0 and 1, default is 0)
  1460. */
  1461. r,
  1462. /**
  1463. * Defines the green component (between 0 and 1, default is 0)
  1464. */
  1465. g,
  1466. /**
  1467. * Defines the blue component (between 0 and 1, default is 0)
  1468. */
  1469. b) {
  1470. if (r === void 0) { r = 0; }
  1471. if (g === void 0) { g = 0; }
  1472. if (b === void 0) { b = 0; }
  1473. this.r = r;
  1474. this.g = g;
  1475. this.b = b;
  1476. }
  1477. /**
  1478. * Creates a string with the Color3 current values
  1479. * @returns the string representation of the Color3 object
  1480. */
  1481. Color3.prototype.toString = function () {
  1482. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1483. };
  1484. /**
  1485. * Returns the string "Color3"
  1486. * @returns "Color3"
  1487. */
  1488. Color3.prototype.getClassName = function () {
  1489. return "Color3";
  1490. };
  1491. /**
  1492. * Compute the Color3 hash code
  1493. * @returns an unique number that can be used to hash Color3 objects
  1494. */
  1495. Color3.prototype.getHashCode = function () {
  1496. var hash = this.r || 0;
  1497. hash = (hash * 397) ^ (this.g || 0);
  1498. hash = (hash * 397) ^ (this.b || 0);
  1499. return hash;
  1500. };
  1501. // Operators
  1502. /**
  1503. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1504. * @param array defines the array where to store the r,g,b components
  1505. * @param index defines an optional index in the target array to define where to start storing values
  1506. * @returns the current Color3 object
  1507. */
  1508. Color3.prototype.toArray = function (array, index) {
  1509. if (index === undefined) {
  1510. index = 0;
  1511. }
  1512. array[index] = this.r;
  1513. array[index + 1] = this.g;
  1514. array[index + 2] = this.b;
  1515. return this;
  1516. };
  1517. /**
  1518. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1519. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1520. * @returns a new {BABYLON.Color4} object
  1521. */
  1522. Color3.prototype.toColor4 = function (alpha) {
  1523. if (alpha === void 0) { alpha = 1; }
  1524. return new Color4(this.r, this.g, this.b, alpha);
  1525. };
  1526. /**
  1527. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1528. * @returns the new array
  1529. */
  1530. Color3.prototype.asArray = function () {
  1531. var result = new Array();
  1532. this.toArray(result, 0);
  1533. return result;
  1534. };
  1535. /**
  1536. * Returns the luminance value
  1537. * @returns a float value
  1538. */
  1539. Color3.prototype.toLuminance = function () {
  1540. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1541. };
  1542. /**
  1543. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1544. * @param otherColor defines the second operand
  1545. * @returns the new Color3 object
  1546. */
  1547. Color3.prototype.multiply = function (otherColor) {
  1548. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1549. };
  1550. /**
  1551. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1552. * @param otherColor defines the second operand
  1553. * @param result defines the Color3 object where to store the result
  1554. * @returns the current Color3
  1555. */
  1556. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1557. result.r = this.r * otherColor.r;
  1558. result.g = this.g * otherColor.g;
  1559. result.b = this.b * otherColor.b;
  1560. return this;
  1561. };
  1562. /**
  1563. * Determines equality between Color3 objects
  1564. * @param otherColor defines the second operand
  1565. * @returns true if the rgb values are equal to the given ones
  1566. */
  1567. Color3.prototype.equals = function (otherColor) {
  1568. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1569. };
  1570. /**
  1571. * Determines equality between the current Color3 object and a set of r,b,g values
  1572. * @param r defines the red component to check
  1573. * @param g defines the green component to check
  1574. * @param b defines the blue component to check
  1575. * @returns true if the rgb values are equal to the given ones
  1576. */
  1577. Color3.prototype.equalsFloats = function (r, g, b) {
  1578. return this.r === r && this.g === g && this.b === b;
  1579. };
  1580. /**
  1581. * Multiplies in place each rgb value by scale
  1582. * @param scale defines the scaling factor
  1583. * @returns the updated Color3
  1584. */
  1585. Color3.prototype.scale = function (scale) {
  1586. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1587. };
  1588. /**
  1589. * Multiplies the rgb values by scale and stores the result into "result"
  1590. * @param scale defines the scaling factor
  1591. * @param result defines the Color3 object where to store the result
  1592. * @returns the unmodified current Color3
  1593. */
  1594. Color3.prototype.scaleToRef = function (scale, result) {
  1595. result.r = this.r * scale;
  1596. result.g = this.g * scale;
  1597. result.b = this.b * scale;
  1598. return this;
  1599. };
  1600. /**
  1601. * Scale the current Color3 values by a factor and add the result to a given Color3
  1602. * @param scale defines the scale factor
  1603. * @param result defines color to store the result into
  1604. * @returns the unmodified current Color3
  1605. */
  1606. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1607. result.r += this.r * scale;
  1608. result.g += this.g * scale;
  1609. result.b += this.b * scale;
  1610. return this;
  1611. };
  1612. /**
  1613. * Clamps the rgb values by the min and max values and stores the result into "result"
  1614. * @param min defines minimum clamping value (default is 0)
  1615. * @param max defines maximum clamping value (default is 1)
  1616. * @param result defines color to store the result into
  1617. * @returns the original Color3
  1618. */
  1619. Color3.prototype.clampToRef = function (min, max, result) {
  1620. if (min === void 0) { min = 0; }
  1621. if (max === void 0) { max = 1; }
  1622. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1623. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1624. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1625. return this;
  1626. };
  1627. /**
  1628. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1629. * @param otherColor defines the second operand
  1630. * @returns the new Color3
  1631. */
  1632. Color3.prototype.add = function (otherColor) {
  1633. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1634. };
  1635. /**
  1636. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1637. * @param otherColor defines the second operand
  1638. * @param result defines Color3 object to store the result into
  1639. * @returns the unmodified current Color3
  1640. */
  1641. Color3.prototype.addToRef = function (otherColor, result) {
  1642. result.r = this.r + otherColor.r;
  1643. result.g = this.g + otherColor.g;
  1644. result.b = this.b + otherColor.b;
  1645. return this;
  1646. };
  1647. /**
  1648. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1649. * @param otherColor defines the second operand
  1650. * @returns the new Color3
  1651. */
  1652. Color3.prototype.subtract = function (otherColor) {
  1653. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1654. };
  1655. /**
  1656. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1657. * @param otherColor defines the second operand
  1658. * @param result defines Color3 object to store the result into
  1659. * @returns the unmodified current Color3
  1660. */
  1661. Color3.prototype.subtractToRef = function (otherColor, result) {
  1662. result.r = this.r - otherColor.r;
  1663. result.g = this.g - otherColor.g;
  1664. result.b = this.b - otherColor.b;
  1665. return this;
  1666. };
  1667. /**
  1668. * Copy the current object
  1669. * @returns a new Color3 copied the current one
  1670. */
  1671. Color3.prototype.clone = function () {
  1672. return new Color3(this.r, this.g, this.b);
  1673. };
  1674. /**
  1675. * Copies the rgb values from the source in the current Color3
  1676. * @param source defines the source Color3 object
  1677. * @returns the updated Color3 object
  1678. */
  1679. Color3.prototype.copyFrom = function (source) {
  1680. this.r = source.r;
  1681. this.g = source.g;
  1682. this.b = source.b;
  1683. return this;
  1684. };
  1685. /**
  1686. * Updates the Color3 rgb values from the given floats
  1687. * @param r defines the red component to read from
  1688. * @param g defines the green component to read from
  1689. * @param b defines the blue component to read from
  1690. * @returns the current Color3 object
  1691. */
  1692. Color3.prototype.copyFromFloats = function (r, g, b) {
  1693. this.r = r;
  1694. this.g = g;
  1695. this.b = b;
  1696. return this;
  1697. };
  1698. /**
  1699. * Updates the Color3 rgb values from the given floats
  1700. * @param r defines the red component to read from
  1701. * @param g defines the green component to read from
  1702. * @param b defines the blue component to read from
  1703. * @returns the current Color3 object
  1704. */
  1705. Color3.prototype.set = function (r, g, b) {
  1706. return this.copyFromFloats(r, g, b);
  1707. };
  1708. /**
  1709. * Compute the Color3 hexadecimal code as a string
  1710. * @returns a string containing the hexadecimal representation of the Color3 object
  1711. */
  1712. Color3.prototype.toHexString = function () {
  1713. var intR = (this.r * 255) | 0;
  1714. var intG = (this.g * 255) | 0;
  1715. var intB = (this.b * 255) | 0;
  1716. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1717. };
  1718. /**
  1719. * Computes a new Color3 converted from the current one to linear space
  1720. * @returns a new Color3 object
  1721. */
  1722. Color3.prototype.toLinearSpace = function () {
  1723. var convertedColor = new Color3();
  1724. this.toLinearSpaceToRef(convertedColor);
  1725. return convertedColor;
  1726. };
  1727. /**
  1728. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1729. * @param convertedColor defines the Color3 object where to store the linear space version
  1730. * @returns the unmodified Color3
  1731. */
  1732. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1733. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1734. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1735. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1736. return this;
  1737. };
  1738. /**
  1739. * Computes a new Color3 converted from the current one to gamma space
  1740. * @returns a new Color3 object
  1741. */
  1742. Color3.prototype.toGammaSpace = function () {
  1743. var convertedColor = new Color3();
  1744. this.toGammaSpaceToRef(convertedColor);
  1745. return convertedColor;
  1746. };
  1747. /**
  1748. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1749. * @param convertedColor defines the Color3 object where to store the gamma space version
  1750. * @returns the unmodified Color3
  1751. */
  1752. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1753. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1754. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1755. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1756. return this;
  1757. };
  1758. // Statics
  1759. /**
  1760. * Creates a new Color3 from the string containing valid hexadecimal values
  1761. * @param hex defines a string containing valid hexadecimal values
  1762. * @returns a new Color3 object
  1763. */
  1764. Color3.FromHexString = function (hex) {
  1765. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1766. return new Color3(0, 0, 0);
  1767. }
  1768. var r = parseInt(hex.substring(1, 3), 16);
  1769. var g = parseInt(hex.substring(3, 5), 16);
  1770. var b = parseInt(hex.substring(5, 7), 16);
  1771. return Color3.FromInts(r, g, b);
  1772. };
  1773. /**
  1774. * Creates a new Vector3 from the starting index of the given array
  1775. * @param array defines the source array
  1776. * @param offset defines an offset in the source array
  1777. * @returns a new Color3 object
  1778. */
  1779. Color3.FromArray = function (array, offset) {
  1780. if (offset === void 0) { offset = 0; }
  1781. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1782. };
  1783. /**
  1784. * Creates a new Color3 from integer values (< 256)
  1785. * @param r defines the red component to read from (value between 0 and 255)
  1786. * @param g defines the green component to read from (value between 0 and 255)
  1787. * @param b defines the blue component to read from (value between 0 and 255)
  1788. * @returns a new Color3 object
  1789. */
  1790. Color3.FromInts = function (r, g, b) {
  1791. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1792. };
  1793. /**
  1794. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1795. * @param start defines the start Color3 value
  1796. * @param end defines the end Color3 value
  1797. * @param amount defines the gradient value between start and end
  1798. * @returns a new Color3 object
  1799. */
  1800. Color3.Lerp = function (start, end, amount) {
  1801. var result = new Color3(0.0, 0.0, 0.0);
  1802. Color3.LerpToRef(start, end, amount, result);
  1803. return result;
  1804. };
  1805. /**
  1806. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1807. * @param left defines the start value
  1808. * @param right defines the end value
  1809. * @param amount defines the gradient factor
  1810. * @param result defines the Color3 object where to store the result
  1811. */
  1812. Color3.LerpToRef = function (left, right, amount, result) {
  1813. result.r = left.r + ((right.r - left.r) * amount);
  1814. result.g = left.g + ((right.g - left.g) * amount);
  1815. result.b = left.b + ((right.b - left.b) * amount);
  1816. };
  1817. /**
  1818. * Returns a Color3 value containing a red color
  1819. * @returns a new Color3 object
  1820. */
  1821. Color3.Red = function () { return new Color3(1, 0, 0); };
  1822. /**
  1823. * Returns a Color3 value containing a green color
  1824. * @returns a new Color3 object
  1825. */
  1826. Color3.Green = function () { return new Color3(0, 1, 0); };
  1827. /**
  1828. * Returns a Color3 value containing a blue color
  1829. * @returns a new Color3 object
  1830. */
  1831. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1832. /**
  1833. * Returns a Color3 value containing a black color
  1834. * @returns a new Color3 object
  1835. */
  1836. Color3.Black = function () { return new Color3(0, 0, 0); };
  1837. /**
  1838. * Returns a Color3 value containing a white color
  1839. * @returns a new Color3 object
  1840. */
  1841. Color3.White = function () { return new Color3(1, 1, 1); };
  1842. /**
  1843. * Returns a Color3 value containing a purple color
  1844. * @returns a new Color3 object
  1845. */
  1846. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1847. /**
  1848. * Returns a Color3 value containing a magenta color
  1849. * @returns a new Color3 object
  1850. */
  1851. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1852. /**
  1853. * Returns a Color3 value containing a yellow color
  1854. * @returns a new Color3 object
  1855. */
  1856. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1857. /**
  1858. * Returns a Color3 value containing a gray color
  1859. * @returns a new Color3 object
  1860. */
  1861. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1862. /**
  1863. * Returns a Color3 value containing a teal color
  1864. * @returns a new Color3 object
  1865. */
  1866. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1867. /**
  1868. * Returns a Color3 value containing a random color
  1869. * @returns a new Color3 object
  1870. */
  1871. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1872. return Color3;
  1873. }());
  1874. BABYLON.Color3 = Color3;
  1875. /**
  1876. * Class used to hold a RBGA color
  1877. */
  1878. var Color4 = /** @class */ (function () {
  1879. /**
  1880. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1881. * @param r defines the red component (between 0 and 1, default is 0)
  1882. * @param g defines the green component (between 0 and 1, default is 0)
  1883. * @param b defines the blue component (between 0 and 1, default is 0)
  1884. * @param a defines the alpha component (between 0 and 1, default is 1)
  1885. */
  1886. function Color4(
  1887. /**
  1888. * Defines the red component (between 0 and 1, default is 0)
  1889. */
  1890. r,
  1891. /**
  1892. * Defines the green component (between 0 and 1, default is 0)
  1893. */
  1894. g,
  1895. /**
  1896. * Defines the blue component (between 0 and 1, default is 0)
  1897. */
  1898. b,
  1899. /**
  1900. * Defines the alpha component (between 0 and 1, default is 1)
  1901. */
  1902. a) {
  1903. if (r === void 0) { r = 0; }
  1904. if (g === void 0) { g = 0; }
  1905. if (b === void 0) { b = 0; }
  1906. if (a === void 0) { a = 1; }
  1907. this.r = r;
  1908. this.g = g;
  1909. this.b = b;
  1910. this.a = a;
  1911. }
  1912. // Operators
  1913. /**
  1914. * Adds in place the given Color4 values to the current Color4 object
  1915. * @param right defines the second operand
  1916. * @returns the current updated Color4 object
  1917. */
  1918. Color4.prototype.addInPlace = function (right) {
  1919. this.r += right.r;
  1920. this.g += right.g;
  1921. this.b += right.b;
  1922. this.a += right.a;
  1923. return this;
  1924. };
  1925. /**
  1926. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1927. * @returns the new array
  1928. */
  1929. Color4.prototype.asArray = function () {
  1930. var result = new Array();
  1931. this.toArray(result, 0);
  1932. return result;
  1933. };
  1934. /**
  1935. * Stores from the starting index in the given array the Color4 successive values
  1936. * @param array defines the array where to store the r,g,b components
  1937. * @param index defines an optional index in the target array to define where to start storing values
  1938. * @returns the current Color4 object
  1939. */
  1940. Color4.prototype.toArray = function (array, index) {
  1941. if (index === undefined) {
  1942. index = 0;
  1943. }
  1944. array[index] = this.r;
  1945. array[index + 1] = this.g;
  1946. array[index + 2] = this.b;
  1947. array[index + 3] = this.a;
  1948. return this;
  1949. };
  1950. /**
  1951. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1952. * @param right defines the second operand
  1953. * @returns a new Color4 object
  1954. */
  1955. Color4.prototype.add = function (right) {
  1956. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1957. };
  1958. /**
  1959. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1960. * @param right defines the second operand
  1961. * @returns a new Color4 object
  1962. */
  1963. Color4.prototype.subtract = function (right) {
  1964. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1965. };
  1966. /**
  1967. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1968. * @param right defines the second operand
  1969. * @param result defines the Color4 object where to store the result
  1970. * @returns the current Color4 object
  1971. */
  1972. Color4.prototype.subtractToRef = function (right, result) {
  1973. result.r = this.r - right.r;
  1974. result.g = this.g - right.g;
  1975. result.b = this.b - right.b;
  1976. result.a = this.a - right.a;
  1977. return this;
  1978. };
  1979. /**
  1980. * Creates a new Color4 with the current Color4 values multiplied by scale
  1981. * @param scale defines the scaling factor to apply
  1982. * @returns a new Color4 object
  1983. */
  1984. Color4.prototype.scale = function (scale) {
  1985. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1986. };
  1987. /**
  1988. * Multiplies the current Color4 values by scale and stores the result in "result"
  1989. * @param scale defines the scaling factor to apply
  1990. * @param result defines the Color4 object where to store the result
  1991. * @returns the current unmodified Color4
  1992. */
  1993. Color4.prototype.scaleToRef = function (scale, result) {
  1994. result.r = this.r * scale;
  1995. result.g = this.g * scale;
  1996. result.b = this.b * scale;
  1997. result.a = this.a * scale;
  1998. return this;
  1999. };
  2000. /**
  2001. * Scale the current Color4 values by a factor and add the result to a given Color4
  2002. * @param scale defines the scale factor
  2003. * @param result defines the Color4 object where to store the result
  2004. * @returns the unmodified current Color4
  2005. */
  2006. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  2007. result.r += this.r * scale;
  2008. result.g += this.g * scale;
  2009. result.b += this.b * scale;
  2010. result.a += this.a * scale;
  2011. return this;
  2012. };
  2013. /**
  2014. * Clamps the rgb values by the min and max values and stores the result into "result"
  2015. * @param min defines minimum clamping value (default is 0)
  2016. * @param max defines maximum clamping value (default is 1)
  2017. * @param result defines color to store the result into.
  2018. * @returns the cuurent Color4
  2019. */
  2020. Color4.prototype.clampToRef = function (min, max, result) {
  2021. if (min === void 0) { min = 0; }
  2022. if (max === void 0) { max = 1; }
  2023. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  2024. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  2025. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  2026. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  2027. return this;
  2028. };
  2029. /**
  2030. * Multipy an Color4 value by another and return a new Color4 object
  2031. * @param color defines the Color4 value to multiply by
  2032. * @returns a new Color4 object
  2033. */
  2034. Color4.prototype.multiply = function (color) {
  2035. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  2036. };
  2037. /**
  2038. * Multipy a Color4 value by another and push the result in a reference value
  2039. * @param color defines the Color4 value to multiply by
  2040. * @param result defines the Color4 to fill the result in
  2041. * @returns the result Color4
  2042. */
  2043. Color4.prototype.multiplyToRef = function (color, result) {
  2044. result.r = this.r * color.r;
  2045. result.g = this.g * color.g;
  2046. result.b = this.b * color.b;
  2047. result.a = this.a * color.a;
  2048. return result;
  2049. };
  2050. /**
  2051. * Creates a string with the Color4 current values
  2052. * @returns the string representation of the Color4 object
  2053. */
  2054. Color4.prototype.toString = function () {
  2055. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  2056. };
  2057. /**
  2058. * Returns the string "Color4"
  2059. * @returns "Color4"
  2060. */
  2061. Color4.prototype.getClassName = function () {
  2062. return "Color4";
  2063. };
  2064. /**
  2065. * Compute the Color4 hash code
  2066. * @returns an unique number that can be used to hash Color4 objects
  2067. */
  2068. Color4.prototype.getHashCode = function () {
  2069. var hash = this.r || 0;
  2070. hash = (hash * 397) ^ (this.g || 0);
  2071. hash = (hash * 397) ^ (this.b || 0);
  2072. hash = (hash * 397) ^ (this.a || 0);
  2073. return hash;
  2074. };
  2075. /**
  2076. * Creates a new Color4 copied from the current one
  2077. * @returns a new Color4 object
  2078. */
  2079. Color4.prototype.clone = function () {
  2080. return new Color4(this.r, this.g, this.b, this.a);
  2081. };
  2082. /**
  2083. * Copies the given Color4 values into the current one
  2084. * @param source defines the source Color4 object
  2085. * @returns the current updated Color4 object
  2086. */
  2087. Color4.prototype.copyFrom = function (source) {
  2088. this.r = source.r;
  2089. this.g = source.g;
  2090. this.b = source.b;
  2091. this.a = source.a;
  2092. return this;
  2093. };
  2094. /**
  2095. * Copies the given float values into the current one
  2096. * @param r defines the red component to read from
  2097. * @param g defines the green component to read from
  2098. * @param b defines the blue component to read from
  2099. * @param a defines the alpha component to read from
  2100. * @returns the current updated Color4 object
  2101. */
  2102. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2103. this.r = r;
  2104. this.g = g;
  2105. this.b = b;
  2106. this.a = a;
  2107. return this;
  2108. };
  2109. /**
  2110. * Copies the given float values into the current one
  2111. * @param r defines the red component to read from
  2112. * @param g defines the green component to read from
  2113. * @param b defines the blue component to read from
  2114. * @param a defines the alpha component to read from
  2115. * @returns the current updated Color4 object
  2116. */
  2117. Color4.prototype.set = function (r, g, b, a) {
  2118. return this.copyFromFloats(r, g, b, a);
  2119. };
  2120. /**
  2121. * Compute the Color4 hexadecimal code as a string
  2122. * @returns a string containing the hexadecimal representation of the Color4 object
  2123. */
  2124. Color4.prototype.toHexString = function () {
  2125. var intR = (this.r * 255) | 0;
  2126. var intG = (this.g * 255) | 0;
  2127. var intB = (this.b * 255) | 0;
  2128. var intA = (this.a * 255) | 0;
  2129. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2130. };
  2131. /**
  2132. * Computes a new Color4 converted from the current one to linear space
  2133. * @returns a new Color4 object
  2134. */
  2135. Color4.prototype.toLinearSpace = function () {
  2136. var convertedColor = new Color4();
  2137. this.toLinearSpaceToRef(convertedColor);
  2138. return convertedColor;
  2139. };
  2140. /**
  2141. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2142. * @param convertedColor defines the Color4 object where to store the linear space version
  2143. * @returns the unmodified Color4
  2144. */
  2145. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2146. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2147. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2148. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2149. convertedColor.a = this.a;
  2150. return this;
  2151. };
  2152. /**
  2153. * Computes a new Color4 converted from the current one to gamma space
  2154. * @returns a new Color4 object
  2155. */
  2156. Color4.prototype.toGammaSpace = function () {
  2157. var convertedColor = new Color4();
  2158. this.toGammaSpaceToRef(convertedColor);
  2159. return convertedColor;
  2160. };
  2161. /**
  2162. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2163. * @param convertedColor defines the Color4 object where to store the gamma space version
  2164. * @returns the unmodified Color4
  2165. */
  2166. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2167. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2168. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2169. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2170. convertedColor.a = this.a;
  2171. return this;
  2172. };
  2173. // Statics
  2174. /**
  2175. * Creates a new Color4 from the string containing valid hexadecimal values
  2176. * @param hex defines a string containing valid hexadecimal values
  2177. * @returns a new Color4 object
  2178. */
  2179. Color4.FromHexString = function (hex) {
  2180. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2181. return new Color4(0.0, 0.0, 0.0, 0.0);
  2182. }
  2183. var r = parseInt(hex.substring(1, 3), 16);
  2184. var g = parseInt(hex.substring(3, 5), 16);
  2185. var b = parseInt(hex.substring(5, 7), 16);
  2186. var a = parseInt(hex.substring(7, 9), 16);
  2187. return Color4.FromInts(r, g, b, a);
  2188. };
  2189. /**
  2190. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2191. * @param left defines the start value
  2192. * @param right defines the end value
  2193. * @param amount defines the gradient factor
  2194. * @returns a new Color4 object
  2195. */
  2196. Color4.Lerp = function (left, right, amount) {
  2197. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2198. Color4.LerpToRef(left, right, amount, result);
  2199. return result;
  2200. };
  2201. /**
  2202. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2203. * @param left defines the start value
  2204. * @param right defines the end value
  2205. * @param amount defines the gradient factor
  2206. * @param result defines the Color4 object where to store data
  2207. */
  2208. Color4.LerpToRef = function (left, right, amount, result) {
  2209. result.r = left.r + (right.r - left.r) * amount;
  2210. result.g = left.g + (right.g - left.g) * amount;
  2211. result.b = left.b + (right.b - left.b) * amount;
  2212. result.a = left.a + (right.a - left.a) * amount;
  2213. };
  2214. /**
  2215. * Creates a new Color4 from a Color3 and an alpha value
  2216. * @param color3 defines the source Color3 to read from
  2217. * @param alpha defines the alpha component (1.0 by default)
  2218. * @returns a new Color4 object
  2219. */
  2220. Color4.FromColor3 = function (color3, alpha) {
  2221. if (alpha === void 0) { alpha = 1.0; }
  2222. return new Color4(color3.r, color3.g, color3.b, alpha);
  2223. };
  2224. /**
  2225. * Creates a new Color4 from the starting index element of the given array
  2226. * @param array defines the source array to read from
  2227. * @param offset defines the offset in the source array
  2228. * @returns a new Color4 object
  2229. */
  2230. Color4.FromArray = function (array, offset) {
  2231. if (offset === void 0) { offset = 0; }
  2232. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2233. };
  2234. /**
  2235. * Creates a new Color3 from integer values (< 256)
  2236. * @param r defines the red component to read from (value between 0 and 255)
  2237. * @param g defines the green component to read from (value between 0 and 255)
  2238. * @param b defines the blue component to read from (value between 0 and 255)
  2239. * @param a defines the alpha component to read from (value between 0 and 255)
  2240. * @returns a new Color3 object
  2241. */
  2242. Color4.FromInts = function (r, g, b, a) {
  2243. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2244. };
  2245. /**
  2246. * Check the content of a given array and convert it to an array containing RGBA data
  2247. * If the original array was already containing count * 4 values then it is returned directly
  2248. * @param colors defines the array to check
  2249. * @param count defines the number of RGBA data to expect
  2250. * @returns an array containing count * 4 values (RGBA)
  2251. */
  2252. Color4.CheckColors4 = function (colors, count) {
  2253. // Check if color3 was used
  2254. if (colors.length === count * 3) {
  2255. var colors4 = [];
  2256. for (var index = 0; index < colors.length; index += 3) {
  2257. var newIndex = (index / 3) * 4;
  2258. colors4[newIndex] = colors[index];
  2259. colors4[newIndex + 1] = colors[index + 1];
  2260. colors4[newIndex + 2] = colors[index + 2];
  2261. colors4[newIndex + 3] = 1.0;
  2262. }
  2263. return colors4;
  2264. }
  2265. return colors;
  2266. };
  2267. return Color4;
  2268. }());
  2269. BABYLON.Color4 = Color4;
  2270. /**
  2271. * Class representing a vector containing 2 coordinates
  2272. */
  2273. var Vector2 = /** @class */ (function () {
  2274. /**
  2275. * Creates a new Vector2 from the given x and y coordinates
  2276. * @param x defines the first coordinate
  2277. * @param y defines the second coordinate
  2278. */
  2279. function Vector2(
  2280. /** defines the first coordinate */
  2281. x,
  2282. /** defines the second coordinate */
  2283. y) {
  2284. if (x === void 0) { x = 0; }
  2285. if (y === void 0) { y = 0; }
  2286. this.x = x;
  2287. this.y = y;
  2288. }
  2289. /**
  2290. * Gets a string with the Vector2 coordinates
  2291. * @returns a string with the Vector2 coordinates
  2292. */
  2293. Vector2.prototype.toString = function () {
  2294. return "{X: " + this.x + " Y:" + this.y + "}";
  2295. };
  2296. /**
  2297. * Gets class name
  2298. * @returns the string "Vector2"
  2299. */
  2300. Vector2.prototype.getClassName = function () {
  2301. return "Vector2";
  2302. };
  2303. /**
  2304. * Gets current vector hash code
  2305. * @returns the Vector2 hash code as a number
  2306. */
  2307. Vector2.prototype.getHashCode = function () {
  2308. var hash = this.x || 0;
  2309. hash = (hash * 397) ^ (this.y || 0);
  2310. return hash;
  2311. };
  2312. // Operators
  2313. /**
  2314. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2315. * @param array defines the source array
  2316. * @param index defines the offset in source array
  2317. * @returns the current Vector2
  2318. */
  2319. Vector2.prototype.toArray = function (array, index) {
  2320. if (index === void 0) { index = 0; }
  2321. array[index] = this.x;
  2322. array[index + 1] = this.y;
  2323. return this;
  2324. };
  2325. /**
  2326. * Copy the current vector to an array
  2327. * @returns a new array with 2 elements: the Vector2 coordinates.
  2328. */
  2329. Vector2.prototype.asArray = function () {
  2330. var result = new Array();
  2331. this.toArray(result, 0);
  2332. return result;
  2333. };
  2334. /**
  2335. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2336. * @param source defines the source Vector2
  2337. * @returns the current updated Vector2
  2338. */
  2339. Vector2.prototype.copyFrom = function (source) {
  2340. this.x = source.x;
  2341. this.y = source.y;
  2342. return this;
  2343. };
  2344. /**
  2345. * Sets the Vector2 coordinates with the given floats
  2346. * @param x defines the first coordinate
  2347. * @param y defines the second coordinate
  2348. * @returns the current updated Vector2
  2349. */
  2350. Vector2.prototype.copyFromFloats = function (x, y) {
  2351. this.x = x;
  2352. this.y = y;
  2353. return this;
  2354. };
  2355. /**
  2356. * Sets the Vector2 coordinates with the given floats
  2357. * @param x defines the first coordinate
  2358. * @param y defines the second coordinate
  2359. * @returns the current updated Vector2
  2360. */
  2361. Vector2.prototype.set = function (x, y) {
  2362. return this.copyFromFloats(x, y);
  2363. };
  2364. /**
  2365. * Add another vector with the current one
  2366. * @param otherVector defines the other vector
  2367. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2368. */
  2369. Vector2.prototype.add = function (otherVector) {
  2370. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2371. };
  2372. /**
  2373. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2374. * @param otherVector defines the other vector
  2375. * @param result defines the target vector
  2376. * @returns the unmodified current Vector2
  2377. */
  2378. Vector2.prototype.addToRef = function (otherVector, result) {
  2379. result.x = this.x + otherVector.x;
  2380. result.y = this.y + otherVector.y;
  2381. return this;
  2382. };
  2383. /**
  2384. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2385. * @param otherVector defines the other vector
  2386. * @returns the current updated Vector2
  2387. */
  2388. Vector2.prototype.addInPlace = function (otherVector) {
  2389. this.x += otherVector.x;
  2390. this.y += otherVector.y;
  2391. return this;
  2392. };
  2393. /**
  2394. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2395. * @param otherVector defines the other vector
  2396. * @returns a new Vector2
  2397. */
  2398. Vector2.prototype.addVector3 = function (otherVector) {
  2399. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2400. };
  2401. /**
  2402. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2403. * @param otherVector defines the other vector
  2404. * @returns a new Vector2
  2405. */
  2406. Vector2.prototype.subtract = function (otherVector) {
  2407. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2408. };
  2409. /**
  2410. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2411. * @param otherVector defines the other vector
  2412. * @param result defines the target vector
  2413. * @returns the unmodified current Vector2
  2414. */
  2415. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2416. result.x = this.x - otherVector.x;
  2417. result.y = this.y - otherVector.y;
  2418. return this;
  2419. };
  2420. /**
  2421. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2422. * @param otherVector defines the other vector
  2423. * @returns the current updated Vector2
  2424. */
  2425. Vector2.prototype.subtractInPlace = function (otherVector) {
  2426. this.x -= otherVector.x;
  2427. this.y -= otherVector.y;
  2428. return this;
  2429. };
  2430. /**
  2431. * Multiplies in place the current Vector2 coordinates by the given ones
  2432. * @param otherVector defines the other vector
  2433. * @returns the current updated Vector2
  2434. */
  2435. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2436. this.x *= otherVector.x;
  2437. this.y *= otherVector.y;
  2438. return this;
  2439. };
  2440. /**
  2441. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2442. * @param otherVector defines the other vector
  2443. * @returns a new Vector2
  2444. */
  2445. Vector2.prototype.multiply = function (otherVector) {
  2446. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2447. };
  2448. /**
  2449. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2450. * @param otherVector defines the other vector
  2451. * @param result defines the target vector
  2452. * @returns the unmodified current Vector2
  2453. */
  2454. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2455. result.x = this.x * otherVector.x;
  2456. result.y = this.y * otherVector.y;
  2457. return this;
  2458. };
  2459. /**
  2460. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2461. * @param x defines the first coordinate
  2462. * @param y defines the second coordinate
  2463. * @returns a new Vector2
  2464. */
  2465. Vector2.prototype.multiplyByFloats = function (x, y) {
  2466. return new Vector2(this.x * x, this.y * y);
  2467. };
  2468. /**
  2469. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2470. * @param otherVector defines the other vector
  2471. * @returns a new Vector2
  2472. */
  2473. Vector2.prototype.divide = function (otherVector) {
  2474. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2475. };
  2476. /**
  2477. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2478. * @param otherVector defines the other vector
  2479. * @param result defines the target vector
  2480. * @returns the unmodified current Vector2
  2481. */
  2482. Vector2.prototype.divideToRef = function (otherVector, result) {
  2483. result.x = this.x / otherVector.x;
  2484. result.y = this.y / otherVector.y;
  2485. return this;
  2486. };
  2487. /**
  2488. * Divides the current Vector2 coordinates by the given ones
  2489. * @param otherVector defines the other vector
  2490. * @returns the current updated Vector2
  2491. */
  2492. Vector2.prototype.divideInPlace = function (otherVector) {
  2493. return this.divideToRef(otherVector, this);
  2494. };
  2495. /**
  2496. * Gets a new Vector2 with current Vector2 negated coordinates
  2497. * @returns a new Vector2
  2498. */
  2499. Vector2.prototype.negate = function () {
  2500. return new Vector2(-this.x, -this.y);
  2501. };
  2502. /**
  2503. * Multiply the Vector2 coordinates by scale
  2504. * @param scale defines the scaling factor
  2505. * @returns the current updated Vector2
  2506. */
  2507. Vector2.prototype.scaleInPlace = function (scale) {
  2508. this.x *= scale;
  2509. this.y *= scale;
  2510. return this;
  2511. };
  2512. /**
  2513. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2514. * @param scale defines the scaling factor
  2515. * @returns a new Vector2
  2516. */
  2517. Vector2.prototype.scale = function (scale) {
  2518. var result = new Vector2(0, 0);
  2519. this.scaleToRef(scale, result);
  2520. return result;
  2521. };
  2522. /**
  2523. * Scale the current Vector2 values by a factor to a given Vector2
  2524. * @param scale defines the scale factor
  2525. * @param result defines the Vector2 object where to store the result
  2526. * @returns the unmodified current Vector2
  2527. */
  2528. Vector2.prototype.scaleToRef = function (scale, result) {
  2529. result.x = this.x * scale;
  2530. result.y = this.y * scale;
  2531. return this;
  2532. };
  2533. /**
  2534. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2535. * @param scale defines the scale factor
  2536. * @param result defines the Vector2 object where to store the result
  2537. * @returns the unmodified current Vector2
  2538. */
  2539. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2540. result.x += this.x * scale;
  2541. result.y += this.y * scale;
  2542. return this;
  2543. };
  2544. /**
  2545. * Gets a boolean if two vectors are equals
  2546. * @param otherVector defines the other vector
  2547. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2548. */
  2549. Vector2.prototype.equals = function (otherVector) {
  2550. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2551. };
  2552. /**
  2553. * Gets a boolean if two vectors are equals (using an epsilon value)
  2554. * @param otherVector defines the other vector
  2555. * @param epsilon defines the minimal distance to consider equality
  2556. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2557. */
  2558. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2559. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2560. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2561. };
  2562. /**
  2563. * Gets a new Vector2 from current Vector2 floored values
  2564. * @returns a new Vector2
  2565. */
  2566. Vector2.prototype.floor = function () {
  2567. return new Vector2(Math.floor(this.x), Math.floor(this.y));
  2568. };
  2569. /**
  2570. * Gets a new Vector2 from current Vector2 floored values
  2571. * @returns a new Vector2
  2572. */
  2573. Vector2.prototype.fract = function () {
  2574. return new Vector2(this.x - Math.floor(this.x), this.y - Math.floor(this.y));
  2575. };
  2576. // Properties
  2577. /**
  2578. * Gets the length of the vector
  2579. * @returns the vector length (float)
  2580. */
  2581. Vector2.prototype.length = function () {
  2582. return Math.sqrt(this.x * this.x + this.y * this.y);
  2583. };
  2584. /**
  2585. * Gets the vector squared length
  2586. * @returns the vector squared length (float)
  2587. */
  2588. Vector2.prototype.lengthSquared = function () {
  2589. return (this.x * this.x + this.y * this.y);
  2590. };
  2591. // Methods
  2592. /**
  2593. * Normalize the vector
  2594. * @returns the current updated Vector2
  2595. */
  2596. Vector2.prototype.normalize = function () {
  2597. var len = this.length();
  2598. if (len === 0)
  2599. return this;
  2600. var num = 1.0 / len;
  2601. this.x *= num;
  2602. this.y *= num;
  2603. return this;
  2604. };
  2605. /**
  2606. * Gets a new Vector2 copied from the Vector2
  2607. * @returns a new Vector2
  2608. */
  2609. Vector2.prototype.clone = function () {
  2610. return new Vector2(this.x, this.y);
  2611. };
  2612. // Statics
  2613. /**
  2614. * Gets a new Vector2(0, 0)
  2615. * @returns a new Vector2
  2616. */
  2617. Vector2.Zero = function () {
  2618. return new Vector2(0, 0);
  2619. };
  2620. /**
  2621. * Gets a new Vector2(1, 1)
  2622. * @returns a new Vector2
  2623. */
  2624. Vector2.One = function () {
  2625. return new Vector2(1, 1);
  2626. };
  2627. /**
  2628. * Gets a new Vector2 set from the given index element of the given array
  2629. * @param array defines the data source
  2630. * @param offset defines the offset in the data source
  2631. * @returns a new Vector2
  2632. */
  2633. Vector2.FromArray = function (array, offset) {
  2634. if (offset === void 0) { offset = 0; }
  2635. return new Vector2(array[offset], array[offset + 1]);
  2636. };
  2637. /**
  2638. * Sets "result" from the given index element of the given array
  2639. * @param array defines the data source
  2640. * @param offset defines the offset in the data source
  2641. * @param result defines the target vector
  2642. */
  2643. Vector2.FromArrayToRef = function (array, offset, result) {
  2644. result.x = array[offset];
  2645. result.y = array[offset + 1];
  2646. };
  2647. /**
  2648. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2649. * @param value1 defines 1st point of control
  2650. * @param value2 defines 2nd point of control
  2651. * @param value3 defines 3rd point of control
  2652. * @param value4 defines 4th point of control
  2653. * @param amount defines the interpolation factor
  2654. * @returns a new Vector2
  2655. */
  2656. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2657. var squared = amount * amount;
  2658. var cubed = amount * squared;
  2659. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2660. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2661. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2662. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2663. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2664. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2665. return new Vector2(x, y);
  2666. };
  2667. /**
  2668. * 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".
  2669. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2670. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2671. * @param value defines the value to clamp
  2672. * @param min defines the lower limit
  2673. * @param max defines the upper limit
  2674. * @returns a new Vector2
  2675. */
  2676. Vector2.Clamp = function (value, min, max) {
  2677. var x = value.x;
  2678. x = (x > max.x) ? max.x : x;
  2679. x = (x < min.x) ? min.x : x;
  2680. var y = value.y;
  2681. y = (y > max.y) ? max.y : y;
  2682. y = (y < min.y) ? min.y : y;
  2683. return new Vector2(x, y);
  2684. };
  2685. /**
  2686. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2687. * @param value1 defines the 1st control point
  2688. * @param tangent1 defines the outgoing tangent
  2689. * @param value2 defines the 2nd control point
  2690. * @param tangent2 defines the incoming tangent
  2691. * @param amount defines the interpolation factor
  2692. * @returns a new Vector2
  2693. */
  2694. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2695. var squared = amount * amount;
  2696. var cubed = amount * squared;
  2697. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2698. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2699. var part3 = (cubed - (2.0 * squared)) + amount;
  2700. var part4 = cubed - squared;
  2701. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2702. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2703. return new Vector2(x, y);
  2704. };
  2705. /**
  2706. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2707. * @param start defines the start vector
  2708. * @param end defines the end vector
  2709. * @param amount defines the interpolation factor
  2710. * @returns a new Vector2
  2711. */
  2712. Vector2.Lerp = function (start, end, amount) {
  2713. var x = start.x + ((end.x - start.x) * amount);
  2714. var y = start.y + ((end.y - start.y) * amount);
  2715. return new Vector2(x, y);
  2716. };
  2717. /**
  2718. * Gets the dot product of the vector "left" and the vector "right"
  2719. * @param left defines first vector
  2720. * @param right defines second vector
  2721. * @returns the dot product (float)
  2722. */
  2723. Vector2.Dot = function (left, right) {
  2724. return left.x * right.x + left.y * right.y;
  2725. };
  2726. /**
  2727. * Returns a new Vector2 equal to the normalized given vector
  2728. * @param vector defines the vector to normalize
  2729. * @returns a new Vector2
  2730. */
  2731. Vector2.Normalize = function (vector) {
  2732. var newVector = vector.clone();
  2733. newVector.normalize();
  2734. return newVector;
  2735. };
  2736. /**
  2737. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2738. * @param left defines 1st vector
  2739. * @param right defines 2nd vector
  2740. * @returns a new Vector2
  2741. */
  2742. Vector2.Minimize = function (left, right) {
  2743. var x = (left.x < right.x) ? left.x : right.x;
  2744. var y = (left.y < right.y) ? left.y : right.y;
  2745. return new Vector2(x, y);
  2746. };
  2747. /**
  2748. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2749. * @param left defines 1st vector
  2750. * @param right defines 2nd vector
  2751. * @returns a new Vector2
  2752. */
  2753. Vector2.Maximize = function (left, right) {
  2754. var x = (left.x > right.x) ? left.x : right.x;
  2755. var y = (left.y > right.y) ? left.y : right.y;
  2756. return new Vector2(x, y);
  2757. };
  2758. /**
  2759. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2760. * @param vector defines the vector to transform
  2761. * @param transformation defines the matrix to apply
  2762. * @returns a new Vector2
  2763. */
  2764. Vector2.Transform = function (vector, transformation) {
  2765. var r = Vector2.Zero();
  2766. Vector2.TransformToRef(vector, transformation, r);
  2767. return r;
  2768. };
  2769. /**
  2770. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2771. * @param vector defines the vector to transform
  2772. * @param transformation defines the matrix to apply
  2773. * @param result defines the target vector
  2774. */
  2775. Vector2.TransformToRef = function (vector, transformation, result) {
  2776. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2777. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2778. result.x = x;
  2779. result.y = y;
  2780. };
  2781. /**
  2782. * Determines if a given vector is included in a triangle
  2783. * @param p defines the vector to test
  2784. * @param p0 defines 1st triangle point
  2785. * @param p1 defines 2nd triangle point
  2786. * @param p2 defines 3rd triangle point
  2787. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2788. */
  2789. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2790. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2791. var sign = a < 0 ? -1 : 1;
  2792. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2793. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2794. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2795. };
  2796. /**
  2797. * Gets the distance between the vectors "value1" and "value2"
  2798. * @param value1 defines first vector
  2799. * @param value2 defines second vector
  2800. * @returns the distance between vectors
  2801. */
  2802. Vector2.Distance = function (value1, value2) {
  2803. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2804. };
  2805. /**
  2806. * Returns the squared distance between the vectors "value1" and "value2"
  2807. * @param value1 defines first vector
  2808. * @param value2 defines second vector
  2809. * @returns the squared distance between vectors
  2810. */
  2811. Vector2.DistanceSquared = function (value1, value2) {
  2812. var x = value1.x - value2.x;
  2813. var y = value1.y - value2.y;
  2814. return (x * x) + (y * y);
  2815. };
  2816. /**
  2817. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2818. * @param value1 defines first vector
  2819. * @param value2 defines second vector
  2820. * @returns a new Vector2
  2821. */
  2822. Vector2.Center = function (value1, value2) {
  2823. var center = value1.add(value2);
  2824. center.scaleInPlace(0.5);
  2825. return center;
  2826. };
  2827. /**
  2828. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2829. * @param p defines the middle point
  2830. * @param segA defines one point of the segment
  2831. * @param segB defines the other point of the segment
  2832. * @returns the shortest distance
  2833. */
  2834. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2835. var l2 = Vector2.DistanceSquared(segA, segB);
  2836. if (l2 === 0.0) {
  2837. return Vector2.Distance(p, segA);
  2838. }
  2839. var v = segB.subtract(segA);
  2840. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2841. var proj = segA.add(v.multiplyByFloats(t, t));
  2842. return Vector2.Distance(p, proj);
  2843. };
  2844. return Vector2;
  2845. }());
  2846. BABYLON.Vector2 = Vector2;
  2847. /**
  2848. * Classed used to store (x,y,z) vector representation
  2849. * A Vector3 is the main object used in 3D geometry
  2850. * It can represent etiher the coordinates of a point the space, either a direction
  2851. * Reminder: Babylon.js uses a left handed forward facing system
  2852. */
  2853. var Vector3 = /** @class */ (function () {
  2854. /**
  2855. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2856. * @param x defines the first coordinates (on X axis)
  2857. * @param y defines the second coordinates (on Y axis)
  2858. * @param z defines the third coordinates (on Z axis)
  2859. */
  2860. function Vector3(
  2861. /**
  2862. * Defines the first coordinates (on X axis)
  2863. */
  2864. x,
  2865. /**
  2866. * Defines the second coordinates (on Y axis)
  2867. */
  2868. y,
  2869. /**
  2870. * Defines the third coordinates (on Z axis)
  2871. */
  2872. z) {
  2873. if (x === void 0) { x = 0; }
  2874. if (y === void 0) { y = 0; }
  2875. if (z === void 0) { z = 0; }
  2876. this.x = x;
  2877. this.y = y;
  2878. this.z = z;
  2879. }
  2880. /**
  2881. * Creates a string representation of the Vector3
  2882. * @returns a string with the Vector3 coordinates.
  2883. */
  2884. Vector3.prototype.toString = function () {
  2885. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2886. };
  2887. /**
  2888. * Gets the class name
  2889. * @returns the string "Vector3"
  2890. */
  2891. Vector3.prototype.getClassName = function () {
  2892. return "Vector3";
  2893. };
  2894. /**
  2895. * Creates the Vector3 hash code
  2896. * @returns a number which tends to be unique between Vector3 instances
  2897. */
  2898. Vector3.prototype.getHashCode = function () {
  2899. var hash = this.x || 0;
  2900. hash = (hash * 397) ^ (this.y || 0);
  2901. hash = (hash * 397) ^ (this.z || 0);
  2902. return hash;
  2903. };
  2904. // Operators
  2905. /**
  2906. * Creates an array containing three elements : the coordinates of the Vector3
  2907. * @returns a new array of numbers
  2908. */
  2909. Vector3.prototype.asArray = function () {
  2910. var result = [];
  2911. this.toArray(result, 0);
  2912. return result;
  2913. };
  2914. /**
  2915. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2916. * @param array defines the destination array
  2917. * @param index defines the offset in the destination array
  2918. * @returns the current Vector3
  2919. */
  2920. Vector3.prototype.toArray = function (array, index) {
  2921. if (index === void 0) { index = 0; }
  2922. array[index] = this.x;
  2923. array[index + 1] = this.y;
  2924. array[index + 2] = this.z;
  2925. return this;
  2926. };
  2927. /**
  2928. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2929. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2930. */
  2931. Vector3.prototype.toQuaternion = function () {
  2932. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2933. };
  2934. /**
  2935. * Adds the given vector to the current Vector3
  2936. * @param otherVector defines the second operand
  2937. * @returns the current updated Vector3
  2938. */
  2939. Vector3.prototype.addInPlace = function (otherVector) {
  2940. this.x += otherVector.x;
  2941. this.y += otherVector.y;
  2942. this.z += otherVector.z;
  2943. return this;
  2944. };
  2945. /**
  2946. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2947. * @param otherVector defines the second operand
  2948. * @returns the resulting Vector3
  2949. */
  2950. Vector3.prototype.add = function (otherVector) {
  2951. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2952. };
  2953. /**
  2954. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2955. * @param otherVector defines the second operand
  2956. * @param result defines the Vector3 object where to store the result
  2957. * @returns the current Vector3
  2958. */
  2959. Vector3.prototype.addToRef = function (otherVector, result) {
  2960. result.x = this.x + otherVector.x;
  2961. result.y = this.y + otherVector.y;
  2962. result.z = this.z + otherVector.z;
  2963. return this;
  2964. };
  2965. /**
  2966. * Subtract the given vector from the current Vector3
  2967. * @param otherVector defines the second operand
  2968. * @returns the current updated Vector3
  2969. */
  2970. Vector3.prototype.subtractInPlace = function (otherVector) {
  2971. this.x -= otherVector.x;
  2972. this.y -= otherVector.y;
  2973. this.z -= otherVector.z;
  2974. return this;
  2975. };
  2976. /**
  2977. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2978. * @param otherVector defines the second operand
  2979. * @returns the resulting Vector3
  2980. */
  2981. Vector3.prototype.subtract = function (otherVector) {
  2982. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2983. };
  2984. /**
  2985. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2986. * @param otherVector defines the second operand
  2987. * @param result defines the Vector3 object where to store the result
  2988. * @returns the current Vector3
  2989. */
  2990. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2991. result.x = this.x - otherVector.x;
  2992. result.y = this.y - otherVector.y;
  2993. result.z = this.z - otherVector.z;
  2994. return this;
  2995. };
  2996. /**
  2997. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2998. * @param x defines the x coordinate of the operand
  2999. * @param y defines the y coordinate of the operand
  3000. * @param z defines the z coordinate of the operand
  3001. * @returns the resulting Vector3
  3002. */
  3003. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  3004. return new Vector3(this.x - x, this.y - y, this.z - z);
  3005. };
  3006. /**
  3007. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  3008. * @param x defines the x coordinate of the operand
  3009. * @param y defines the y coordinate of the operand
  3010. * @param z defines the z coordinate of the operand
  3011. * @param result defines the Vector3 object where to store the result
  3012. * @returns the current Vector3
  3013. */
  3014. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  3015. result.x = this.x - x;
  3016. result.y = this.y - y;
  3017. result.z = this.z - z;
  3018. return this;
  3019. };
  3020. /**
  3021. * Gets a new Vector3 set with the current Vector3 negated coordinates
  3022. * @returns a new Vector3
  3023. */
  3024. Vector3.prototype.negate = function () {
  3025. return new Vector3(-this.x, -this.y, -this.z);
  3026. };
  3027. /**
  3028. * Multiplies the Vector3 coordinates by the float "scale"
  3029. * @param scale defines the multiplier factor
  3030. * @returns the current updated Vector3
  3031. */
  3032. Vector3.prototype.scaleInPlace = function (scale) {
  3033. this.x *= scale;
  3034. this.y *= scale;
  3035. this.z *= scale;
  3036. return this;
  3037. };
  3038. /**
  3039. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  3040. * @param scale defines the multiplier factor
  3041. * @returns a new Vector3
  3042. */
  3043. Vector3.prototype.scale = function (scale) {
  3044. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  3045. };
  3046. /**
  3047. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  3048. * @param scale defines the multiplier factor
  3049. * @param result defines the Vector3 object where to store the result
  3050. * @returns the current Vector3
  3051. */
  3052. Vector3.prototype.scaleToRef = function (scale, result) {
  3053. result.x = this.x * scale;
  3054. result.y = this.y * scale;
  3055. result.z = this.z * scale;
  3056. return this;
  3057. };
  3058. /**
  3059. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  3060. * @param scale defines the scale factor
  3061. * @param result defines the Vector3 object where to store the result
  3062. * @returns the unmodified current Vector3
  3063. */
  3064. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  3065. result.x += this.x * scale;
  3066. result.y += this.y * scale;
  3067. result.z += this.z * scale;
  3068. return this;
  3069. };
  3070. /**
  3071. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  3072. * @param otherVector defines the second operand
  3073. * @returns true if both vectors are equals
  3074. */
  3075. Vector3.prototype.equals = function (otherVector) {
  3076. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  3077. };
  3078. /**
  3079. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  3080. * @param otherVector defines the second operand
  3081. * @param epsilon defines the minimal distance to define values as equals
  3082. * @returns true if both vectors are distant less than epsilon
  3083. */
  3084. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3085. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3086. 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);
  3087. };
  3088. /**
  3089. * Returns true if the current Vector3 coordinates equals the given floats
  3090. * @param x defines the x coordinate of the operand
  3091. * @param y defines the y coordinate of the operand
  3092. * @param z defines the z coordinate of the operand
  3093. * @returns true if both vectors are equals
  3094. */
  3095. Vector3.prototype.equalsToFloats = function (x, y, z) {
  3096. return this.x === x && this.y === y && this.z === z;
  3097. };
  3098. /**
  3099. * Multiplies the current Vector3 coordinates by the given ones
  3100. * @param otherVector defines the second operand
  3101. * @returns the current updated Vector3
  3102. */
  3103. Vector3.prototype.multiplyInPlace = function (otherVector) {
  3104. this.x *= otherVector.x;
  3105. this.y *= otherVector.y;
  3106. this.z *= otherVector.z;
  3107. return this;
  3108. };
  3109. /**
  3110. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  3111. * @param otherVector defines the second operand
  3112. * @returns the new Vector3
  3113. */
  3114. Vector3.prototype.multiply = function (otherVector) {
  3115. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3116. };
  3117. /**
  3118. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3119. * @param otherVector defines the second operand
  3120. * @param result defines the Vector3 object where to store the result
  3121. * @returns the current Vector3
  3122. */
  3123. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3124. result.x = this.x * otherVector.x;
  3125. result.y = this.y * otherVector.y;
  3126. result.z = this.z * otherVector.z;
  3127. return this;
  3128. };
  3129. /**
  3130. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3131. * @param x defines the x coordinate of the operand
  3132. * @param y defines the y coordinate of the operand
  3133. * @param z defines the z coordinate of the operand
  3134. * @returns the new Vector3
  3135. */
  3136. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3137. return new Vector3(this.x * x, this.y * y, this.z * z);
  3138. };
  3139. /**
  3140. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3141. * @param otherVector defines the second operand
  3142. * @returns the new Vector3
  3143. */
  3144. Vector3.prototype.divide = function (otherVector) {
  3145. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3146. };
  3147. /**
  3148. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3149. * @param otherVector defines the second operand
  3150. * @param result defines the Vector3 object where to store the result
  3151. * @returns the current Vector3
  3152. */
  3153. Vector3.prototype.divideToRef = function (otherVector, result) {
  3154. result.x = this.x / otherVector.x;
  3155. result.y = this.y / otherVector.y;
  3156. result.z = this.z / otherVector.z;
  3157. return this;
  3158. };
  3159. /**
  3160. * Divides the current Vector3 coordinates by the given ones.
  3161. * @param otherVector defines the second operand
  3162. * @returns the current updated Vector3
  3163. */
  3164. Vector3.prototype.divideInPlace = function (otherVector) {
  3165. return this.divideToRef(otherVector, this);
  3166. };
  3167. /**
  3168. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3169. * @param other defines the second operand
  3170. * @returns the current updated Vector3
  3171. */
  3172. Vector3.prototype.minimizeInPlace = function (other) {
  3173. return this.minimizeInPlaceFromFloats(other.x, other.y, other.z);
  3174. };
  3175. /**
  3176. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3177. * @param other defines the second operand
  3178. * @returns the current updated Vector3
  3179. */
  3180. Vector3.prototype.maximizeInPlace = function (other) {
  3181. return this.maximizeInPlaceFromFloats(other.x, other.y, other.z);
  3182. };
  3183. /**
  3184. * Updates the current Vector3 with the minimal coordinate values between its and the given coordinates
  3185. * @param x defines the x coordinate of the operand
  3186. * @param y defines the y coordinate of the operand
  3187. * @param z defines the z coordinate of the operand
  3188. * @returns the current updated Vector3
  3189. */
  3190. Vector3.prototype.minimizeInPlaceFromFloats = function (x, y, z) {
  3191. this.x = Math.min(this.x, x);
  3192. this.y = Math.min(this.y, y);
  3193. this.z = Math.min(this.z, z);
  3194. return this;
  3195. };
  3196. /**
  3197. * Updates the current Vector3 with the maximal coordinate values between its and the given coordinates.
  3198. * @param x defines the x coordinate of the operand
  3199. * @param y defines the y coordinate of the operand
  3200. * @param z defines the z coordinate of the operand
  3201. * @returns the current updated Vector3
  3202. */
  3203. Vector3.prototype.maximizeInPlaceFromFloats = function (x, y, z) {
  3204. this.x = Math.max(this.x, x);
  3205. this.y = Math.max(this.y, y);
  3206. this.z = Math.max(this.z, z);
  3207. return this;
  3208. };
  3209. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3210. /**
  3211. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3212. */
  3213. get: function () {
  3214. var absX = Math.abs(this.x);
  3215. var absY = Math.abs(this.y);
  3216. if (absX !== absY) {
  3217. return true;
  3218. }
  3219. var absZ = Math.abs(this.z);
  3220. if (absX !== absZ) {
  3221. return true;
  3222. }
  3223. if (absY !== absZ) {
  3224. return true;
  3225. }
  3226. return false;
  3227. },
  3228. enumerable: true,
  3229. configurable: true
  3230. });
  3231. /**
  3232. * Gets a new Vector3 from current Vector3 floored values
  3233. * @returns a new Vector3
  3234. */
  3235. Vector3.prototype.floor = function () {
  3236. return new Vector3(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z));
  3237. };
  3238. /**
  3239. * Gets a new Vector3 from current Vector3 floored values
  3240. * @returns a new Vector3
  3241. */
  3242. Vector3.prototype.fract = function () {
  3243. return new Vector3(this.x - Math.floor(this.x), this.y - Math.floor(this.y), this.z - Math.floor(this.z));
  3244. };
  3245. // Properties
  3246. /**
  3247. * Gets the length of the Vector3
  3248. * @returns the length of the Vecto3
  3249. */
  3250. Vector3.prototype.length = function () {
  3251. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3252. };
  3253. /**
  3254. * Gets the squared length of the Vector3
  3255. * @returns squared length of the Vector3
  3256. */
  3257. Vector3.prototype.lengthSquared = function () {
  3258. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3259. };
  3260. /**
  3261. * Normalize the current Vector3.
  3262. * Please note that this is an in place operation.
  3263. * @returns the current updated Vector3
  3264. */
  3265. Vector3.prototype.normalize = function () {
  3266. var len = this.length();
  3267. if (len === 0 || len === 1.0)
  3268. return this;
  3269. var num = 1.0 / len;
  3270. this.x *= num;
  3271. this.y *= num;
  3272. this.z *= num;
  3273. return this;
  3274. };
  3275. /**
  3276. * Normalize the current Vector3 to a new vector
  3277. * @returns the new Vector3
  3278. */
  3279. Vector3.prototype.normalizeToNew = function () {
  3280. var normalized = new Vector3(0, 0, 0);
  3281. this.normalizeToRef(normalized);
  3282. return normalized;
  3283. };
  3284. /**
  3285. * Normalize the current Vector3 to the reference
  3286. * @param reference define the Vector3 to update
  3287. * @returns the updated Vector3
  3288. */
  3289. Vector3.prototype.normalizeToRef = function (reference) {
  3290. var len = this.length();
  3291. if (len === 0 || len === 1.0) {
  3292. reference.set(this.x, this.y, this.z);
  3293. return reference;
  3294. }
  3295. var scale = 1.0 / len;
  3296. this.scaleToRef(scale, reference);
  3297. return reference;
  3298. };
  3299. /**
  3300. * Creates a new Vector3 copied from the current Vector3
  3301. * @returns the new Vector3
  3302. */
  3303. Vector3.prototype.clone = function () {
  3304. return new Vector3(this.x, this.y, this.z);
  3305. };
  3306. /**
  3307. * Copies the given vector coordinates to the current Vector3 ones
  3308. * @param source defines the source Vector3
  3309. * @returns the current updated Vector3
  3310. */
  3311. Vector3.prototype.copyFrom = function (source) {
  3312. this.x = source.x;
  3313. this.y = source.y;
  3314. this.z = source.z;
  3315. return this;
  3316. };
  3317. /**
  3318. * Copies the given floats to the current Vector3 coordinates
  3319. * @param x defines the x coordinate of the operand
  3320. * @param y defines the y coordinate of the operand
  3321. * @param z defines the z coordinate of the operand
  3322. * @returns the current updated Vector3
  3323. */
  3324. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3325. this.x = x;
  3326. this.y = y;
  3327. this.z = z;
  3328. return this;
  3329. };
  3330. /**
  3331. * Copies the given floats to the current Vector3 coordinates
  3332. * @param x defines the x coordinate of the operand
  3333. * @param y defines the y coordinate of the operand
  3334. * @param z defines the z coordinate of the operand
  3335. * @returns the current updated Vector3
  3336. */
  3337. Vector3.prototype.set = function (x, y, z) {
  3338. return this.copyFromFloats(x, y, z);
  3339. };
  3340. // Statics
  3341. /**
  3342. * Get the clip factor between two vectors
  3343. * @param vector0 defines the first operand
  3344. * @param vector1 defines the second operand
  3345. * @param axis defines the axis to use
  3346. * @param size defines the size along the axis
  3347. * @returns the clip factor
  3348. */
  3349. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3350. var d0 = Vector3.Dot(vector0, axis) - size;
  3351. var d1 = Vector3.Dot(vector1, axis) - size;
  3352. var s = d0 / (d0 - d1);
  3353. return s;
  3354. };
  3355. /**
  3356. * Get angle between two vectors
  3357. * @param vector0 angle between vector0 and vector1
  3358. * @param vector1 angle between vector0 and vector1
  3359. * @param normal direction of the normal
  3360. * @return the angle between vector0 and vector1
  3361. */
  3362. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3363. var v0 = vector0.clone().normalize();
  3364. var v1 = vector1.clone().normalize();
  3365. var dot = Vector3.Dot(v0, v1);
  3366. var n = Vector3.Cross(v0, v1);
  3367. if (Vector3.Dot(n, normal) > 0) {
  3368. return Math.acos(dot);
  3369. }
  3370. return -Math.acos(dot);
  3371. };
  3372. /**
  3373. * Returns a new Vector3 set from the index "offset" of the given array
  3374. * @param array defines the source array
  3375. * @param offset defines the offset in the source array
  3376. * @returns the new Vector3
  3377. */
  3378. Vector3.FromArray = function (array, offset) {
  3379. if (!offset) {
  3380. offset = 0;
  3381. }
  3382. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3383. };
  3384. /**
  3385. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3386. * This function is deprecated. Use FromArray instead
  3387. * @param array defines the source array
  3388. * @param offset defines the offset in the source array
  3389. * @returns the new Vector3
  3390. */
  3391. Vector3.FromFloatArray = function (array, offset) {
  3392. return Vector3.FromArray(array, offset);
  3393. };
  3394. /**
  3395. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3396. * @param array defines the source array
  3397. * @param offset defines the offset in the source array
  3398. * @param result defines the Vector3 where to store the result
  3399. */
  3400. Vector3.FromArrayToRef = function (array, offset, result) {
  3401. result.x = array[offset];
  3402. result.y = array[offset + 1];
  3403. result.z = array[offset + 2];
  3404. };
  3405. /**
  3406. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3407. * This function is deprecated. Use FromArrayToRef instead.
  3408. * @param array defines the source array
  3409. * @param offset defines the offset in the source array
  3410. * @param result defines the Vector3 where to store the result
  3411. */
  3412. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3413. return Vector3.FromArrayToRef(array, offset, result);
  3414. };
  3415. /**
  3416. * Sets the given vector "result" with the given floats.
  3417. * @param x defines the x coordinate of the source
  3418. * @param y defines the y coordinate of the source
  3419. * @param z defines the z coordinate of the source
  3420. * @param result defines the Vector3 where to store the result
  3421. */
  3422. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3423. result.x = x;
  3424. result.y = y;
  3425. result.z = z;
  3426. };
  3427. /**
  3428. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3429. * @returns a new empty Vector3
  3430. */
  3431. Vector3.Zero = function () {
  3432. return new Vector3(0.0, 0.0, 0.0);
  3433. };
  3434. /**
  3435. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3436. * @returns a new unit Vector3
  3437. */
  3438. Vector3.One = function () {
  3439. return new Vector3(1.0, 1.0, 1.0);
  3440. };
  3441. /**
  3442. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3443. * @returns a new up Vector3
  3444. */
  3445. Vector3.Up = function () {
  3446. return new Vector3(0.0, 1.0, 0.0);
  3447. };
  3448. /**
  3449. * Returns a new Vector3 set to (0.0, -1.0, 0.0)
  3450. * @returns a new down Vector3
  3451. */
  3452. Vector3.Down = function () {
  3453. return new Vector3(0.0, -1.0, 0.0);
  3454. };
  3455. /**
  3456. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3457. * @returns a new forward Vector3
  3458. */
  3459. Vector3.Forward = function () {
  3460. return new Vector3(0.0, 0.0, 1.0);
  3461. };
  3462. /**
  3463. * Returns a new Vector3 set to (0.0, 0.0, -1.0)
  3464. * @returns a new forward Vector3
  3465. */
  3466. Vector3.Backward = function () {
  3467. return new Vector3(0.0, 0.0, -1.0);
  3468. };
  3469. /**
  3470. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3471. * @returns a new right Vector3
  3472. */
  3473. Vector3.Right = function () {
  3474. return new Vector3(1.0, 0.0, 0.0);
  3475. };
  3476. /**
  3477. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3478. * @returns a new left Vector3
  3479. */
  3480. Vector3.Left = function () {
  3481. return new Vector3(-1.0, 0.0, 0.0);
  3482. };
  3483. /**
  3484. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3485. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3486. * @param vector defines the Vector3 to transform
  3487. * @param transformation defines the transformation matrix
  3488. * @returns the transformed Vector3
  3489. */
  3490. Vector3.TransformCoordinates = function (vector, transformation) {
  3491. var result = Vector3.Zero();
  3492. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3493. return result;
  3494. };
  3495. /**
  3496. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3497. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3498. * @param vector defines the Vector3 to transform
  3499. * @param transformation defines the transformation matrix
  3500. * @param result defines the Vector3 where to store the result
  3501. */
  3502. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3503. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3504. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3505. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3506. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3507. result.x = x / w;
  3508. result.y = y / w;
  3509. result.z = z / w;
  3510. };
  3511. /**
  3512. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3513. * This method computes tranformed coordinates only, not transformed direction vectors
  3514. * @param x define the x coordinate of the source vector
  3515. * @param y define the y coordinate of the source vector
  3516. * @param z define the z coordinate of the source vector
  3517. * @param transformation defines the transformation matrix
  3518. * @param result defines the Vector3 where to store the result
  3519. */
  3520. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3521. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3522. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3523. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3524. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3525. result.x = rx / rw;
  3526. result.y = ry / rw;
  3527. result.z = rz / rw;
  3528. };
  3529. /**
  3530. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3531. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3532. * @param vector defines the Vector3 to transform
  3533. * @param transformation defines the transformation matrix
  3534. * @returns the new Vector3
  3535. */
  3536. Vector3.TransformNormal = function (vector, transformation) {
  3537. var result = Vector3.Zero();
  3538. Vector3.TransformNormalToRef(vector, transformation, result);
  3539. return result;
  3540. };
  3541. /**
  3542. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3543. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3544. * @param vector defines the Vector3 to transform
  3545. * @param transformation defines the transformation matrix
  3546. * @param result defines the Vector3 where to store the result
  3547. */
  3548. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3549. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3550. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3551. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3552. result.x = x;
  3553. result.y = y;
  3554. result.z = z;
  3555. };
  3556. /**
  3557. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3558. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3559. * @param x define the x coordinate of the source vector
  3560. * @param y define the y coordinate of the source vector
  3561. * @param z define the z coordinate of the source vector
  3562. * @param transformation defines the transformation matrix
  3563. * @param result defines the Vector3 where to store the result
  3564. */
  3565. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3566. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3567. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3568. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3569. };
  3570. /**
  3571. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3572. * @param value1 defines the first control point
  3573. * @param value2 defines the second control point
  3574. * @param value3 defines the third control point
  3575. * @param value4 defines the fourth control point
  3576. * @param amount defines the amount on the spline to use
  3577. * @returns the new Vector3
  3578. */
  3579. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3580. var squared = amount * amount;
  3581. var cubed = amount * squared;
  3582. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3583. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3584. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3585. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3586. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3587. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3588. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3589. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3590. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3591. return new Vector3(x, y, z);
  3592. };
  3593. /**
  3594. * 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"
  3595. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3596. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3597. * @param value defines the current value
  3598. * @param min defines the lower range value
  3599. * @param max defines the upper range value
  3600. * @returns the new Vector3
  3601. */
  3602. Vector3.Clamp = function (value, min, max) {
  3603. var x = value.x;
  3604. x = (x > max.x) ? max.x : x;
  3605. x = (x < min.x) ? min.x : x;
  3606. var y = value.y;
  3607. y = (y > max.y) ? max.y : y;
  3608. y = (y < min.y) ? min.y : y;
  3609. var z = value.z;
  3610. z = (z > max.z) ? max.z : z;
  3611. z = (z < min.z) ? min.z : z;
  3612. return new Vector3(x, y, z);
  3613. };
  3614. /**
  3615. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3616. * @param value1 defines the first control point
  3617. * @param tangent1 defines the first tangent vector
  3618. * @param value2 defines the second control point
  3619. * @param tangent2 defines the second tangent vector
  3620. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3621. * @returns the new Vector3
  3622. */
  3623. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3624. var squared = amount * amount;
  3625. var cubed = amount * squared;
  3626. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3627. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3628. var part3 = (cubed - (2.0 * squared)) + amount;
  3629. var part4 = cubed - squared;
  3630. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3631. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3632. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3633. return new Vector3(x, y, z);
  3634. };
  3635. /**
  3636. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3637. * @param start defines the start value
  3638. * @param end defines the end value
  3639. * @param amount max defines amount between both (between 0 and 1)
  3640. * @returns the new Vector3
  3641. */
  3642. Vector3.Lerp = function (start, end, amount) {
  3643. var result = new Vector3(0, 0, 0);
  3644. Vector3.LerpToRef(start, end, amount, result);
  3645. return result;
  3646. };
  3647. /**
  3648. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3649. * @param start defines the start value
  3650. * @param end defines the end value
  3651. * @param amount max defines amount between both (between 0 and 1)
  3652. * @param result defines the Vector3 where to store the result
  3653. */
  3654. Vector3.LerpToRef = function (start, end, amount, result) {
  3655. result.x = start.x + ((end.x - start.x) * amount);
  3656. result.y = start.y + ((end.y - start.y) * amount);
  3657. result.z = start.z + ((end.z - start.z) * amount);
  3658. };
  3659. /**
  3660. * Returns the dot product (float) between the vectors "left" and "right"
  3661. * @param left defines the left operand
  3662. * @param right defines the right operand
  3663. * @returns the dot product
  3664. */
  3665. Vector3.Dot = function (left, right) {
  3666. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3667. };
  3668. /**
  3669. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3670. * The cross product is then orthogonal to both "left" and "right"
  3671. * @param left defines the left operand
  3672. * @param right defines the right operand
  3673. * @returns the cross product
  3674. */
  3675. Vector3.Cross = function (left, right) {
  3676. var result = Vector3.Zero();
  3677. Vector3.CrossToRef(left, right, result);
  3678. return result;
  3679. };
  3680. /**
  3681. * Sets the given vector "result" with the cross product of "left" and "right"
  3682. * The cross product is then orthogonal to both "left" and "right"
  3683. * @param left defines the left operand
  3684. * @param right defines the right operand
  3685. * @param result defines the Vector3 where to store the result
  3686. */
  3687. Vector3.CrossToRef = function (left, right, result) {
  3688. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3689. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3690. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3691. result.copyFrom(MathTmp.Vector3[0]);
  3692. };
  3693. /**
  3694. * Returns a new Vector3 as the normalization of the given vector
  3695. * @param vector defines the Vector3 to normalize
  3696. * @returns the new Vector3
  3697. */
  3698. Vector3.Normalize = function (vector) {
  3699. var result = Vector3.Zero();
  3700. Vector3.NormalizeToRef(vector, result);
  3701. return result;
  3702. };
  3703. /**
  3704. * Sets the given vector "result" with the normalization of the given first vector
  3705. * @param vector defines the Vector3 to normalize
  3706. * @param result defines the Vector3 where to store the result
  3707. */
  3708. Vector3.NormalizeToRef = function (vector, result) {
  3709. result.copyFrom(vector);
  3710. result.normalize();
  3711. };
  3712. /**
  3713. * Project a Vector3 onto screen space
  3714. * @param vector defines the Vector3 to project
  3715. * @param world defines the world matrix to use
  3716. * @param transform defines the transform (view x projection) matrix to use
  3717. * @param viewport defines the screen viewport to use
  3718. * @returns the new Vector3
  3719. */
  3720. Vector3.Project = function (vector, world, transform, viewport) {
  3721. var cw = viewport.width;
  3722. var ch = viewport.height;
  3723. var cx = viewport.x;
  3724. var cy = viewport.y;
  3725. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3726. 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);
  3727. var matrix = MathTmp.Matrix[0];
  3728. world.multiplyToRef(transform, matrix);
  3729. matrix.multiplyToRef(viewportMatrix, matrix);
  3730. return Vector3.TransformCoordinates(vector, matrix);
  3731. };
  3732. /**
  3733. * Unproject from screen space to object space
  3734. * @param source defines the screen space Vector3 to use
  3735. * @param viewportWidth defines the current width of the viewport
  3736. * @param viewportHeight defines the current height of the viewport
  3737. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3738. * @param transform defines the transform (view x projection) matrix to use
  3739. * @returns the new Vector3
  3740. */
  3741. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3742. var matrix = MathTmp.Matrix[0];
  3743. world.multiplyToRef(transform, matrix);
  3744. matrix.invert();
  3745. source.x = source.x / viewportWidth * 2 - 1;
  3746. source.y = -(source.y / viewportHeight * 2 - 1);
  3747. var vector = Vector3.TransformCoordinates(source, matrix);
  3748. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3749. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3750. vector = vector.scale(1.0 / num);
  3751. }
  3752. return vector;
  3753. };
  3754. /**
  3755. * Unproject from screen space to object space
  3756. * @param source defines the screen space Vector3 to use
  3757. * @param viewportWidth defines the current width of the viewport
  3758. * @param viewportHeight defines the current height of the viewport
  3759. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3760. * @param view defines the view matrix to use
  3761. * @param projection defines the projection matrix to use
  3762. * @returns the new Vector3
  3763. */
  3764. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3765. var result = Vector3.Zero();
  3766. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3767. return result;
  3768. };
  3769. /**
  3770. * Unproject from screen space to object space
  3771. * @param source defines the screen space Vector3 to use
  3772. * @param viewportWidth defines the current width of the viewport
  3773. * @param viewportHeight defines the current height of the viewport
  3774. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3775. * @param view defines the view matrix to use
  3776. * @param projection defines the projection matrix to use
  3777. * @param result defines the Vector3 where to store the result
  3778. */
  3779. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3780. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3781. };
  3782. /**
  3783. * Unproject from screen space to object space
  3784. * @param sourceX defines the screen space x coordinate to use
  3785. * @param sourceY defines the screen space y coordinate to use
  3786. * @param sourceZ defines the screen space z coordinate to use
  3787. * @param viewportWidth defines the current width of the viewport
  3788. * @param viewportHeight defines the current height of the viewport
  3789. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3790. * @param view defines the view matrix to use
  3791. * @param projection defines the projection matrix to use
  3792. * @param result defines the Vector3 where to store the result
  3793. */
  3794. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3795. var matrix = MathTmp.Matrix[0];
  3796. world.multiplyToRef(view, matrix);
  3797. matrix.multiplyToRef(projection, matrix);
  3798. matrix.invert();
  3799. var screenSource = MathTmp.Vector3[0];
  3800. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3801. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3802. screenSource.z = 2 * sourceZ - 1.0;
  3803. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3804. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3805. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3806. result.scaleInPlace(1.0 / num);
  3807. }
  3808. };
  3809. /**
  3810. * Gets the minimal coordinate values between two Vector3
  3811. * @param left defines the first operand
  3812. * @param right defines the second operand
  3813. * @returns the new Vector3
  3814. */
  3815. Vector3.Minimize = function (left, right) {
  3816. var min = left.clone();
  3817. min.minimizeInPlace(right);
  3818. return min;
  3819. };
  3820. /**
  3821. * Gets the maximal coordinate values between two Vector3
  3822. * @param left defines the first operand
  3823. * @param right defines the second operand
  3824. * @returns the new Vector3
  3825. */
  3826. Vector3.Maximize = function (left, right) {
  3827. var max = left.clone();
  3828. max.maximizeInPlace(right);
  3829. return max;
  3830. };
  3831. /**
  3832. * Returns the distance between the vectors "value1" and "value2"
  3833. * @param value1 defines the first operand
  3834. * @param value2 defines the second operand
  3835. * @returns the distance
  3836. */
  3837. Vector3.Distance = function (value1, value2) {
  3838. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3839. };
  3840. /**
  3841. * Returns the squared distance between the vectors "value1" and "value2"
  3842. * @param value1 defines the first operand
  3843. * @param value2 defines the second operand
  3844. * @returns the squared distance
  3845. */
  3846. Vector3.DistanceSquared = function (value1, value2) {
  3847. var x = value1.x - value2.x;
  3848. var y = value1.y - value2.y;
  3849. var z = value1.z - value2.z;
  3850. return (x * x) + (y * y) + (z * z);
  3851. };
  3852. /**
  3853. * Returns a new Vector3 located at the center between "value1" and "value2"
  3854. * @param value1 defines the first operand
  3855. * @param value2 defines the second operand
  3856. * @returns the new Vector3
  3857. */
  3858. Vector3.Center = function (value1, value2) {
  3859. var center = value1.add(value2);
  3860. center.scaleInPlace(0.5);
  3861. return center;
  3862. };
  3863. /**
  3864. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3865. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3866. * to something in order to rotate it from its local system to the given target system
  3867. * Note: axis1, axis2 and axis3 are normalized during this operation
  3868. * @param axis1 defines the first axis
  3869. * @param axis2 defines the second axis
  3870. * @param axis3 defines the third axis
  3871. * @returns a new Vector3
  3872. */
  3873. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3874. var rotation = Vector3.Zero();
  3875. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3876. return rotation;
  3877. };
  3878. /**
  3879. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3880. * @param axis1 defines the first axis
  3881. * @param axis2 defines the second axis
  3882. * @param axis3 defines the third axis
  3883. * @param ref defines the Vector3 where to store the result
  3884. */
  3885. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3886. var quat = MathTmp.Quaternion[0];
  3887. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3888. quat.toEulerAnglesToRef(ref);
  3889. };
  3890. return Vector3;
  3891. }());
  3892. BABYLON.Vector3 = Vector3;
  3893. /**
  3894. * Vector4 class created for EulerAngle class conversion to Quaternion
  3895. */
  3896. var Vector4 = /** @class */ (function () {
  3897. /**
  3898. * Creates a Vector4 object from the given floats.
  3899. * @param x x value of the vector
  3900. * @param y y value of the vector
  3901. * @param z z value of the vector
  3902. * @param w w value of the vector
  3903. */
  3904. function Vector4(
  3905. /** x value of the vector */
  3906. x,
  3907. /** y value of the vector */
  3908. y,
  3909. /** z value of the vector */
  3910. z,
  3911. /** w value of the vector */
  3912. w) {
  3913. this.x = x;
  3914. this.y = y;
  3915. this.z = z;
  3916. this.w = w;
  3917. }
  3918. /**
  3919. * Returns the string with the Vector4 coordinates.
  3920. * @returns a string containing all the vector values
  3921. */
  3922. Vector4.prototype.toString = function () {
  3923. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3924. };
  3925. /**
  3926. * Returns the string "Vector4".
  3927. * @returns "Vector4"
  3928. */
  3929. Vector4.prototype.getClassName = function () {
  3930. return "Vector4";
  3931. };
  3932. /**
  3933. * Returns the Vector4 hash code.
  3934. * @returns a unique hash code
  3935. */
  3936. Vector4.prototype.getHashCode = function () {
  3937. var hash = this.x || 0;
  3938. hash = (hash * 397) ^ (this.y || 0);
  3939. hash = (hash * 397) ^ (this.z || 0);
  3940. hash = (hash * 397) ^ (this.w || 0);
  3941. return hash;
  3942. };
  3943. // Operators
  3944. /**
  3945. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3946. * @returns the resulting array
  3947. */
  3948. Vector4.prototype.asArray = function () {
  3949. var result = new Array();
  3950. this.toArray(result, 0);
  3951. return result;
  3952. };
  3953. /**
  3954. * Populates the given array from the given index with the Vector4 coordinates.
  3955. * @param array array to populate
  3956. * @param index index of the array to start at (default: 0)
  3957. * @returns the Vector4.
  3958. */
  3959. Vector4.prototype.toArray = function (array, index) {
  3960. if (index === undefined) {
  3961. index = 0;
  3962. }
  3963. array[index] = this.x;
  3964. array[index + 1] = this.y;
  3965. array[index + 2] = this.z;
  3966. array[index + 3] = this.w;
  3967. return this;
  3968. };
  3969. /**
  3970. * Adds the given vector to the current Vector4.
  3971. * @param otherVector the vector to add
  3972. * @returns the updated Vector4.
  3973. */
  3974. Vector4.prototype.addInPlace = function (otherVector) {
  3975. this.x += otherVector.x;
  3976. this.y += otherVector.y;
  3977. this.z += otherVector.z;
  3978. this.w += otherVector.w;
  3979. return this;
  3980. };
  3981. /**
  3982. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3983. * @param otherVector the vector to add
  3984. * @returns the resulting vector
  3985. */
  3986. Vector4.prototype.add = function (otherVector) {
  3987. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3988. };
  3989. /**
  3990. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3991. * @param otherVector the vector to add
  3992. * @param result the vector to store the result
  3993. * @returns the current Vector4.
  3994. */
  3995. Vector4.prototype.addToRef = function (otherVector, result) {
  3996. result.x = this.x + otherVector.x;
  3997. result.y = this.y + otherVector.y;
  3998. result.z = this.z + otherVector.z;
  3999. result.w = this.w + otherVector.w;
  4000. return this;
  4001. };
  4002. /**
  4003. * Subtract in place the given vector from the current Vector4.
  4004. * @param otherVector the vector to subtract
  4005. * @returns the updated Vector4.
  4006. */
  4007. Vector4.prototype.subtractInPlace = function (otherVector) {
  4008. this.x -= otherVector.x;
  4009. this.y -= otherVector.y;
  4010. this.z -= otherVector.z;
  4011. this.w -= otherVector.w;
  4012. return this;
  4013. };
  4014. /**
  4015. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  4016. * @param otherVector the vector to add
  4017. * @returns the new vector with the result
  4018. */
  4019. Vector4.prototype.subtract = function (otherVector) {
  4020. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  4021. };
  4022. /**
  4023. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  4024. * @param otherVector the vector to subtract
  4025. * @param result the vector to store the result
  4026. * @returns the current Vector4.
  4027. */
  4028. Vector4.prototype.subtractToRef = function (otherVector, result) {
  4029. result.x = this.x - otherVector.x;
  4030. result.y = this.y - otherVector.y;
  4031. result.z = this.z - otherVector.z;
  4032. result.w = this.w - otherVector.w;
  4033. return this;
  4034. };
  4035. /**
  4036. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  4037. */
  4038. /**
  4039. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  4040. * @param x value to subtract
  4041. * @param y value to subtract
  4042. * @param z value to subtract
  4043. * @param w value to subtract
  4044. * @returns new vector containing the result
  4045. */
  4046. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  4047. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  4048. };
  4049. /**
  4050. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  4051. * @param x value to subtract
  4052. * @param y value to subtract
  4053. * @param z value to subtract
  4054. * @param w value to subtract
  4055. * @param result the vector to store the result in
  4056. * @returns the current Vector4.
  4057. */
  4058. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  4059. result.x = this.x - x;
  4060. result.y = this.y - y;
  4061. result.z = this.z - z;
  4062. result.w = this.w - w;
  4063. return this;
  4064. };
  4065. /**
  4066. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  4067. * @returns a new vector with the negated values
  4068. */
  4069. Vector4.prototype.negate = function () {
  4070. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  4071. };
  4072. /**
  4073. * Multiplies the current Vector4 coordinates by scale (float).
  4074. * @param scale the number to scale with
  4075. * @returns the updated Vector4.
  4076. */
  4077. Vector4.prototype.scaleInPlace = function (scale) {
  4078. this.x *= scale;
  4079. this.y *= scale;
  4080. this.z *= scale;
  4081. this.w *= scale;
  4082. return this;
  4083. };
  4084. /**
  4085. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  4086. * @param scale the number to scale with
  4087. * @returns a new vector with the result
  4088. */
  4089. Vector4.prototype.scale = function (scale) {
  4090. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  4091. };
  4092. /**
  4093. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  4094. * @param scale the number to scale with
  4095. * @param result a vector to store the result in
  4096. * @returns the current Vector4.
  4097. */
  4098. Vector4.prototype.scaleToRef = function (scale, result) {
  4099. result.x = this.x * scale;
  4100. result.y = this.y * scale;
  4101. result.z = this.z * scale;
  4102. result.w = this.w * scale;
  4103. return this;
  4104. };
  4105. /**
  4106. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  4107. * @param scale defines the scale factor
  4108. * @param result defines the Vector4 object where to store the result
  4109. * @returns the unmodified current Vector4
  4110. */
  4111. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  4112. result.x += this.x * scale;
  4113. result.y += this.y * scale;
  4114. result.z += this.z * scale;
  4115. result.w += this.w * scale;
  4116. return this;
  4117. };
  4118. /**
  4119. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  4120. * @param otherVector the vector to compare against
  4121. * @returns true if they are equal
  4122. */
  4123. Vector4.prototype.equals = function (otherVector) {
  4124. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  4125. };
  4126. /**
  4127. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  4128. * @param otherVector vector to compare against
  4129. * @param epsilon (Default: very small number)
  4130. * @returns true if they are equal
  4131. */
  4132. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  4133. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  4134. return otherVector
  4135. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  4136. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  4137. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  4138. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  4139. };
  4140. /**
  4141. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  4142. * @param x x value to compare against
  4143. * @param y y value to compare against
  4144. * @param z z value to compare against
  4145. * @param w w value to compare against
  4146. * @returns true if equal
  4147. */
  4148. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  4149. return this.x === x && this.y === y && this.z === z && this.w === w;
  4150. };
  4151. /**
  4152. * Multiplies in place the current Vector4 by the given one.
  4153. * @param otherVector vector to multiple with
  4154. * @returns the updated Vector4.
  4155. */
  4156. Vector4.prototype.multiplyInPlace = function (otherVector) {
  4157. this.x *= otherVector.x;
  4158. this.y *= otherVector.y;
  4159. this.z *= otherVector.z;
  4160. this.w *= otherVector.w;
  4161. return this;
  4162. };
  4163. /**
  4164. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  4165. * @param otherVector vector to multiple with
  4166. * @returns resulting new vector
  4167. */
  4168. Vector4.prototype.multiply = function (otherVector) {
  4169. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  4170. };
  4171. /**
  4172. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  4173. * @param otherVector vector to multiple with
  4174. * @param result vector to store the result
  4175. * @returns the current Vector4.
  4176. */
  4177. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  4178. result.x = this.x * otherVector.x;
  4179. result.y = this.y * otherVector.y;
  4180. result.z = this.z * otherVector.z;
  4181. result.w = this.w * otherVector.w;
  4182. return this;
  4183. };
  4184. /**
  4185. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  4186. * @param x x value multiply with
  4187. * @param y y value multiply with
  4188. * @param z z value multiply with
  4189. * @param w w value multiply with
  4190. * @returns resulting new vector
  4191. */
  4192. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  4193. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  4194. };
  4195. /**
  4196. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  4197. * @param otherVector vector to devide with
  4198. * @returns resulting new vector
  4199. */
  4200. Vector4.prototype.divide = function (otherVector) {
  4201. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  4202. };
  4203. /**
  4204. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  4205. * @param otherVector vector to devide with
  4206. * @param result vector to store the result
  4207. * @returns the current Vector4.
  4208. */
  4209. Vector4.prototype.divideToRef = function (otherVector, result) {
  4210. result.x = this.x / otherVector.x;
  4211. result.y = this.y / otherVector.y;
  4212. result.z = this.z / otherVector.z;
  4213. result.w = this.w / otherVector.w;
  4214. return this;
  4215. };
  4216. /**
  4217. * Divides the current Vector3 coordinates by the given ones.
  4218. * @param otherVector vector to devide with
  4219. * @returns the updated Vector3.
  4220. */
  4221. Vector4.prototype.divideInPlace = function (otherVector) {
  4222. return this.divideToRef(otherVector, this);
  4223. };
  4224. /**
  4225. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  4226. * @param other defines the second operand
  4227. * @returns the current updated Vector4
  4228. */
  4229. Vector4.prototype.minimizeInPlace = function (other) {
  4230. if (other.x < this.x)
  4231. this.x = other.x;
  4232. if (other.y < this.y)
  4233. this.y = other.y;
  4234. if (other.z < this.z)
  4235. this.z = other.z;
  4236. if (other.w < this.w)
  4237. this.w = other.w;
  4238. return this;
  4239. };
  4240. /**
  4241. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4242. * @param other defines the second operand
  4243. * @returns the current updated Vector4
  4244. */
  4245. Vector4.prototype.maximizeInPlace = function (other) {
  4246. if (other.x > this.x)
  4247. this.x = other.x;
  4248. if (other.y > this.y)
  4249. this.y = other.y;
  4250. if (other.z > this.z)
  4251. this.z = other.z;
  4252. if (other.w > this.w)
  4253. this.w = other.w;
  4254. return this;
  4255. };
  4256. /**
  4257. * Gets a new Vector4 from current Vector4 floored values
  4258. * @returns a new Vector4
  4259. */
  4260. Vector4.prototype.floor = function () {
  4261. return new Vector4(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z), Math.floor(this.w));
  4262. };
  4263. /**
  4264. * Gets a new Vector4 from current Vector3 floored values
  4265. * @returns a new Vector4
  4266. */
  4267. Vector4.prototype.fract = function () {
  4268. return new Vector4(this.x - Math.floor(this.x), this.y - Math.floor(this.y), this.z - Math.floor(this.z), this.w - Math.floor(this.w));
  4269. };
  4270. // Properties
  4271. /**
  4272. * Returns the Vector4 length (float).
  4273. * @returns the length
  4274. */
  4275. Vector4.prototype.length = function () {
  4276. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4277. };
  4278. /**
  4279. * Returns the Vector4 squared length (float).
  4280. * @returns the length squared
  4281. */
  4282. Vector4.prototype.lengthSquared = function () {
  4283. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4284. };
  4285. // Methods
  4286. /**
  4287. * Normalizes in place the Vector4.
  4288. * @returns the updated Vector4.
  4289. */
  4290. Vector4.prototype.normalize = function () {
  4291. var len = this.length();
  4292. if (len === 0)
  4293. return this;
  4294. var num = 1.0 / len;
  4295. this.x *= num;
  4296. this.y *= num;
  4297. this.z *= num;
  4298. this.w *= num;
  4299. return this;
  4300. };
  4301. /**
  4302. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4303. * @returns this converted to a new vector3
  4304. */
  4305. Vector4.prototype.toVector3 = function () {
  4306. return new Vector3(this.x, this.y, this.z);
  4307. };
  4308. /**
  4309. * Returns a new Vector4 copied from the current one.
  4310. * @returns the new cloned vector
  4311. */
  4312. Vector4.prototype.clone = function () {
  4313. return new Vector4(this.x, this.y, this.z, this.w);
  4314. };
  4315. /**
  4316. * Updates the current Vector4 with the given one coordinates.
  4317. * @param source the source vector to copy from
  4318. * @returns the updated Vector4.
  4319. */
  4320. Vector4.prototype.copyFrom = function (source) {
  4321. this.x = source.x;
  4322. this.y = source.y;
  4323. this.z = source.z;
  4324. this.w = source.w;
  4325. return this;
  4326. };
  4327. /**
  4328. * Updates the current Vector4 coordinates with the given floats.
  4329. * @param x float to copy from
  4330. * @param y float to copy from
  4331. * @param z float to copy from
  4332. * @param w float to copy from
  4333. * @returns the updated Vector4.
  4334. */
  4335. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4336. this.x = x;
  4337. this.y = y;
  4338. this.z = z;
  4339. this.w = w;
  4340. return this;
  4341. };
  4342. /**
  4343. * Updates the current Vector4 coordinates with the given floats.
  4344. * @param x float to set from
  4345. * @param y float to set from
  4346. * @param z float to set from
  4347. * @param w float to set from
  4348. * @returns the updated Vector4.
  4349. */
  4350. Vector4.prototype.set = function (x, y, z, w) {
  4351. return this.copyFromFloats(x, y, z, w);
  4352. };
  4353. // Statics
  4354. /**
  4355. * Returns a new Vector4 set from the starting index of the given array.
  4356. * @param array the array to pull values from
  4357. * @param offset the offset into the array to start at
  4358. * @returns the new vector
  4359. */
  4360. Vector4.FromArray = function (array, offset) {
  4361. if (!offset) {
  4362. offset = 0;
  4363. }
  4364. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4365. };
  4366. /**
  4367. * Updates the given vector "result" from the starting index of the given array.
  4368. * @param array the array to pull values from
  4369. * @param offset the offset into the array to start at
  4370. * @param result the vector to store the result in
  4371. */
  4372. Vector4.FromArrayToRef = function (array, offset, result) {
  4373. result.x = array[offset];
  4374. result.y = array[offset + 1];
  4375. result.z = array[offset + 2];
  4376. result.w = array[offset + 3];
  4377. };
  4378. /**
  4379. * Updates the given vector "result" from the starting index of the given Float32Array.
  4380. * @param array the array to pull values from
  4381. * @param offset the offset into the array to start at
  4382. * @param result the vector to store the result in
  4383. */
  4384. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4385. Vector4.FromArrayToRef(array, offset, result);
  4386. };
  4387. /**
  4388. * Updates the given vector "result" coordinates from the given floats.
  4389. * @param x float to set from
  4390. * @param y float to set from
  4391. * @param z float to set from
  4392. * @param w float to set from
  4393. * @param result the vector to the floats in
  4394. */
  4395. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4396. result.x = x;
  4397. result.y = y;
  4398. result.z = z;
  4399. result.w = w;
  4400. };
  4401. /**
  4402. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4403. * @returns the new vector
  4404. */
  4405. Vector4.Zero = function () {
  4406. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4407. };
  4408. /**
  4409. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4410. * @returns the new vector
  4411. */
  4412. Vector4.One = function () {
  4413. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4414. };
  4415. /**
  4416. * Returns a new normalized Vector4 from the given one.
  4417. * @param vector the vector to normalize
  4418. * @returns the vector
  4419. */
  4420. Vector4.Normalize = function (vector) {
  4421. var result = Vector4.Zero();
  4422. Vector4.NormalizeToRef(vector, result);
  4423. return result;
  4424. };
  4425. /**
  4426. * Updates the given vector "result" from the normalization of the given one.
  4427. * @param vector the vector to normalize
  4428. * @param result the vector to store the result in
  4429. */
  4430. Vector4.NormalizeToRef = function (vector, result) {
  4431. result.copyFrom(vector);
  4432. result.normalize();
  4433. };
  4434. /**
  4435. * Returns a vector with the minimum values from the left and right vectors
  4436. * @param left left vector to minimize
  4437. * @param right right vector to minimize
  4438. * @returns a new vector with the minimum of the left and right vector values
  4439. */
  4440. Vector4.Minimize = function (left, right) {
  4441. var min = left.clone();
  4442. min.minimizeInPlace(right);
  4443. return min;
  4444. };
  4445. /**
  4446. * Returns a vector with the maximum values from the left and right vectors
  4447. * @param left left vector to maximize
  4448. * @param right right vector to maximize
  4449. * @returns a new vector with the maximum of the left and right vector values
  4450. */
  4451. Vector4.Maximize = function (left, right) {
  4452. var max = left.clone();
  4453. max.maximizeInPlace(right);
  4454. return max;
  4455. };
  4456. /**
  4457. * Returns the distance (float) between the vectors "value1" and "value2".
  4458. * @param value1 value to calulate the distance between
  4459. * @param value2 value to calulate the distance between
  4460. * @return the distance between the two vectors
  4461. */
  4462. Vector4.Distance = function (value1, value2) {
  4463. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4464. };
  4465. /**
  4466. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4467. * @param value1 value to calulate the distance between
  4468. * @param value2 value to calulate the distance between
  4469. * @return the distance between the two vectors squared
  4470. */
  4471. Vector4.DistanceSquared = function (value1, value2) {
  4472. var x = value1.x - value2.x;
  4473. var y = value1.y - value2.y;
  4474. var z = value1.z - value2.z;
  4475. var w = value1.w - value2.w;
  4476. return (x * x) + (y * y) + (z * z) + (w * w);
  4477. };
  4478. /**
  4479. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4480. * @param value1 value to calulate the center between
  4481. * @param value2 value to calulate the center between
  4482. * @return the center between the two vectors
  4483. */
  4484. Vector4.Center = function (value1, value2) {
  4485. var center = value1.add(value2);
  4486. center.scaleInPlace(0.5);
  4487. return center;
  4488. };
  4489. /**
  4490. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4491. * This methods computes transformed normalized direction vectors only.
  4492. * @param vector the vector to transform
  4493. * @param transformation the transformation matrix to apply
  4494. * @returns the new vector
  4495. */
  4496. Vector4.TransformNormal = function (vector, transformation) {
  4497. var result = Vector4.Zero();
  4498. Vector4.TransformNormalToRef(vector, transformation, result);
  4499. return result;
  4500. };
  4501. /**
  4502. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4503. * This methods computes transformed normalized direction vectors only.
  4504. * @param vector the vector to transform
  4505. * @param transformation the transformation matrix to apply
  4506. * @param result the vector to store the result in
  4507. */
  4508. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4509. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4510. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4511. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4512. result.x = x;
  4513. result.y = y;
  4514. result.z = z;
  4515. result.w = vector.w;
  4516. };
  4517. /**
  4518. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4519. * This methods computes transformed normalized direction vectors only.
  4520. * @param x value to transform
  4521. * @param y value to transform
  4522. * @param z value to transform
  4523. * @param w value to transform
  4524. * @param transformation the transformation matrix to apply
  4525. * @param result the vector to store the results in
  4526. */
  4527. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4528. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4529. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4530. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4531. result.w = w;
  4532. };
  4533. return Vector4;
  4534. }());
  4535. BABYLON.Vector4 = Vector4;
  4536. /**
  4537. * Size containing widht and height
  4538. */
  4539. var Size = /** @class */ (function () {
  4540. /**
  4541. * Creates a Size object from the given width and height (floats).
  4542. * @param width width of the new size
  4543. * @param height height of the new size
  4544. */
  4545. function Size(width, height) {
  4546. this.width = width;
  4547. this.height = height;
  4548. }
  4549. /**
  4550. * Returns a string with the Size width and height
  4551. * @returns a string with the Size width and height
  4552. */
  4553. Size.prototype.toString = function () {
  4554. return "{W: " + this.width + ", H: " + this.height + "}";
  4555. };
  4556. /**
  4557. * "Size"
  4558. * @returns the string "Size"
  4559. */
  4560. Size.prototype.getClassName = function () {
  4561. return "Size";
  4562. };
  4563. /**
  4564. * Returns the Size hash code.
  4565. * @returns a hash code for a unique width and height
  4566. */
  4567. Size.prototype.getHashCode = function () {
  4568. var hash = this.width || 0;
  4569. hash = (hash * 397) ^ (this.height || 0);
  4570. return hash;
  4571. };
  4572. /**
  4573. * Updates the current size from the given one.
  4574. * @param src the given size
  4575. */
  4576. Size.prototype.copyFrom = function (src) {
  4577. this.width = src.width;
  4578. this.height = src.height;
  4579. };
  4580. /**
  4581. * Updates in place the current Size from the given floats.
  4582. * @param width width of the new size
  4583. * @param height height of the new size
  4584. * @returns the updated Size.
  4585. */
  4586. Size.prototype.copyFromFloats = function (width, height) {
  4587. this.width = width;
  4588. this.height = height;
  4589. return this;
  4590. };
  4591. /**
  4592. * Updates in place the current Size from the given floats.
  4593. * @param width width to set
  4594. * @param height height to set
  4595. * @returns the updated Size.
  4596. */
  4597. Size.prototype.set = function (width, height) {
  4598. return this.copyFromFloats(width, height);
  4599. };
  4600. /**
  4601. * Multiplies the width and height by numbers
  4602. * @param w factor to multiple the width by
  4603. * @param h factor to multiple the height by
  4604. * @returns a new Size set with the multiplication result of the current Size and the given floats.
  4605. */
  4606. Size.prototype.multiplyByFloats = function (w, h) {
  4607. return new Size(this.width * w, this.height * h);
  4608. };
  4609. /**
  4610. * Clones the size
  4611. * @returns a new Size copied from the given one.
  4612. */
  4613. Size.prototype.clone = function () {
  4614. return new Size(this.width, this.height);
  4615. };
  4616. /**
  4617. * True if the current Size and the given one width and height are strictly equal.
  4618. * @param other the other size to compare against
  4619. * @returns True if the current Size and the given one width and height are strictly equal.
  4620. */
  4621. Size.prototype.equals = function (other) {
  4622. if (!other) {
  4623. return false;
  4624. }
  4625. return (this.width === other.width) && (this.height === other.height);
  4626. };
  4627. Object.defineProperty(Size.prototype, "surface", {
  4628. /**
  4629. * The surface of the Size : width * height (float).
  4630. */
  4631. get: function () {
  4632. return this.width * this.height;
  4633. },
  4634. enumerable: true,
  4635. configurable: true
  4636. });
  4637. /**
  4638. * Create a new size of zero
  4639. * @returns a new Size set to (0.0, 0.0)
  4640. */
  4641. Size.Zero = function () {
  4642. return new Size(0.0, 0.0);
  4643. };
  4644. /**
  4645. * Sums the width and height of two sizes
  4646. * @param otherSize size to add to this size
  4647. * @returns a new Size set as the addition result of the current Size and the given one.
  4648. */
  4649. Size.prototype.add = function (otherSize) {
  4650. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4651. return r;
  4652. };
  4653. /**
  4654. * Subtracts the width and height of two
  4655. * @param otherSize size to subtract to this size
  4656. * @returns a new Size set as the subtraction result of the given one from the current Size.
  4657. */
  4658. Size.prototype.subtract = function (otherSize) {
  4659. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4660. return r;
  4661. };
  4662. /**
  4663. * Creates a new Size set at the linear interpolation "amount" between "start" and "end"
  4664. * @param start starting size to lerp between
  4665. * @param end end size to lerp between
  4666. * @param amount amount to lerp between the start and end values
  4667. * @returns a new Size set at the linear interpolation "amount" between "start" and "end"
  4668. */
  4669. Size.Lerp = function (start, end, amount) {
  4670. var w = start.width + ((end.width - start.width) * amount);
  4671. var h = start.height + ((end.height - start.height) * amount);
  4672. return new Size(w, h);
  4673. };
  4674. return Size;
  4675. }());
  4676. BABYLON.Size = Size;
  4677. /**
  4678. * Class used to store quaternion data
  4679. * @see https://en.wikipedia.org/wiki/Quaternion
  4680. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4681. */
  4682. var Quaternion = /** @class */ (function () {
  4683. /**
  4684. * Creates a new Quaternion from the given floats
  4685. * @param x defines the first component (0 by default)
  4686. * @param y defines the second component (0 by default)
  4687. * @param z defines the third component (0 by default)
  4688. * @param w defines the fourth component (1.0 by default)
  4689. */
  4690. function Quaternion(
  4691. /** defines the first component (0 by default) */
  4692. x,
  4693. /** defines the second component (0 by default) */
  4694. y,
  4695. /** defines the third component (0 by default) */
  4696. z,
  4697. /** defines the fourth component (1.0 by default) */
  4698. w) {
  4699. if (x === void 0) { x = 0.0; }
  4700. if (y === void 0) { y = 0.0; }
  4701. if (z === void 0) { z = 0.0; }
  4702. if (w === void 0) { w = 1.0; }
  4703. this.x = x;
  4704. this.y = y;
  4705. this.z = z;
  4706. this.w = w;
  4707. }
  4708. /**
  4709. * Gets a string representation for the current quaternion
  4710. * @returns a string with the Quaternion coordinates
  4711. */
  4712. Quaternion.prototype.toString = function () {
  4713. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4714. };
  4715. /**
  4716. * Gets the class name of the quaternion
  4717. * @returns the string "Quaternion"
  4718. */
  4719. Quaternion.prototype.getClassName = function () {
  4720. return "Quaternion";
  4721. };
  4722. /**
  4723. * Gets a hash code for this quaternion
  4724. * @returns the quaternion hash code
  4725. */
  4726. Quaternion.prototype.getHashCode = function () {
  4727. var hash = this.x || 0;
  4728. hash = (hash * 397) ^ (this.y || 0);
  4729. hash = (hash * 397) ^ (this.z || 0);
  4730. hash = (hash * 397) ^ (this.w || 0);
  4731. return hash;
  4732. };
  4733. /**
  4734. * Copy the quaternion to an array
  4735. * @returns a new array populated with 4 elements from the quaternion coordinates
  4736. */
  4737. Quaternion.prototype.asArray = function () {
  4738. return [this.x, this.y, this.z, this.w];
  4739. };
  4740. /**
  4741. * Check if two quaternions are equals
  4742. * @param otherQuaternion defines the second operand
  4743. * @return true if the current quaternion and the given one coordinates are strictly equals
  4744. */
  4745. Quaternion.prototype.equals = function (otherQuaternion) {
  4746. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4747. };
  4748. /**
  4749. * Clone the current quaternion
  4750. * @returns a new quaternion copied from the current one
  4751. */
  4752. Quaternion.prototype.clone = function () {
  4753. return new Quaternion(this.x, this.y, this.z, this.w);
  4754. };
  4755. /**
  4756. * Copy a quaternion to the current one
  4757. * @param other defines the other quaternion
  4758. * @returns the updated current quaternion
  4759. */
  4760. Quaternion.prototype.copyFrom = function (other) {
  4761. this.x = other.x;
  4762. this.y = other.y;
  4763. this.z = other.z;
  4764. this.w = other.w;
  4765. return this;
  4766. };
  4767. /**
  4768. * Updates the current quaternion with the given float coordinates
  4769. * @param x defines the x coordinate
  4770. * @param y defines the y coordinate
  4771. * @param z defines the z coordinate
  4772. * @param w defines the w coordinate
  4773. * @returns the updated current quaternion
  4774. */
  4775. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4776. this.x = x;
  4777. this.y = y;
  4778. this.z = z;
  4779. this.w = w;
  4780. return this;
  4781. };
  4782. /**
  4783. * Updates the current quaternion from the given float coordinates
  4784. * @param x defines the x coordinate
  4785. * @param y defines the y coordinate
  4786. * @param z defines the z coordinate
  4787. * @param w defines the w coordinate
  4788. * @returns the updated current quaternion
  4789. */
  4790. Quaternion.prototype.set = function (x, y, z, w) {
  4791. return this.copyFromFloats(x, y, z, w);
  4792. };
  4793. /**
  4794. * Adds two quaternions
  4795. * @param other defines the second operand
  4796. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4797. */
  4798. Quaternion.prototype.add = function (other) {
  4799. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4800. };
  4801. /**
  4802. * Add a quaternion to the current one
  4803. * @param other defines the quaternion to add
  4804. * @returns the current quaternion
  4805. */
  4806. Quaternion.prototype.addInPlace = function (other) {
  4807. this.x += other.x;
  4808. this.y += other.y;
  4809. this.z += other.z;
  4810. this.w += other.w;
  4811. return this;
  4812. };
  4813. /**
  4814. * Subtract two quaternions
  4815. * @param other defines the second operand
  4816. * @returns a new quaternion as the subtraction result of the given one from the current one
  4817. */
  4818. Quaternion.prototype.subtract = function (other) {
  4819. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4820. };
  4821. /**
  4822. * Multiplies the current quaternion by a scale factor
  4823. * @param value defines the scale factor
  4824. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4825. */
  4826. Quaternion.prototype.scale = function (value) {
  4827. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4828. };
  4829. /**
  4830. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4831. * @param scale defines the scale factor
  4832. * @param result defines the Quaternion object where to store the result
  4833. * @returns the unmodified current quaternion
  4834. */
  4835. Quaternion.prototype.scaleToRef = function (scale, result) {
  4836. result.x = this.x * scale;
  4837. result.y = this.y * scale;
  4838. result.z = this.z * scale;
  4839. result.w = this.w * scale;
  4840. return this;
  4841. };
  4842. /**
  4843. * Multiplies in place the current quaternion by a scale factor
  4844. * @param value defines the scale factor
  4845. * @returns the current modified quaternion
  4846. */
  4847. Quaternion.prototype.scaleInPlace = function (value) {
  4848. this.x *= value;
  4849. this.y *= value;
  4850. this.z *= value;
  4851. this.w *= value;
  4852. return this;
  4853. };
  4854. /**
  4855. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4856. * @param scale defines the scale factor
  4857. * @param result defines the Quaternion object where to store the result
  4858. * @returns the unmodified current quaternion
  4859. */
  4860. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4861. result.x += this.x * scale;
  4862. result.y += this.y * scale;
  4863. result.z += this.z * scale;
  4864. result.w += this.w * scale;
  4865. return this;
  4866. };
  4867. /**
  4868. * Multiplies two quaternions
  4869. * @param q1 defines the second operand
  4870. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4871. */
  4872. Quaternion.prototype.multiply = function (q1) {
  4873. var result = new Quaternion(0, 0, 0, 1.0);
  4874. this.multiplyToRef(q1, result);
  4875. return result;
  4876. };
  4877. /**
  4878. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4879. * @param q1 defines the second operand
  4880. * @param result defines the target quaternion
  4881. * @returns the current quaternion
  4882. */
  4883. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4884. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4885. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4886. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4887. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4888. result.copyFromFloats(x, y, z, w);
  4889. return this;
  4890. };
  4891. /**
  4892. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4893. * @param q1 defines the second operand
  4894. * @returns the currentupdated quaternion
  4895. */
  4896. Quaternion.prototype.multiplyInPlace = function (q1) {
  4897. this.multiplyToRef(q1, this);
  4898. return this;
  4899. };
  4900. /**
  4901. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4902. * @param ref defines the target quaternion
  4903. * @returns the current quaternion
  4904. */
  4905. Quaternion.prototype.conjugateToRef = function (ref) {
  4906. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4907. return this;
  4908. };
  4909. /**
  4910. * Conjugates in place (1-q) the current quaternion
  4911. * @returns the current updated quaternion
  4912. */
  4913. Quaternion.prototype.conjugateInPlace = function () {
  4914. this.x *= -1;
  4915. this.y *= -1;
  4916. this.z *= -1;
  4917. return this;
  4918. };
  4919. /**
  4920. * Conjugates in place (1-q) the current quaternion
  4921. * @returns a new quaternion
  4922. */
  4923. Quaternion.prototype.conjugate = function () {
  4924. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4925. return result;
  4926. };
  4927. /**
  4928. * Gets length of current quaternion
  4929. * @returns the quaternion length (float)
  4930. */
  4931. Quaternion.prototype.length = function () {
  4932. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4933. };
  4934. /**
  4935. * Normalize in place the current quaternion
  4936. * @returns the current updated quaternion
  4937. */
  4938. Quaternion.prototype.normalize = function () {
  4939. var length = 1.0 / this.length();
  4940. this.x *= length;
  4941. this.y *= length;
  4942. this.z *= length;
  4943. this.w *= length;
  4944. return this;
  4945. };
  4946. /**
  4947. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4948. * @param order is a reserved parameter and is ignore for now
  4949. * @returns a new Vector3 containing the Euler angles
  4950. */
  4951. Quaternion.prototype.toEulerAngles = function (order) {
  4952. if (order === void 0) { order = "YZX"; }
  4953. var result = Vector3.Zero();
  4954. this.toEulerAnglesToRef(result, order);
  4955. return result;
  4956. };
  4957. /**
  4958. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4959. * @param result defines the vector which will be filled with the Euler angles
  4960. * @param order is a reserved parameter and is ignore for now
  4961. * @returns the current unchanged quaternion
  4962. */
  4963. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4964. if (order === void 0) { order = "YZX"; }
  4965. var qz = this.z;
  4966. var qx = this.x;
  4967. var qy = this.y;
  4968. var qw = this.w;
  4969. var sqw = qw * qw;
  4970. var sqz = qz * qz;
  4971. var sqx = qx * qx;
  4972. var sqy = qy * qy;
  4973. var zAxisY = qy * qz - qx * qw;
  4974. var limit = .4999999;
  4975. if (zAxisY < -limit) {
  4976. result.y = 2 * Math.atan2(qy, qw);
  4977. result.x = Math.PI / 2;
  4978. result.z = 0;
  4979. }
  4980. else if (zAxisY > limit) {
  4981. result.y = 2 * Math.atan2(qy, qw);
  4982. result.x = -Math.PI / 2;
  4983. result.z = 0;
  4984. }
  4985. else {
  4986. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4987. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4988. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4989. }
  4990. return this;
  4991. };
  4992. /**
  4993. * Updates the given rotation matrix with the current quaternion values
  4994. * @param result defines the target matrix
  4995. * @returns the current unchanged quaternion
  4996. */
  4997. Quaternion.prototype.toRotationMatrix = function (result) {
  4998. var xx = this.x * this.x;
  4999. var yy = this.y * this.y;
  5000. var zz = this.z * this.z;
  5001. var xy = this.x * this.y;
  5002. var zw = this.z * this.w;
  5003. var zx = this.z * this.x;
  5004. var yw = this.y * this.w;
  5005. var yz = this.y * this.z;
  5006. var xw = this.x * this.w;
  5007. result.m[0] = 1.0 - (2.0 * (yy + zz));
  5008. result.m[1] = 2.0 * (xy + zw);
  5009. result.m[2] = 2.0 * (zx - yw);
  5010. result.m[3] = 0;
  5011. result.m[4] = 2.0 * (xy - zw);
  5012. result.m[5] = 1.0 - (2.0 * (zz + xx));
  5013. result.m[6] = 2.0 * (yz + xw);
  5014. result.m[7] = 0;
  5015. result.m[8] = 2.0 * (zx + yw);
  5016. result.m[9] = 2.0 * (yz - xw);
  5017. result.m[10] = 1.0 - (2.0 * (yy + xx));
  5018. result.m[11] = 0;
  5019. result.m[12] = 0;
  5020. result.m[13] = 0;
  5021. result.m[14] = 0;
  5022. result.m[15] = 1.0;
  5023. result._markAsUpdated();
  5024. return this;
  5025. };
  5026. /**
  5027. * Updates the current quaternion from the given rotation matrix values
  5028. * @param matrix defines the source matrix
  5029. * @returns the current updated quaternion
  5030. */
  5031. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  5032. Quaternion.FromRotationMatrixToRef(matrix, this);
  5033. return this;
  5034. };
  5035. // Statics
  5036. /**
  5037. * Creates a new quaternion from a rotation matrix
  5038. * @param matrix defines the source matrix
  5039. * @returns a new quaternion created from the given rotation matrix values
  5040. */
  5041. Quaternion.FromRotationMatrix = function (matrix) {
  5042. var result = new Quaternion();
  5043. Quaternion.FromRotationMatrixToRef(matrix, result);
  5044. return result;
  5045. };
  5046. /**
  5047. * Updates the given quaternion with the given rotation matrix values
  5048. * @param matrix defines the source matrix
  5049. * @param result defines the target quaternion
  5050. */
  5051. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  5052. var data = matrix.m;
  5053. var m11 = data[0], m12 = data[4], m13 = data[8];
  5054. var m21 = data[1], m22 = data[5], m23 = data[9];
  5055. var m31 = data[2], m32 = data[6], m33 = data[10];
  5056. var trace = m11 + m22 + m33;
  5057. var s;
  5058. if (trace > 0) {
  5059. s = 0.5 / Math.sqrt(trace + 1.0);
  5060. result.w = 0.25 / s;
  5061. result.x = (m32 - m23) * s;
  5062. result.y = (m13 - m31) * s;
  5063. result.z = (m21 - m12) * s;
  5064. }
  5065. else if (m11 > m22 && m11 > m33) {
  5066. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  5067. result.w = (m32 - m23) / s;
  5068. result.x = 0.25 * s;
  5069. result.y = (m12 + m21) / s;
  5070. result.z = (m13 + m31) / s;
  5071. }
  5072. else if (m22 > m33) {
  5073. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  5074. result.w = (m13 - m31) / s;
  5075. result.x = (m12 + m21) / s;
  5076. result.y = 0.25 * s;
  5077. result.z = (m23 + m32) / s;
  5078. }
  5079. else {
  5080. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  5081. result.w = (m21 - m12) / s;
  5082. result.x = (m13 + m31) / s;
  5083. result.y = (m23 + m32) / s;
  5084. result.z = 0.25 * s;
  5085. }
  5086. };
  5087. /**
  5088. * Returns the dot product (float) between the quaternions "left" and "right"
  5089. * @param left defines the left operand
  5090. * @param right defines the right operand
  5091. * @returns the dot product
  5092. */
  5093. Quaternion.Dot = function (left, right) {
  5094. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  5095. };
  5096. /**
  5097. * Checks if the two quaternions are close to each other
  5098. * @param quat0 defines the first quaternion to check
  5099. * @param quat1 defines the second quaternion to check
  5100. * @returns true if the two quaternions are close to each other
  5101. */
  5102. Quaternion.AreClose = function (quat0, quat1) {
  5103. var dot = Quaternion.Dot(quat0, quat1);
  5104. return dot >= 0;
  5105. };
  5106. /**
  5107. * Creates an empty quaternion
  5108. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  5109. */
  5110. Quaternion.Zero = function () {
  5111. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  5112. };
  5113. /**
  5114. * Inverse a given quaternion
  5115. * @param q defines the source quaternion
  5116. * @returns a new quaternion as the inverted current quaternion
  5117. */
  5118. Quaternion.Inverse = function (q) {
  5119. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  5120. };
  5121. /**
  5122. * Creates an identity quaternion
  5123. * @returns the identity quaternion
  5124. */
  5125. Quaternion.Identity = function () {
  5126. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  5127. };
  5128. /**
  5129. * Gets a boolean indicating if the given quaternion is identity
  5130. * @param quaternion defines the quaternion to check
  5131. * @returns true if the quaternion is identity
  5132. */
  5133. Quaternion.IsIdentity = function (quaternion) {
  5134. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  5135. };
  5136. /**
  5137. * Creates a quaternion from a rotation around an axis
  5138. * @param axis defines the axis to use
  5139. * @param angle defines the angle to use
  5140. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  5141. */
  5142. Quaternion.RotationAxis = function (axis, angle) {
  5143. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  5144. };
  5145. /**
  5146. * Creates a rotation around an axis and stores it into the given quaternion
  5147. * @param axis defines the axis to use
  5148. * @param angle defines the angle to use
  5149. * @param result defines the target quaternion
  5150. * @returns the target quaternion
  5151. */
  5152. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  5153. var sin = Math.sin(angle / 2);
  5154. axis.normalize();
  5155. result.w = Math.cos(angle / 2);
  5156. result.x = axis.x * sin;
  5157. result.y = axis.y * sin;
  5158. result.z = axis.z * sin;
  5159. return result;
  5160. };
  5161. /**
  5162. * Creates a new quaternion from data stored into an array
  5163. * @param array defines the data source
  5164. * @param offset defines the offset in the source array where the data starts
  5165. * @returns a new quaternion
  5166. */
  5167. Quaternion.FromArray = function (array, offset) {
  5168. if (!offset) {
  5169. offset = 0;
  5170. }
  5171. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  5172. };
  5173. /**
  5174. * Creates a new quaternion from the given Euler float angles (y, x, z)
  5175. * @param yaw defines the rotation around Y axis
  5176. * @param pitch defines the rotation around X axis
  5177. * @param roll defines the rotation around Z axis
  5178. * @returns the new quaternion
  5179. */
  5180. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5181. var q = new Quaternion();
  5182. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  5183. return q;
  5184. };
  5185. /**
  5186. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  5187. * @param yaw defines the rotation around Y axis
  5188. * @param pitch defines the rotation around X axis
  5189. * @param roll defines the rotation around Z axis
  5190. * @param result defines the target quaternion
  5191. */
  5192. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5193. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  5194. var halfRoll = roll * 0.5;
  5195. var halfPitch = pitch * 0.5;
  5196. var halfYaw = yaw * 0.5;
  5197. var sinRoll = Math.sin(halfRoll);
  5198. var cosRoll = Math.cos(halfRoll);
  5199. var sinPitch = Math.sin(halfPitch);
  5200. var cosPitch = Math.cos(halfPitch);
  5201. var sinYaw = Math.sin(halfYaw);
  5202. var cosYaw = Math.cos(halfYaw);
  5203. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  5204. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  5205. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  5206. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  5207. };
  5208. /**
  5209. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  5210. * @param alpha defines the rotation around first axis
  5211. * @param beta defines the rotation around second axis
  5212. * @param gamma defines the rotation around third axis
  5213. * @returns the new quaternion
  5214. */
  5215. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  5216. var result = new Quaternion();
  5217. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  5218. return result;
  5219. };
  5220. /**
  5221. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  5222. * @param alpha defines the rotation around first axis
  5223. * @param beta defines the rotation around second axis
  5224. * @param gamma defines the rotation around third axis
  5225. * @param result defines the target quaternion
  5226. */
  5227. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  5228. // Produces a quaternion from Euler angles in the z-x-z orientation
  5229. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  5230. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  5231. var halfBeta = beta * 0.5;
  5232. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  5233. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  5234. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  5235. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  5236. };
  5237. /**
  5238. * 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)
  5239. * @param axis1 defines the first axis
  5240. * @param axis2 defines the second axis
  5241. * @param axis3 defines the third axis
  5242. * @returns the new quaternion
  5243. */
  5244. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  5245. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  5246. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  5247. return quat;
  5248. };
  5249. /**
  5250. * 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
  5251. * @param axis1 defines the first axis
  5252. * @param axis2 defines the second axis
  5253. * @param axis3 defines the third axis
  5254. * @param ref defines the target quaternion
  5255. */
  5256. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  5257. var rotMat = MathTmp.Matrix[0];
  5258. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  5259. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  5260. };
  5261. /**
  5262. * Interpolates between two quaternions
  5263. * @param left defines first quaternion
  5264. * @param right defines second quaternion
  5265. * @param amount defines the gradient to use
  5266. * @returns the new interpolated quaternion
  5267. */
  5268. Quaternion.Slerp = function (left, right, amount) {
  5269. var result = Quaternion.Identity();
  5270. Quaternion.SlerpToRef(left, right, amount, result);
  5271. return result;
  5272. };
  5273. /**
  5274. * Interpolates between two quaternions and stores it into a target quaternion
  5275. * @param left defines first quaternion
  5276. * @param right defines second quaternion
  5277. * @param amount defines the gradient to use
  5278. * @param result defines the target quaternion
  5279. */
  5280. Quaternion.SlerpToRef = function (left, right, amount, result) {
  5281. var num2;
  5282. var num3;
  5283. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  5284. var flag = false;
  5285. if (num4 < 0) {
  5286. flag = true;
  5287. num4 = -num4;
  5288. }
  5289. if (num4 > 0.999999) {
  5290. num3 = 1 - amount;
  5291. num2 = flag ? -amount : amount;
  5292. }
  5293. else {
  5294. var num5 = Math.acos(num4);
  5295. var num6 = (1.0 / Math.sin(num5));
  5296. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  5297. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  5298. }
  5299. result.x = (num3 * left.x) + (num2 * right.x);
  5300. result.y = (num3 * left.y) + (num2 * right.y);
  5301. result.z = (num3 * left.z) + (num2 * right.z);
  5302. result.w = (num3 * left.w) + (num2 * right.w);
  5303. };
  5304. /**
  5305. * Interpolate between two quaternions using Hermite interpolation
  5306. * @param value1 defines first quaternion
  5307. * @param tangent1 defines the incoming tangent
  5308. * @param value2 defines second quaternion
  5309. * @param tangent2 defines the outgoing tangent
  5310. * @param amount defines the target quaternion
  5311. * @returns the new interpolated quaternion
  5312. */
  5313. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5314. var squared = amount * amount;
  5315. var cubed = amount * squared;
  5316. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5317. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5318. var part3 = (cubed - (2.0 * squared)) + amount;
  5319. var part4 = cubed - squared;
  5320. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  5321. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  5322. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  5323. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  5324. return new Quaternion(x, y, z, w);
  5325. };
  5326. return Quaternion;
  5327. }());
  5328. BABYLON.Quaternion = Quaternion;
  5329. /**
  5330. * Class used to store matrix data (4x4)
  5331. */
  5332. var Matrix = /** @class */ (function () {
  5333. /**
  5334. * Creates an empty matrix (filled with zeros)
  5335. */
  5336. function Matrix() {
  5337. this._isIdentity = false;
  5338. this._isIdentityDirty = true;
  5339. /**
  5340. * Gets or sets the internal data of the matrix
  5341. */
  5342. this.m = new Float32Array(16);
  5343. this._markAsUpdated();
  5344. }
  5345. /** @hidden */
  5346. Matrix.prototype._markAsUpdated = function () {
  5347. this.updateFlag = Matrix._updateFlagSeed++;
  5348. this._isIdentityDirty = true;
  5349. };
  5350. // Properties
  5351. /**
  5352. * Check if the current matrix is indentity
  5353. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5354. * @returns true is the matrix is the identity matrix
  5355. */
  5356. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5357. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5358. if (this._isIdentityDirty) {
  5359. this._isIdentityDirty = false;
  5360. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5361. this._isIdentity = false;
  5362. }
  5363. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5364. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5365. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5366. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5367. this._isIdentity = false;
  5368. }
  5369. else {
  5370. this._isIdentity = true;
  5371. }
  5372. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5373. this._isIdentity = false;
  5374. }
  5375. }
  5376. return this._isIdentity;
  5377. };
  5378. /**
  5379. * Gets the determinant of the matrix
  5380. * @returns the matrix determinant
  5381. */
  5382. Matrix.prototype.determinant = function () {
  5383. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5384. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5385. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5386. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5387. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5388. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5389. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5390. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5391. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5392. };
  5393. // Methods
  5394. /**
  5395. * Returns the matrix as a Float32Array
  5396. * @returns the matrix underlying array
  5397. */
  5398. Matrix.prototype.toArray = function () {
  5399. return this.m;
  5400. };
  5401. /**
  5402. * Returns the matrix as a Float32Array
  5403. * @returns the matrix underlying array.
  5404. */
  5405. Matrix.prototype.asArray = function () {
  5406. return this.toArray();
  5407. };
  5408. /**
  5409. * Inverts the current matrix in place
  5410. * @returns the current inverted matrix
  5411. */
  5412. Matrix.prototype.invert = function () {
  5413. this.invertToRef(this);
  5414. return this;
  5415. };
  5416. /**
  5417. * Sets all the matrix elements to zero
  5418. * @returns the current matrix
  5419. */
  5420. Matrix.prototype.reset = function () {
  5421. for (var index = 0; index < 16; index++) {
  5422. this.m[index] = 0.0;
  5423. }
  5424. this._markAsUpdated();
  5425. return this;
  5426. };
  5427. /**
  5428. * Adds the current matrix with a second one
  5429. * @param other defines the matrix to add
  5430. * @returns a new matrix as the addition of the current matrix and the given one
  5431. */
  5432. Matrix.prototype.add = function (other) {
  5433. var result = new Matrix();
  5434. this.addToRef(other, result);
  5435. return result;
  5436. };
  5437. /**
  5438. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5439. * @param other defines the matrix to add
  5440. * @param result defines the target matrix
  5441. * @returns the current matrix
  5442. */
  5443. Matrix.prototype.addToRef = function (other, result) {
  5444. for (var index = 0; index < 16; index++) {
  5445. result.m[index] = this.m[index] + other.m[index];
  5446. }
  5447. result._markAsUpdated();
  5448. return this;
  5449. };
  5450. /**
  5451. * Adds in place the given matrix to the current matrix
  5452. * @param other defines the second operand
  5453. * @returns the current updated matrix
  5454. */
  5455. Matrix.prototype.addToSelf = function (other) {
  5456. for (var index = 0; index < 16; index++) {
  5457. this.m[index] += other.m[index];
  5458. }
  5459. this._markAsUpdated();
  5460. return this;
  5461. };
  5462. /**
  5463. * Sets the given matrix to the current inverted Matrix
  5464. * @param other defines the target matrix
  5465. * @returns the unmodified current matrix
  5466. */
  5467. Matrix.prototype.invertToRef = function (other) {
  5468. var l1 = this.m[0];
  5469. var l2 = this.m[1];
  5470. var l3 = this.m[2];
  5471. var l4 = this.m[3];
  5472. var l5 = this.m[4];
  5473. var l6 = this.m[5];
  5474. var l7 = this.m[6];
  5475. var l8 = this.m[7];
  5476. var l9 = this.m[8];
  5477. var l10 = this.m[9];
  5478. var l11 = this.m[10];
  5479. var l12 = this.m[11];
  5480. var l13 = this.m[12];
  5481. var l14 = this.m[13];
  5482. var l15 = this.m[14];
  5483. var l16 = this.m[15];
  5484. var l17 = (l11 * l16) - (l12 * l15);
  5485. var l18 = (l10 * l16) - (l12 * l14);
  5486. var l19 = (l10 * l15) - (l11 * l14);
  5487. var l20 = (l9 * l16) - (l12 * l13);
  5488. var l21 = (l9 * l15) - (l11 * l13);
  5489. var l22 = (l9 * l14) - (l10 * l13);
  5490. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5491. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5492. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5493. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5494. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5495. var l28 = (l7 * l16) - (l8 * l15);
  5496. var l29 = (l6 * l16) - (l8 * l14);
  5497. var l30 = (l6 * l15) - (l7 * l14);
  5498. var l31 = (l5 * l16) - (l8 * l13);
  5499. var l32 = (l5 * l15) - (l7 * l13);
  5500. var l33 = (l5 * l14) - (l6 * l13);
  5501. var l34 = (l7 * l12) - (l8 * l11);
  5502. var l35 = (l6 * l12) - (l8 * l10);
  5503. var l36 = (l6 * l11) - (l7 * l10);
  5504. var l37 = (l5 * l12) - (l8 * l9);
  5505. var l38 = (l5 * l11) - (l7 * l9);
  5506. var l39 = (l5 * l10) - (l6 * l9);
  5507. other.m[0] = l23 * l27;
  5508. other.m[4] = l24 * l27;
  5509. other.m[8] = l25 * l27;
  5510. other.m[12] = l26 * l27;
  5511. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5512. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5513. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5514. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5515. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5516. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5517. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5518. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5519. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5520. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5521. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5522. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5523. other._markAsUpdated();
  5524. return this;
  5525. };
  5526. /**
  5527. * Inserts the translation vector (using 3 floats) in the current matrix
  5528. * @param x defines the 1st component of the translation
  5529. * @param y defines the 2nd component of the translation
  5530. * @param z defines the 3rd component of the translation
  5531. * @returns the current updated matrix
  5532. */
  5533. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5534. this.m[12] = x;
  5535. this.m[13] = y;
  5536. this.m[14] = z;
  5537. this._markAsUpdated();
  5538. return this;
  5539. };
  5540. /**
  5541. * Inserts the translation vector in the current matrix
  5542. * @param vector3 defines the translation to insert
  5543. * @returns the current updated matrix
  5544. */
  5545. Matrix.prototype.setTranslation = function (vector3) {
  5546. this.m[12] = vector3.x;
  5547. this.m[13] = vector3.y;
  5548. this.m[14] = vector3.z;
  5549. this._markAsUpdated();
  5550. return this;
  5551. };
  5552. /**
  5553. * Gets the translation value of the current matrix
  5554. * @returns a new Vector3 as the extracted translation from the matrix
  5555. */
  5556. Matrix.prototype.getTranslation = function () {
  5557. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5558. };
  5559. /**
  5560. * Fill a Vector3 with the extracted translation from the matrix
  5561. * @param result defines the Vector3 where to store the translation
  5562. * @returns the current matrix
  5563. */
  5564. Matrix.prototype.getTranslationToRef = function (result) {
  5565. result.x = this.m[12];
  5566. result.y = this.m[13];
  5567. result.z = this.m[14];
  5568. return this;
  5569. };
  5570. /**
  5571. * Remove rotation and scaling part from the matrix
  5572. * @returns the updated matrix
  5573. */
  5574. Matrix.prototype.removeRotationAndScaling = function () {
  5575. this.setRowFromFloats(0, 1, 0, 0, 0);
  5576. this.setRowFromFloats(1, 0, 1, 0, 0);
  5577. this.setRowFromFloats(2, 0, 0, 1, 0);
  5578. return this;
  5579. };
  5580. /**
  5581. * Multiply two matrices
  5582. * @param other defines the second operand
  5583. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5584. */
  5585. Matrix.prototype.multiply = function (other) {
  5586. var result = new Matrix();
  5587. this.multiplyToRef(other, result);
  5588. return result;
  5589. };
  5590. /**
  5591. * Copy the current matrix from the given one
  5592. * @param other defines the source matrix
  5593. * @returns the current updated matrix
  5594. */
  5595. Matrix.prototype.copyFrom = function (other) {
  5596. for (var index = 0; index < 16; index++) {
  5597. this.m[index] = other.m[index];
  5598. }
  5599. this._markAsUpdated();
  5600. return this;
  5601. };
  5602. /**
  5603. * Populates the given array from the starting index with the current matrix values
  5604. * @param array defines the target array
  5605. * @param offset defines the offset in the target array where to start storing values
  5606. * @returns the current matrix
  5607. */
  5608. Matrix.prototype.copyToArray = function (array, offset) {
  5609. if (offset === void 0) { offset = 0; }
  5610. for (var index = 0; index < 16; index++) {
  5611. array[offset + index] = this.m[index];
  5612. }
  5613. return this;
  5614. };
  5615. /**
  5616. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5617. * @param other defines the second operand
  5618. * @param result defines the matrix where to store the multiplication
  5619. * @returns the current matrix
  5620. */
  5621. Matrix.prototype.multiplyToRef = function (other, result) {
  5622. this.multiplyToArray(other, result.m, 0);
  5623. result._markAsUpdated();
  5624. return this;
  5625. };
  5626. /**
  5627. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5628. * @param other defines the second operand
  5629. * @param result defines the array where to store the multiplication
  5630. * @param offset defines the offset in the target array where to start storing values
  5631. * @returns the current matrix
  5632. */
  5633. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5634. var tm0 = this.m[0];
  5635. var tm1 = this.m[1];
  5636. var tm2 = this.m[2];
  5637. var tm3 = this.m[3];
  5638. var tm4 = this.m[4];
  5639. var tm5 = this.m[5];
  5640. var tm6 = this.m[6];
  5641. var tm7 = this.m[7];
  5642. var tm8 = this.m[8];
  5643. var tm9 = this.m[9];
  5644. var tm10 = this.m[10];
  5645. var tm11 = this.m[11];
  5646. var tm12 = this.m[12];
  5647. var tm13 = this.m[13];
  5648. var tm14 = this.m[14];
  5649. var tm15 = this.m[15];
  5650. var om0 = other.m[0];
  5651. var om1 = other.m[1];
  5652. var om2 = other.m[2];
  5653. var om3 = other.m[3];
  5654. var om4 = other.m[4];
  5655. var om5 = other.m[5];
  5656. var om6 = other.m[6];
  5657. var om7 = other.m[7];
  5658. var om8 = other.m[8];
  5659. var om9 = other.m[9];
  5660. var om10 = other.m[10];
  5661. var om11 = other.m[11];
  5662. var om12 = other.m[12];
  5663. var om13 = other.m[13];
  5664. var om14 = other.m[14];
  5665. var om15 = other.m[15];
  5666. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5667. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5668. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5669. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5670. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5671. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5672. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5673. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5674. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5675. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5676. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5677. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5678. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5679. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5680. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5681. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5682. return this;
  5683. };
  5684. /**
  5685. * Check equality between this matrix and a second one
  5686. * @param value defines the second matrix to compare
  5687. * @returns true is the current matrix and the given one values are strictly equal
  5688. */
  5689. Matrix.prototype.equals = function (value) {
  5690. return value &&
  5691. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5692. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5693. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5694. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5695. };
  5696. /**
  5697. * Clone the current matrix
  5698. * @returns a new matrix from the current matrix
  5699. */
  5700. Matrix.prototype.clone = function () {
  5701. 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]);
  5702. };
  5703. /**
  5704. * Returns the name of the current matrix class
  5705. * @returns the string "Matrix"
  5706. */
  5707. Matrix.prototype.getClassName = function () {
  5708. return "Matrix";
  5709. };
  5710. /**
  5711. * Gets the hash code of the current matrix
  5712. * @returns the hash code
  5713. */
  5714. Matrix.prototype.getHashCode = function () {
  5715. var hash = this.m[0] || 0;
  5716. for (var i = 1; i < 16; i++) {
  5717. hash = (hash * 397) ^ (this.m[i] || 0);
  5718. }
  5719. return hash;
  5720. };
  5721. /**
  5722. * Decomposes the current Matrix into a translation, rotation and scaling components
  5723. * @param scale defines the scale vector3 given as a reference to update
  5724. * @param rotation defines the rotation quaternion given as a reference to update
  5725. * @param translation defines the translation vector3 given as a reference to update
  5726. * @returns true if operation was successful
  5727. */
  5728. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5729. if (translation) {
  5730. translation.x = this.m[12];
  5731. translation.y = this.m[13];
  5732. translation.z = this.m[14];
  5733. }
  5734. scale = scale || MathTmp.Vector3[0];
  5735. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5736. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5737. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5738. if (this.determinant() <= 0) {
  5739. scale.y *= -1;
  5740. }
  5741. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5742. if (rotation) {
  5743. rotation.x = 0;
  5744. rotation.y = 0;
  5745. rotation.z = 0;
  5746. rotation.w = 1;
  5747. }
  5748. return false;
  5749. }
  5750. if (rotation) {
  5751. 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]);
  5752. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5753. }
  5754. return true;
  5755. };
  5756. /**
  5757. * Gets specific row of the matrix
  5758. * @param index defines the number of the row to get
  5759. * @returns the index-th row of the current matrix as a new Vector4
  5760. */
  5761. Matrix.prototype.getRow = function (index) {
  5762. if (index < 0 || index > 3) {
  5763. return null;
  5764. }
  5765. var i = index * 4;
  5766. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5767. };
  5768. /**
  5769. * Sets the index-th row of the current matrix to the vector4 values
  5770. * @param index defines the number of the row to set
  5771. * @param row defines the target vector4
  5772. * @returns the updated current matrix
  5773. */
  5774. Matrix.prototype.setRow = function (index, row) {
  5775. if (index < 0 || index > 3) {
  5776. return this;
  5777. }
  5778. var i = index * 4;
  5779. this.m[i + 0] = row.x;
  5780. this.m[i + 1] = row.y;
  5781. this.m[i + 2] = row.z;
  5782. this.m[i + 3] = row.w;
  5783. this._markAsUpdated();
  5784. return this;
  5785. };
  5786. /**
  5787. * Compute the transpose of the matrix
  5788. * @returns the new transposed matrix
  5789. */
  5790. Matrix.prototype.transpose = function () {
  5791. return Matrix.Transpose(this);
  5792. };
  5793. /**
  5794. * Compute the transpose of the matrix and store it in a given matrix
  5795. * @param result defines the target matrix
  5796. * @returns the current matrix
  5797. */
  5798. Matrix.prototype.transposeToRef = function (result) {
  5799. Matrix.TransposeToRef(this, result);
  5800. return this;
  5801. };
  5802. /**
  5803. * Sets the index-th row of the current matrix with the given 4 x float values
  5804. * @param index defines the row index
  5805. * @param x defines the x component to set
  5806. * @param y defines the y component to set
  5807. * @param z defines the z component to set
  5808. * @param w defines the w component to set
  5809. * @returns the updated current matrix
  5810. */
  5811. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5812. if (index < 0 || index > 3) {
  5813. return this;
  5814. }
  5815. var i = index * 4;
  5816. this.m[i + 0] = x;
  5817. this.m[i + 1] = y;
  5818. this.m[i + 2] = z;
  5819. this.m[i + 3] = w;
  5820. this._markAsUpdated();
  5821. return this;
  5822. };
  5823. /**
  5824. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5825. * @param scale defines the scale factor
  5826. * @returns a new matrix
  5827. */
  5828. Matrix.prototype.scale = function (scale) {
  5829. var result = new Matrix();
  5830. this.scaleToRef(scale, result);
  5831. return result;
  5832. };
  5833. /**
  5834. * Scale the current matrix values by a factor to a given result matrix
  5835. * @param scale defines the scale factor
  5836. * @param result defines the matrix to store the result
  5837. * @returns the current matrix
  5838. */
  5839. Matrix.prototype.scaleToRef = function (scale, result) {
  5840. for (var index = 0; index < 16; index++) {
  5841. result.m[index] = this.m[index] * scale;
  5842. }
  5843. result._markAsUpdated();
  5844. return this;
  5845. };
  5846. /**
  5847. * Scale the current matrix values by a factor and add the result to a given matrix
  5848. * @param scale defines the scale factor
  5849. * @param result defines the Matrix to store the result
  5850. * @returns the current matrix
  5851. */
  5852. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5853. for (var index = 0; index < 16; index++) {
  5854. result.m[index] += this.m[index] * scale;
  5855. }
  5856. result._markAsUpdated();
  5857. return this;
  5858. };
  5859. /**
  5860. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5861. * @param ref matrix to store the result
  5862. */
  5863. Matrix.prototype.toNormalMatrix = function (ref) {
  5864. this.invertToRef(ref);
  5865. ref.transpose();
  5866. var m = ref.m;
  5867. 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);
  5868. };
  5869. /**
  5870. * Gets only rotation part of the current matrix
  5871. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5872. */
  5873. Matrix.prototype.getRotationMatrix = function () {
  5874. var result = Matrix.Identity();
  5875. this.getRotationMatrixToRef(result);
  5876. return result;
  5877. };
  5878. /**
  5879. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5880. * @param result defines the target matrix to store data to
  5881. * @returns the current matrix
  5882. */
  5883. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5884. var m = this.m;
  5885. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5886. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5887. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5888. if (this.determinant() <= 0) {
  5889. sy *= -1;
  5890. }
  5891. if (sx === 0 || sy === 0 || sz === 0) {
  5892. Matrix.IdentityToRef(result);
  5893. }
  5894. else {
  5895. 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);
  5896. }
  5897. return this;
  5898. };
  5899. // Statics
  5900. /**
  5901. * Creates a matrix from an array
  5902. * @param array defines the source array
  5903. * @param offset defines an offset in the source array
  5904. * @returns a new Matrix set from the starting index of the given array
  5905. */
  5906. Matrix.FromArray = function (array, offset) {
  5907. var result = new Matrix();
  5908. if (!offset) {
  5909. offset = 0;
  5910. }
  5911. Matrix.FromArrayToRef(array, offset, result);
  5912. return result;
  5913. };
  5914. /**
  5915. * Copy the content of an array into a given matrix
  5916. * @param array defines the source array
  5917. * @param offset defines an offset in the source array
  5918. * @param result defines the target matrix
  5919. */
  5920. Matrix.FromArrayToRef = function (array, offset, result) {
  5921. for (var index = 0; index < 16; index++) {
  5922. result.m[index] = array[index + offset];
  5923. }
  5924. result._markAsUpdated();
  5925. };
  5926. /**
  5927. * Stores an array into a matrix after having multiplied each component by a given factor
  5928. * @param array defines the source array
  5929. * @param offset defines the offset in the source array
  5930. * @param scale defines the scaling factor
  5931. * @param result defines the target matrix
  5932. */
  5933. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5934. for (var index = 0; index < 16; index++) {
  5935. result.m[index] = array[index + offset] * scale;
  5936. }
  5937. result._markAsUpdated();
  5938. };
  5939. /**
  5940. * Stores a list of values (16) inside a given matrix
  5941. * @param initialM11 defines 1st value of 1st row
  5942. * @param initialM12 defines 2nd value of 1st row
  5943. * @param initialM13 defines 3rd value of 1st row
  5944. * @param initialM14 defines 4th value of 1st row
  5945. * @param initialM21 defines 1st value of 2nd row
  5946. * @param initialM22 defines 2nd value of 2nd row
  5947. * @param initialM23 defines 3rd value of 2nd row
  5948. * @param initialM24 defines 4th value of 2nd row
  5949. * @param initialM31 defines 1st value of 3rd row
  5950. * @param initialM32 defines 2nd value of 3rd row
  5951. * @param initialM33 defines 3rd value of 3rd row
  5952. * @param initialM34 defines 4th value of 3rd row
  5953. * @param initialM41 defines 1st value of 4th row
  5954. * @param initialM42 defines 2nd value of 4th row
  5955. * @param initialM43 defines 3rd value of 4th row
  5956. * @param initialM44 defines 4th value of 4th row
  5957. * @param result defines the target matrix
  5958. */
  5959. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5960. result.m[0] = initialM11;
  5961. result.m[1] = initialM12;
  5962. result.m[2] = initialM13;
  5963. result.m[3] = initialM14;
  5964. result.m[4] = initialM21;
  5965. result.m[5] = initialM22;
  5966. result.m[6] = initialM23;
  5967. result.m[7] = initialM24;
  5968. result.m[8] = initialM31;
  5969. result.m[9] = initialM32;
  5970. result.m[10] = initialM33;
  5971. result.m[11] = initialM34;
  5972. result.m[12] = initialM41;
  5973. result.m[13] = initialM42;
  5974. result.m[14] = initialM43;
  5975. result.m[15] = initialM44;
  5976. result._markAsUpdated();
  5977. };
  5978. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5979. /**
  5980. * Gets an identity matrix that must not be updated
  5981. */
  5982. get: function () {
  5983. return Matrix._identityReadOnly;
  5984. },
  5985. enumerable: true,
  5986. configurable: true
  5987. });
  5988. /**
  5989. * Creates new matrix from a list of values (16)
  5990. * @param initialM11 defines 1st value of 1st row
  5991. * @param initialM12 defines 2nd value of 1st row
  5992. * @param initialM13 defines 3rd value of 1st row
  5993. * @param initialM14 defines 4th value of 1st row
  5994. * @param initialM21 defines 1st value of 2nd row
  5995. * @param initialM22 defines 2nd value of 2nd row
  5996. * @param initialM23 defines 3rd value of 2nd row
  5997. * @param initialM24 defines 4th value of 2nd row
  5998. * @param initialM31 defines 1st value of 3rd row
  5999. * @param initialM32 defines 2nd value of 3rd row
  6000. * @param initialM33 defines 3rd value of 3rd row
  6001. * @param initialM34 defines 4th value of 3rd row
  6002. * @param initialM41 defines 1st value of 4th row
  6003. * @param initialM42 defines 2nd value of 4th row
  6004. * @param initialM43 defines 3rd value of 4th row
  6005. * @param initialM44 defines 4th value of 4th row
  6006. * @returns the new matrix
  6007. */
  6008. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  6009. var result = new Matrix();
  6010. result.m[0] = initialM11;
  6011. result.m[1] = initialM12;
  6012. result.m[2] = initialM13;
  6013. result.m[3] = initialM14;
  6014. result.m[4] = initialM21;
  6015. result.m[5] = initialM22;
  6016. result.m[6] = initialM23;
  6017. result.m[7] = initialM24;
  6018. result.m[8] = initialM31;
  6019. result.m[9] = initialM32;
  6020. result.m[10] = initialM33;
  6021. result.m[11] = initialM34;
  6022. result.m[12] = initialM41;
  6023. result.m[13] = initialM42;
  6024. result.m[14] = initialM43;
  6025. result.m[15] = initialM44;
  6026. return result;
  6027. };
  6028. /**
  6029. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  6030. * @param scale defines the scale vector3
  6031. * @param rotation defines the rotation quaternion
  6032. * @param translation defines the translation vector3
  6033. * @returns a new matrix
  6034. */
  6035. Matrix.Compose = function (scale, rotation, translation) {
  6036. var result = Matrix.Identity();
  6037. Matrix.ComposeToRef(scale, rotation, translation, result);
  6038. return result;
  6039. };
  6040. /**
  6041. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  6042. * @param scale defines the scale vector3
  6043. * @param rotation defines the rotation quaternion
  6044. * @param translation defines the translation vector3
  6045. * @param result defines the target matrix
  6046. */
  6047. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  6048. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  6049. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  6050. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  6051. result.setTranslation(translation);
  6052. };
  6053. /**
  6054. * Creates a new identity matrix
  6055. * @returns a new identity matrix
  6056. */
  6057. Matrix.Identity = function () {
  6058. 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);
  6059. };
  6060. /**
  6061. * Creates a new identity matrix and stores the result in a given matrix
  6062. * @param result defines the target matrix
  6063. */
  6064. Matrix.IdentityToRef = function (result) {
  6065. 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);
  6066. };
  6067. /**
  6068. * Creates a new zero matrix
  6069. * @returns a new zero matrix
  6070. */
  6071. Matrix.Zero = function () {
  6072. 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);
  6073. };
  6074. /**
  6075. * Creates a new rotation matrix for "angle" radians around the X axis
  6076. * @param angle defines the angle (in radians) to use
  6077. * @return the new matrix
  6078. */
  6079. Matrix.RotationX = function (angle) {
  6080. var result = new Matrix();
  6081. Matrix.RotationXToRef(angle, result);
  6082. return result;
  6083. };
  6084. /**
  6085. * Creates a new matrix as the invert of a given matrix
  6086. * @param source defines the source matrix
  6087. * @returns the new matrix
  6088. */
  6089. Matrix.Invert = function (source) {
  6090. var result = new Matrix();
  6091. source.invertToRef(result);
  6092. return result;
  6093. };
  6094. /**
  6095. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  6096. * @param angle defines the angle (in radians) to use
  6097. * @param result defines the target matrix
  6098. */
  6099. Matrix.RotationXToRef = function (angle, result) {
  6100. var s = Math.sin(angle);
  6101. var c = Math.cos(angle);
  6102. result.m[0] = 1.0;
  6103. result.m[15] = 1.0;
  6104. result.m[5] = c;
  6105. result.m[10] = c;
  6106. result.m[9] = -s;
  6107. result.m[6] = s;
  6108. result.m[1] = 0.0;
  6109. result.m[2] = 0.0;
  6110. result.m[3] = 0.0;
  6111. result.m[4] = 0.0;
  6112. result.m[7] = 0.0;
  6113. result.m[8] = 0.0;
  6114. result.m[11] = 0.0;
  6115. result.m[12] = 0.0;
  6116. result.m[13] = 0.0;
  6117. result.m[14] = 0.0;
  6118. result._markAsUpdated();
  6119. };
  6120. /**
  6121. * Creates a new rotation matrix for "angle" radians around the Y axis
  6122. * @param angle defines the angle (in radians) to use
  6123. * @return the new matrix
  6124. */
  6125. Matrix.RotationY = function (angle) {
  6126. var result = new Matrix();
  6127. Matrix.RotationYToRef(angle, result);
  6128. return result;
  6129. };
  6130. /**
  6131. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  6132. * @param angle defines the angle (in radians) to use
  6133. * @param result defines the target matrix
  6134. */
  6135. Matrix.RotationYToRef = function (angle, result) {
  6136. var s = Math.sin(angle);
  6137. var c = Math.cos(angle);
  6138. result.m[5] = 1.0;
  6139. result.m[15] = 1.0;
  6140. result.m[0] = c;
  6141. result.m[2] = -s;
  6142. result.m[8] = s;
  6143. result.m[10] = c;
  6144. result.m[1] = 0.0;
  6145. result.m[3] = 0.0;
  6146. result.m[4] = 0.0;
  6147. result.m[6] = 0.0;
  6148. result.m[7] = 0.0;
  6149. result.m[9] = 0.0;
  6150. result.m[11] = 0.0;
  6151. result.m[12] = 0.0;
  6152. result.m[13] = 0.0;
  6153. result.m[14] = 0.0;
  6154. result._markAsUpdated();
  6155. };
  6156. /**
  6157. * Creates a new rotation matrix for "angle" radians around the Z axis
  6158. * @param angle defines the angle (in radians) to use
  6159. * @return the new matrix
  6160. */
  6161. Matrix.RotationZ = function (angle) {
  6162. var result = new Matrix();
  6163. Matrix.RotationZToRef(angle, result);
  6164. return result;
  6165. };
  6166. /**
  6167. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  6168. * @param angle defines the angle (in radians) to use
  6169. * @param result defines the target matrix
  6170. */
  6171. Matrix.RotationZToRef = function (angle, result) {
  6172. var s = Math.sin(angle);
  6173. var c = Math.cos(angle);
  6174. result.m[10] = 1.0;
  6175. result.m[15] = 1.0;
  6176. result.m[0] = c;
  6177. result.m[1] = s;
  6178. result.m[4] = -s;
  6179. result.m[5] = c;
  6180. result.m[2] = 0.0;
  6181. result.m[3] = 0.0;
  6182. result.m[6] = 0.0;
  6183. result.m[7] = 0.0;
  6184. result.m[8] = 0.0;
  6185. result.m[9] = 0.0;
  6186. result.m[11] = 0.0;
  6187. result.m[12] = 0.0;
  6188. result.m[13] = 0.0;
  6189. result.m[14] = 0.0;
  6190. result._markAsUpdated();
  6191. };
  6192. /**
  6193. * Creates a new rotation matrix for "angle" radians around the given axis
  6194. * @param axis defines the axis to use
  6195. * @param angle defines the angle (in radians) to use
  6196. * @return the new matrix
  6197. */
  6198. Matrix.RotationAxis = function (axis, angle) {
  6199. var result = Matrix.Zero();
  6200. Matrix.RotationAxisToRef(axis, angle, result);
  6201. return result;
  6202. };
  6203. /**
  6204. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  6205. * @param axis defines the axis to use
  6206. * @param angle defines the angle (in radians) to use
  6207. * @param result defines the target matrix
  6208. */
  6209. Matrix.RotationAxisToRef = function (axis, angle, result) {
  6210. var s = Math.sin(-angle);
  6211. var c = Math.cos(-angle);
  6212. var c1 = 1 - c;
  6213. axis.normalize();
  6214. result.m[0] = (axis.x * axis.x) * c1 + c;
  6215. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  6216. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  6217. result.m[3] = 0.0;
  6218. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  6219. result.m[5] = (axis.y * axis.y) * c1 + c;
  6220. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  6221. result.m[7] = 0.0;
  6222. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  6223. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  6224. result.m[10] = (axis.z * axis.z) * c1 + c;
  6225. result.m[11] = 0.0;
  6226. result.m[15] = 1.0;
  6227. result._markAsUpdated();
  6228. };
  6229. /**
  6230. * Creates a rotation matrix
  6231. * @param yaw defines the yaw angle in radians (Y axis)
  6232. * @param pitch defines the pitch angle in radians (X axis)
  6233. * @param roll defines the roll angle in radians (X axis)
  6234. * @returns the new rotation matrix
  6235. */
  6236. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  6237. var result = new Matrix();
  6238. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  6239. return result;
  6240. };
  6241. /**
  6242. * Creates a rotation matrix and stores it in a given matrix
  6243. * @param yaw defines the yaw angle in radians (Y axis)
  6244. * @param pitch defines the pitch angle in radians (X axis)
  6245. * @param roll defines the roll angle in radians (X axis)
  6246. * @param result defines the target matrix
  6247. */
  6248. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  6249. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  6250. this._tempQuaternion.toRotationMatrix(result);
  6251. };
  6252. /**
  6253. * Creates a scaling matrix
  6254. * @param x defines the scale factor on X axis
  6255. * @param y defines the scale factor on Y axis
  6256. * @param z defines the scale factor on Z axis
  6257. * @returns the new matrix
  6258. */
  6259. Matrix.Scaling = function (x, y, z) {
  6260. var result = Matrix.Zero();
  6261. Matrix.ScalingToRef(x, y, z, result);
  6262. return result;
  6263. };
  6264. /**
  6265. * Creates a scaling matrix and stores it in a given matrix
  6266. * @param x defines the scale factor on X axis
  6267. * @param y defines the scale factor on Y axis
  6268. * @param z defines the scale factor on Z axis
  6269. * @param result defines the target matrix
  6270. */
  6271. Matrix.ScalingToRef = function (x, y, z, result) {
  6272. result.m[0] = x;
  6273. result.m[1] = 0.0;
  6274. result.m[2] = 0.0;
  6275. result.m[3] = 0.0;
  6276. result.m[4] = 0.0;
  6277. result.m[5] = y;
  6278. result.m[6] = 0.0;
  6279. result.m[7] = 0.0;
  6280. result.m[8] = 0.0;
  6281. result.m[9] = 0.0;
  6282. result.m[10] = z;
  6283. result.m[11] = 0.0;
  6284. result.m[12] = 0.0;
  6285. result.m[13] = 0.0;
  6286. result.m[14] = 0.0;
  6287. result.m[15] = 1.0;
  6288. result._markAsUpdated();
  6289. };
  6290. /**
  6291. * Creates a translation matrix
  6292. * @param x defines the translation on X axis
  6293. * @param y defines the translation on Y axis
  6294. * @param z defines the translationon Z axis
  6295. * @returns the new matrix
  6296. */
  6297. Matrix.Translation = function (x, y, z) {
  6298. var result = Matrix.Identity();
  6299. Matrix.TranslationToRef(x, y, z, result);
  6300. return result;
  6301. };
  6302. /**
  6303. * Creates a translation matrix and stores it in a given matrix
  6304. * @param x defines the translation on X axis
  6305. * @param y defines the translation on Y axis
  6306. * @param z defines the translationon Z axis
  6307. * @param result defines the target matrix
  6308. */
  6309. Matrix.TranslationToRef = function (x, y, z, result) {
  6310. 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);
  6311. };
  6312. /**
  6313. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6314. * @param startValue defines the start value
  6315. * @param endValue defines the end value
  6316. * @param gradient defines the gradient factor
  6317. * @returns the new matrix
  6318. */
  6319. Matrix.Lerp = function (startValue, endValue, gradient) {
  6320. var result = Matrix.Zero();
  6321. Matrix.LerpToRef(startValue, endValue, gradient, result);
  6322. return result;
  6323. };
  6324. /**
  6325. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6326. * @param startValue defines the start value
  6327. * @param endValue defines the end value
  6328. * @param gradient defines the gradient factor
  6329. * @param result defines the Matrix object where to store data
  6330. */
  6331. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  6332. for (var index = 0; index < 16; index++) {
  6333. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  6334. }
  6335. result._markAsUpdated();
  6336. };
  6337. /**
  6338. * Builds a new matrix whose values are computed by:
  6339. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6340. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6341. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6342. * @param startValue defines the first matrix
  6343. * @param endValue defines the second matrix
  6344. * @param gradient defines the gradient between the two matrices
  6345. * @returns the new matrix
  6346. */
  6347. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6348. var result = Matrix.Zero();
  6349. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6350. return result;
  6351. };
  6352. /**
  6353. * Update a matrix to values which are computed by:
  6354. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6355. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6356. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6357. * @param startValue defines the first matrix
  6358. * @param endValue defines the second matrix
  6359. * @param gradient defines the gradient between the two matrices
  6360. * @param result defines the target matrix
  6361. */
  6362. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6363. var startScale = MathTmp.Vector3[0];
  6364. var startRotation = MathTmp.Quaternion[0];
  6365. var startTranslation = MathTmp.Vector3[1];
  6366. startValue.decompose(startScale, startRotation, startTranslation);
  6367. var endScale = MathTmp.Vector3[2];
  6368. var endRotation = MathTmp.Quaternion[1];
  6369. var endTranslation = MathTmp.Vector3[3];
  6370. endValue.decompose(endScale, endRotation, endTranslation);
  6371. var resultScale = MathTmp.Vector3[4];
  6372. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6373. var resultRotation = MathTmp.Quaternion[2];
  6374. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6375. var resultTranslation = MathTmp.Vector3[5];
  6376. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6377. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6378. };
  6379. /**
  6380. * 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"
  6381. * This function works in left handed mode
  6382. * @param eye defines the final position of the entity
  6383. * @param target defines where the entity should look at
  6384. * @param up defines the up vector for the entity
  6385. * @returns the new matrix
  6386. */
  6387. Matrix.LookAtLH = function (eye, target, up) {
  6388. var result = Matrix.Zero();
  6389. Matrix.LookAtLHToRef(eye, target, up, result);
  6390. return result;
  6391. };
  6392. /**
  6393. * 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".
  6394. * This function works in left handed mode
  6395. * @param eye defines the final position of the entity
  6396. * @param target defines where the entity should look at
  6397. * @param up defines the up vector for the entity
  6398. * @param result defines the target matrix
  6399. */
  6400. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6401. // Z axis
  6402. target.subtractToRef(eye, this._zAxis);
  6403. this._zAxis.normalize();
  6404. // X axis
  6405. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6406. if (this._xAxis.lengthSquared() === 0) {
  6407. this._xAxis.x = 1.0;
  6408. }
  6409. else {
  6410. this._xAxis.normalize();
  6411. }
  6412. // Y axis
  6413. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6414. this._yAxis.normalize();
  6415. // Eye angles
  6416. var ex = -Vector3.Dot(this._xAxis, eye);
  6417. var ey = -Vector3.Dot(this._yAxis, eye);
  6418. var ez = -Vector3.Dot(this._zAxis, eye);
  6419. 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);
  6420. };
  6421. /**
  6422. * 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"
  6423. * This function works in right handed mode
  6424. * @param eye defines the final position of the entity
  6425. * @param target defines where the entity should look at
  6426. * @param up defines the up vector for the entity
  6427. * @returns the new matrix
  6428. */
  6429. Matrix.LookAtRH = function (eye, target, up) {
  6430. var result = Matrix.Zero();
  6431. Matrix.LookAtRHToRef(eye, target, up, result);
  6432. return result;
  6433. };
  6434. /**
  6435. * 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".
  6436. * This function works in right handed mode
  6437. * @param eye defines the final position of the entity
  6438. * @param target defines where the entity should look at
  6439. * @param up defines the up vector for the entity
  6440. * @param result defines the target matrix
  6441. */
  6442. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6443. // Z axis
  6444. eye.subtractToRef(target, this._zAxis);
  6445. this._zAxis.normalize();
  6446. // X axis
  6447. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6448. if (this._xAxis.lengthSquared() === 0) {
  6449. this._xAxis.x = 1.0;
  6450. }
  6451. else {
  6452. this._xAxis.normalize();
  6453. }
  6454. // Y axis
  6455. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6456. this._yAxis.normalize();
  6457. // Eye angles
  6458. var ex = -Vector3.Dot(this._xAxis, eye);
  6459. var ey = -Vector3.Dot(this._yAxis, eye);
  6460. var ez = -Vector3.Dot(this._zAxis, eye);
  6461. 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);
  6462. };
  6463. /**
  6464. * Create a left-handed orthographic projection matrix
  6465. * @param width defines the viewport width
  6466. * @param height defines the viewport height
  6467. * @param znear defines the near clip plane
  6468. * @param zfar defines the far clip plane
  6469. * @returns a new matrix as a left-handed orthographic projection matrix
  6470. */
  6471. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6472. var matrix = Matrix.Zero();
  6473. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6474. return matrix;
  6475. };
  6476. /**
  6477. * Store a left-handed orthographic projection to a given matrix
  6478. * @param width defines the viewport width
  6479. * @param height defines the viewport height
  6480. * @param znear defines the near clip plane
  6481. * @param zfar defines the far clip plane
  6482. * @param result defines the target matrix
  6483. */
  6484. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6485. var n = znear;
  6486. var f = zfar;
  6487. var a = 2.0 / width;
  6488. var b = 2.0 / height;
  6489. var c = 2.0 / (f - n);
  6490. var d = -(f + n) / (f - n);
  6491. 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);
  6492. };
  6493. /**
  6494. * Create a left-handed orthographic projection matrix
  6495. * @param left defines the viewport left coordinate
  6496. * @param right defines the viewport right coordinate
  6497. * @param bottom defines the viewport bottom coordinate
  6498. * @param top defines the viewport top coordinate
  6499. * @param znear defines the near clip plane
  6500. * @param zfar defines the far clip plane
  6501. * @returns a new matrix as a left-handed orthographic projection matrix
  6502. */
  6503. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6504. var matrix = Matrix.Zero();
  6505. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6506. return matrix;
  6507. };
  6508. /**
  6509. * Stores a left-handed orthographic projection into a given matrix
  6510. * @param left defines the viewport left coordinate
  6511. * @param right defines the viewport right coordinate
  6512. * @param bottom defines the viewport bottom coordinate
  6513. * @param top defines the viewport top coordinate
  6514. * @param znear defines the near clip plane
  6515. * @param zfar defines the far clip plane
  6516. * @param result defines the target matrix
  6517. */
  6518. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6519. var n = znear;
  6520. var f = zfar;
  6521. var a = 2.0 / (right - left);
  6522. var b = 2.0 / (top - bottom);
  6523. var c = 2.0 / (f - n);
  6524. var d = -(f + n) / (f - n);
  6525. var i0 = (left + right) / (left - right);
  6526. var i1 = (top + bottom) / (bottom - top);
  6527. 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);
  6528. };
  6529. /**
  6530. * Creates a right-handed orthographic projection matrix
  6531. * @param left defines the viewport left coordinate
  6532. * @param right defines the viewport right coordinate
  6533. * @param bottom defines the viewport bottom coordinate
  6534. * @param top defines the viewport top coordinate
  6535. * @param znear defines the near clip plane
  6536. * @param zfar defines the far clip plane
  6537. * @returns a new matrix as a right-handed orthographic projection matrix
  6538. */
  6539. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6540. var matrix = Matrix.Zero();
  6541. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6542. return matrix;
  6543. };
  6544. /**
  6545. * Stores a right-handed orthographic projection into a given matrix
  6546. * @param left defines the viewport left coordinate
  6547. * @param right defines the viewport right coordinate
  6548. * @param bottom defines the viewport bottom coordinate
  6549. * @param top defines the viewport top coordinate
  6550. * @param znear defines the near clip plane
  6551. * @param zfar defines the far clip plane
  6552. * @param result defines the target matrix
  6553. */
  6554. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6555. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6556. result.m[10] *= -1.0;
  6557. };
  6558. /**
  6559. * Creates a left-handed perspective projection matrix
  6560. * @param width defines the viewport width
  6561. * @param height defines the viewport height
  6562. * @param znear defines the near clip plane
  6563. * @param zfar defines the far clip plane
  6564. * @returns a new matrix as a left-handed perspective projection matrix
  6565. */
  6566. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6567. var matrix = Matrix.Zero();
  6568. var n = znear;
  6569. var f = zfar;
  6570. var a = 2.0 * n / width;
  6571. var b = 2.0 * n / height;
  6572. var c = (f + n) / (f - n);
  6573. var d = -2.0 * f * n / (f - n);
  6574. 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);
  6575. return matrix;
  6576. };
  6577. /**
  6578. * Creates a left-handed perspective projection matrix
  6579. * @param fov defines the horizontal field of view
  6580. * @param aspect defines the aspect ratio
  6581. * @param znear defines the near clip plane
  6582. * @param zfar defines the far clip plane
  6583. * @returns a new matrix as a left-handed perspective projection matrix
  6584. */
  6585. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6586. var matrix = Matrix.Zero();
  6587. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6588. return matrix;
  6589. };
  6590. /**
  6591. * Stores a left-handed perspective projection into a given matrix
  6592. * @param fov defines the horizontal field of view
  6593. * @param aspect defines the aspect ratio
  6594. * @param znear defines the near clip plane
  6595. * @param zfar defines the far clip plane
  6596. * @param result defines the target matrix
  6597. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6598. */
  6599. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6600. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6601. var n = znear;
  6602. var f = zfar;
  6603. var t = 1.0 / (Math.tan(fov * 0.5));
  6604. var a = isVerticalFovFixed ? (t / aspect) : t;
  6605. var b = isVerticalFovFixed ? t : (t * aspect);
  6606. var c = (f + n) / (f - n);
  6607. var d = -2.0 * f * n / (f - n);
  6608. 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);
  6609. };
  6610. /**
  6611. * Creates a right-handed perspective projection matrix
  6612. * @param fov defines the horizontal field of view
  6613. * @param aspect defines the aspect ratio
  6614. * @param znear defines the near clip plane
  6615. * @param zfar defines the far clip plane
  6616. * @returns a new matrix as a right-handed perspective projection matrix
  6617. */
  6618. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6619. var matrix = Matrix.Zero();
  6620. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6621. return matrix;
  6622. };
  6623. /**
  6624. * Stores a right-handed perspective projection into a given matrix
  6625. * @param fov defines the horizontal field of view
  6626. * @param aspect defines the aspect ratio
  6627. * @param znear defines the near clip plane
  6628. * @param zfar defines the far clip plane
  6629. * @param result defines the target matrix
  6630. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6631. */
  6632. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6633. //alternatively this could be expressed as:
  6634. // m = PerspectiveFovLHToRef
  6635. // m[10] *= -1.0;
  6636. // m[11] *= -1.0;
  6637. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6638. var n = znear;
  6639. var f = zfar;
  6640. var t = 1.0 / (Math.tan(fov * 0.5));
  6641. var a = isVerticalFovFixed ? (t / aspect) : t;
  6642. var b = isVerticalFovFixed ? t : (t * aspect);
  6643. var c = -(f + n) / (f - n);
  6644. var d = -2 * f * n / (f - n);
  6645. 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);
  6646. };
  6647. /**
  6648. * Stores a perspective projection for WebVR info a given matrix
  6649. * @param fov defines the field of view
  6650. * @param znear defines the near clip plane
  6651. * @param zfar defines the far clip plane
  6652. * @param result defines the target matrix
  6653. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6654. */
  6655. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6656. if (rightHanded === void 0) { rightHanded = false; }
  6657. var rightHandedFactor = rightHanded ? -1 : 1;
  6658. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6659. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6660. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6661. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6662. var xScale = 2.0 / (leftTan + rightTan);
  6663. var yScale = 2.0 / (upTan + downTan);
  6664. result.m[0] = xScale;
  6665. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6666. result.m[5] = yScale;
  6667. result.m[6] = result.m[7] = 0.0;
  6668. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6669. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6670. result.m[10] = -zfar / (znear - zfar);
  6671. result.m[11] = 1.0 * rightHandedFactor;
  6672. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6673. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6674. result._markAsUpdated();
  6675. };
  6676. /**
  6677. * Computes a complete transformation matrix
  6678. * @param viewport defines the viewport to use
  6679. * @param world defines the world matrix
  6680. * @param view defines the view matrix
  6681. * @param projection defines the projection matrix
  6682. * @param zmin defines the near clip plane
  6683. * @param zmax defines the far clip plane
  6684. * @returns the transformation matrix
  6685. */
  6686. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6687. var cw = viewport.width;
  6688. var ch = viewport.height;
  6689. var cx = viewport.x;
  6690. var cy = viewport.y;
  6691. 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);
  6692. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6693. };
  6694. /**
  6695. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6696. * @param matrix defines the matrix to use
  6697. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6698. */
  6699. Matrix.GetAsMatrix2x2 = function (matrix) {
  6700. return new Float32Array([
  6701. matrix.m[0], matrix.m[1],
  6702. matrix.m[4], matrix.m[5]
  6703. ]);
  6704. };
  6705. /**
  6706. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6707. * @param matrix defines the matrix to use
  6708. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6709. */
  6710. Matrix.GetAsMatrix3x3 = function (matrix) {
  6711. return new Float32Array([
  6712. matrix.m[0], matrix.m[1], matrix.m[2],
  6713. matrix.m[4], matrix.m[5], matrix.m[6],
  6714. matrix.m[8], matrix.m[9], matrix.m[10]
  6715. ]);
  6716. };
  6717. /**
  6718. * Compute the transpose of a given matrix
  6719. * @param matrix defines the matrix to transpose
  6720. * @returns the new matrix
  6721. */
  6722. Matrix.Transpose = function (matrix) {
  6723. var result = new Matrix();
  6724. Matrix.TransposeToRef(matrix, result);
  6725. return result;
  6726. };
  6727. /**
  6728. * Compute the transpose of a matrix and store it in a target matrix
  6729. * @param matrix defines the matrix to transpose
  6730. * @param result defines the target matrix
  6731. */
  6732. Matrix.TransposeToRef = function (matrix, result) {
  6733. result.m[0] = matrix.m[0];
  6734. result.m[1] = matrix.m[4];
  6735. result.m[2] = matrix.m[8];
  6736. result.m[3] = matrix.m[12];
  6737. result.m[4] = matrix.m[1];
  6738. result.m[5] = matrix.m[5];
  6739. result.m[6] = matrix.m[9];
  6740. result.m[7] = matrix.m[13];
  6741. result.m[8] = matrix.m[2];
  6742. result.m[9] = matrix.m[6];
  6743. result.m[10] = matrix.m[10];
  6744. result.m[11] = matrix.m[14];
  6745. result.m[12] = matrix.m[3];
  6746. result.m[13] = matrix.m[7];
  6747. result.m[14] = matrix.m[11];
  6748. result.m[15] = matrix.m[15];
  6749. };
  6750. /**
  6751. * Computes a reflection matrix from a plane
  6752. * @param plane defines the reflection plane
  6753. * @returns a new matrix
  6754. */
  6755. Matrix.Reflection = function (plane) {
  6756. var matrix = new Matrix();
  6757. Matrix.ReflectionToRef(plane, matrix);
  6758. return matrix;
  6759. };
  6760. /**
  6761. * Computes a reflection matrix from a plane
  6762. * @param plane defines the reflection plane
  6763. * @param result defines the target matrix
  6764. */
  6765. Matrix.ReflectionToRef = function (plane, result) {
  6766. plane.normalize();
  6767. var x = plane.normal.x;
  6768. var y = plane.normal.y;
  6769. var z = plane.normal.z;
  6770. var temp = -2 * x;
  6771. var temp2 = -2 * y;
  6772. var temp3 = -2 * z;
  6773. result.m[0] = (temp * x) + 1;
  6774. result.m[1] = temp2 * x;
  6775. result.m[2] = temp3 * x;
  6776. result.m[3] = 0.0;
  6777. result.m[4] = temp * y;
  6778. result.m[5] = (temp2 * y) + 1;
  6779. result.m[6] = temp3 * y;
  6780. result.m[7] = 0.0;
  6781. result.m[8] = temp * z;
  6782. result.m[9] = temp2 * z;
  6783. result.m[10] = (temp3 * z) + 1;
  6784. result.m[11] = 0.0;
  6785. result.m[12] = temp * plane.d;
  6786. result.m[13] = temp2 * plane.d;
  6787. result.m[14] = temp3 * plane.d;
  6788. result.m[15] = 1.0;
  6789. result._markAsUpdated();
  6790. };
  6791. /**
  6792. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6793. * @param xaxis defines the value of the 1st axis
  6794. * @param yaxis defines the value of the 2nd axis
  6795. * @param zaxis defines the value of the 3rd axis
  6796. * @param result defines the target matrix
  6797. */
  6798. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6799. result.m[0] = xaxis.x;
  6800. result.m[1] = xaxis.y;
  6801. result.m[2] = xaxis.z;
  6802. result.m[3] = 0.0;
  6803. result.m[4] = yaxis.x;
  6804. result.m[5] = yaxis.y;
  6805. result.m[6] = yaxis.z;
  6806. result.m[7] = 0.0;
  6807. result.m[8] = zaxis.x;
  6808. result.m[9] = zaxis.y;
  6809. result.m[10] = zaxis.z;
  6810. result.m[11] = 0.0;
  6811. result.m[12] = 0.0;
  6812. result.m[13] = 0.0;
  6813. result.m[14] = 0.0;
  6814. result.m[15] = 1.0;
  6815. result._markAsUpdated();
  6816. };
  6817. /**
  6818. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6819. * @param quat defines the quaternion to use
  6820. * @param result defines the target matrix
  6821. */
  6822. Matrix.FromQuaternionToRef = function (quat, result) {
  6823. var xx = quat.x * quat.x;
  6824. var yy = quat.y * quat.y;
  6825. var zz = quat.z * quat.z;
  6826. var xy = quat.x * quat.y;
  6827. var zw = quat.z * quat.w;
  6828. var zx = quat.z * quat.x;
  6829. var yw = quat.y * quat.w;
  6830. var yz = quat.y * quat.z;
  6831. var xw = quat.x * quat.w;
  6832. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6833. result.m[1] = 2.0 * (xy + zw);
  6834. result.m[2] = 2.0 * (zx - yw);
  6835. result.m[3] = 0.0;
  6836. result.m[4] = 2.0 * (xy - zw);
  6837. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6838. result.m[6] = 2.0 * (yz + xw);
  6839. result.m[7] = 0.0;
  6840. result.m[8] = 2.0 * (zx + yw);
  6841. result.m[9] = 2.0 * (yz - xw);
  6842. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6843. result.m[11] = 0.0;
  6844. result.m[12] = 0.0;
  6845. result.m[13] = 0.0;
  6846. result.m[14] = 0.0;
  6847. result.m[15] = 1.0;
  6848. result._markAsUpdated();
  6849. };
  6850. Matrix._tempQuaternion = new Quaternion();
  6851. Matrix._xAxis = Vector3.Zero();
  6852. Matrix._yAxis = Vector3.Zero();
  6853. Matrix._zAxis = Vector3.Zero();
  6854. Matrix._updateFlagSeed = 0;
  6855. Matrix._identityReadOnly = Matrix.Identity();
  6856. return Matrix;
  6857. }());
  6858. BABYLON.Matrix = Matrix;
  6859. /**
  6860. * Represens a plane by the equation ax + by + cz + d = 0
  6861. */
  6862. var Plane = /** @class */ (function () {
  6863. /**
  6864. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6865. * @param a a component of the plane
  6866. * @param b b component of the plane
  6867. * @param c c component of the plane
  6868. * @param d d component of the plane
  6869. */
  6870. function Plane(a, b, c, d) {
  6871. this.normal = new Vector3(a, b, c);
  6872. this.d = d;
  6873. }
  6874. /**
  6875. * @returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6876. */
  6877. Plane.prototype.asArray = function () {
  6878. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6879. };
  6880. // Methods
  6881. /**
  6882. * @returns a new plane copied from the current Plane.
  6883. */
  6884. Plane.prototype.clone = function () {
  6885. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6886. };
  6887. /**
  6888. * @returns the string "Plane".
  6889. */
  6890. Plane.prototype.getClassName = function () {
  6891. return "Plane";
  6892. };
  6893. /**
  6894. * @returns the Plane hash code.
  6895. */
  6896. Plane.prototype.getHashCode = function () {
  6897. var hash = this.normal.getHashCode();
  6898. hash = (hash * 397) ^ (this.d || 0);
  6899. return hash;
  6900. };
  6901. /**
  6902. * Normalize the current Plane in place.
  6903. * @returns the updated Plane.
  6904. */
  6905. Plane.prototype.normalize = function () {
  6906. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6907. var magnitude = 0.0;
  6908. if (norm !== 0) {
  6909. magnitude = 1.0 / norm;
  6910. }
  6911. this.normal.x *= magnitude;
  6912. this.normal.y *= magnitude;
  6913. this.normal.z *= magnitude;
  6914. this.d *= magnitude;
  6915. return this;
  6916. };
  6917. /**
  6918. * Applies a transformation the plane and returns the result
  6919. * @param transformation the transformation matrix to be applied to the plane
  6920. * @returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6921. */
  6922. Plane.prototype.transform = function (transformation) {
  6923. var transposedMatrix = Matrix.Transpose(transformation);
  6924. var x = this.normal.x;
  6925. var y = this.normal.y;
  6926. var z = this.normal.z;
  6927. var d = this.d;
  6928. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6929. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6930. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6931. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6932. return new Plane(normalX, normalY, normalZ, finalD);
  6933. };
  6934. /**
  6935. * Calcualtte the dot product between the point and the plane normal
  6936. * @param point point to calculate the dot product with
  6937. * @returns the dot product (float) of the point coordinates and the plane normal.
  6938. */
  6939. Plane.prototype.dotCoordinate = function (point) {
  6940. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6941. };
  6942. /**
  6943. * Updates the current Plane from the plane defined by the three given points.
  6944. * @param point1 one of the points used to contruct the plane
  6945. * @param point2 one of the points used to contruct the plane
  6946. * @param point3 one of the points used to contruct the plane
  6947. * @returns the updated Plane.
  6948. */
  6949. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6950. var x1 = point2.x - point1.x;
  6951. var y1 = point2.y - point1.y;
  6952. var z1 = point2.z - point1.z;
  6953. var x2 = point3.x - point1.x;
  6954. var y2 = point3.y - point1.y;
  6955. var z2 = point3.z - point1.z;
  6956. var yz = (y1 * z2) - (z1 * y2);
  6957. var xz = (z1 * x2) - (x1 * z2);
  6958. var xy = (x1 * y2) - (y1 * x2);
  6959. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6960. var invPyth;
  6961. if (pyth !== 0) {
  6962. invPyth = 1.0 / pyth;
  6963. }
  6964. else {
  6965. invPyth = 0.0;
  6966. }
  6967. this.normal.x = yz * invPyth;
  6968. this.normal.y = xz * invPyth;
  6969. this.normal.z = xy * invPyth;
  6970. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6971. return this;
  6972. };
  6973. /**
  6974. * Checks if the plane is facing a given direction
  6975. * @param direction the direction to check if the plane is facing
  6976. * @param epsilon value the dot product is compared against (returns true if dot <= epsilon)
  6977. * @returns True is the vector "direction" is the same side than the plane normal.
  6978. */
  6979. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6980. var dot = Vector3.Dot(this.normal, direction);
  6981. return (dot <= epsilon);
  6982. };
  6983. /**
  6984. * Calculates the distance to a point
  6985. * @param point point to calculate distance to
  6986. * @returns the signed distance (float) from the given point to the Plane.
  6987. */
  6988. Plane.prototype.signedDistanceTo = function (point) {
  6989. return Vector3.Dot(point, this.normal) + this.d;
  6990. };
  6991. // Statics
  6992. /**
  6993. * Creates a plane from an array
  6994. * @param array the array to create a plane from
  6995. * @returns a new Plane from the given array.
  6996. */
  6997. Plane.FromArray = function (array) {
  6998. return new Plane(array[0], array[1], array[2], array[3]);
  6999. };
  7000. /**
  7001. * Creates a plane from three points
  7002. * @param point1 point used to create the plane
  7003. * @param point2 point used to create the plane
  7004. * @param point3 point used to create the plane
  7005. * @returns a new Plane defined by the three given points.
  7006. */
  7007. Plane.FromPoints = function (point1, point2, point3) {
  7008. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  7009. result.copyFromPoints(point1, point2, point3);
  7010. return result;
  7011. };
  7012. /**
  7013. * Creates a plane from an origin point and a normal
  7014. * @param origin origin of the plane to be constructed
  7015. * @param normal normal of the plane to be constructed
  7016. * @returns a new Plane the normal vector to this plane at the given origin point.
  7017. * Note : the vector "normal" is updated because normalized.
  7018. */
  7019. Plane.FromPositionAndNormal = function (origin, normal) {
  7020. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  7021. normal.normalize();
  7022. result.normal = normal;
  7023. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  7024. return result;
  7025. };
  7026. /**
  7027. * Calculates the distance from a plane and a point
  7028. * @param origin origin of the plane to be constructed
  7029. * @param normal normal of the plane to be constructed
  7030. * @param point point to calculate distance to
  7031. * @returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  7032. */
  7033. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  7034. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  7035. return Vector3.Dot(point, normal) + d;
  7036. };
  7037. return Plane;
  7038. }());
  7039. BABYLON.Plane = Plane;
  7040. /**
  7041. * Class used to represent a viewport on screen
  7042. */
  7043. var Viewport = /** @class */ (function () {
  7044. /**
  7045. * Creates a Viewport object located at (x, y) and sized (width, height)
  7046. * @param x defines viewport left coordinate
  7047. * @param y defines viewport top coordinate
  7048. * @param width defines the viewport width
  7049. * @param height defines the viewport height
  7050. */
  7051. function Viewport(
  7052. /** viewport left coordinate */
  7053. x,
  7054. /** viewport top coordinate */
  7055. y,
  7056. /**viewport width */
  7057. width,
  7058. /** viewport height */
  7059. height) {
  7060. this.x = x;
  7061. this.y = y;
  7062. this.width = width;
  7063. this.height = height;
  7064. }
  7065. /**
  7066. * Creates a new viewport using absolute sizing (from 0-> width, 0-> height instead of 0->1)
  7067. * @param renderWidthOrEngine defines either an engine or the rendering width
  7068. * @param renderHeight defines the rendering height
  7069. * @returns a new Viewport
  7070. */
  7071. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  7072. if (renderWidthOrEngine.getRenderWidth) {
  7073. var engine = renderWidthOrEngine;
  7074. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  7075. }
  7076. var renderWidth = renderWidthOrEngine;
  7077. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  7078. };
  7079. /**
  7080. * Returns a new Viewport copied from the current one
  7081. * @returns a new Viewport
  7082. */
  7083. Viewport.prototype.clone = function () {
  7084. return new Viewport(this.x, this.y, this.width, this.height);
  7085. };
  7086. return Viewport;
  7087. }());
  7088. BABYLON.Viewport = Viewport;
  7089. /**
  7090. * Reprasents a camera frustum
  7091. */
  7092. var Frustum = /** @class */ (function () {
  7093. function Frustum() {
  7094. }
  7095. /**
  7096. * Gets the planes representing the frustum
  7097. * @param transform matrix to be applied to the returned planes
  7098. * @returns a new array of 6 Frustum planes computed by the given transformation matrix.
  7099. */
  7100. Frustum.GetPlanes = function (transform) {
  7101. var frustumPlanes = [];
  7102. for (var index = 0; index < 6; index++) {
  7103. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  7104. }
  7105. Frustum.GetPlanesToRef(transform, frustumPlanes);
  7106. return frustumPlanes;
  7107. };
  7108. /**
  7109. * Gets the near frustum plane transformed by the transform matrix
  7110. * @param transform transformation matrix to be applied to the resulting frustum plane
  7111. * @param frustumPlane the resuling frustum plane
  7112. */
  7113. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  7114. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  7115. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  7116. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  7117. frustumPlane.d = transform.m[15] + transform.m[14];
  7118. frustumPlane.normalize();
  7119. };
  7120. /**
  7121. * Gets the far frustum plane transformed by the transform matrix
  7122. * @param transform transformation matrix to be applied to the resulting frustum plane
  7123. * @param frustumPlane the resuling frustum plane
  7124. */
  7125. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  7126. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  7127. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  7128. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  7129. frustumPlane.d = transform.m[15] - transform.m[14];
  7130. frustumPlane.normalize();
  7131. };
  7132. /**
  7133. * Gets the left frustum plane transformed by the transform matrix
  7134. * @param transform transformation matrix to be applied to the resulting frustum plane
  7135. * @param frustumPlane the resuling frustum plane
  7136. */
  7137. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  7138. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  7139. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  7140. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  7141. frustumPlane.d = transform.m[15] + transform.m[12];
  7142. frustumPlane.normalize();
  7143. };
  7144. /**
  7145. * Gets the right frustum plane transformed by the transform matrix
  7146. * @param transform transformation matrix to be applied to the resulting frustum plane
  7147. * @param frustumPlane the resuling frustum plane
  7148. */
  7149. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  7150. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  7151. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  7152. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  7153. frustumPlane.d = transform.m[15] - transform.m[12];
  7154. frustumPlane.normalize();
  7155. };
  7156. /**
  7157. * Gets the top frustum plane transformed by the transform matrix
  7158. * @param transform transformation matrix to be applied to the resulting frustum plane
  7159. * @param frustumPlane the resuling frustum plane
  7160. */
  7161. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  7162. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  7163. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  7164. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  7165. frustumPlane.d = transform.m[15] - transform.m[13];
  7166. frustumPlane.normalize();
  7167. };
  7168. /**
  7169. * Gets the bottom frustum plane transformed by the transform matrix
  7170. * @param transform transformation matrix to be applied to the resulting frustum plane
  7171. * @param frustumPlane the resuling frustum plane
  7172. */
  7173. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  7174. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  7175. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  7176. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  7177. frustumPlane.d = transform.m[15] + transform.m[13];
  7178. frustumPlane.normalize();
  7179. };
  7180. /**
  7181. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  7182. * @param transform transformation matrix to be applied to the resulting frustum planes
  7183. * @param frustumPlanes the resuling frustum planes
  7184. */
  7185. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  7186. // Near
  7187. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  7188. // Far
  7189. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  7190. // Left
  7191. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  7192. // Right
  7193. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  7194. // Top
  7195. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  7196. // Bottom
  7197. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  7198. };
  7199. return Frustum;
  7200. }());
  7201. BABYLON.Frustum = Frustum;
  7202. /** Defines supported spaces */
  7203. var Space;
  7204. (function (Space) {
  7205. /** Local (object) space */
  7206. Space[Space["LOCAL"] = 0] = "LOCAL";
  7207. /** World space */
  7208. Space[Space["WORLD"] = 1] = "WORLD";
  7209. /** Bone space */
  7210. Space[Space["BONE"] = 2] = "BONE";
  7211. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  7212. /** Defines the 3 main axes */
  7213. var Axis = /** @class */ (function () {
  7214. function Axis() {
  7215. }
  7216. /** X axis */
  7217. Axis.X = new Vector3(1.0, 0.0, 0.0);
  7218. /** Y axis */
  7219. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  7220. /** Z axis */
  7221. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  7222. return Axis;
  7223. }());
  7224. BABYLON.Axis = Axis;
  7225. ;
  7226. /** Class used to represent a Bezier curve */
  7227. var BezierCurve = /** @class */ (function () {
  7228. function BezierCurve() {
  7229. }
  7230. /**
  7231. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats
  7232. * @param t defines the time
  7233. * @param x1 defines the left coordinate on X axis
  7234. * @param y1 defines the left coordinate on Y axis
  7235. * @param x2 defines the right coordinate on X axis
  7236. * @param y2 defines the right coordinate on Y axis
  7237. * @returns the interpolated value
  7238. */
  7239. BezierCurve.Interpolate = function (t, x1, y1, x2, y2) {
  7240. // Extract X (which is equal to time here)
  7241. var f0 = 1 - 3 * x2 + 3 * x1;
  7242. var f1 = 3 * x2 - 6 * x1;
  7243. var f2 = 3 * x1;
  7244. var refinedT = t;
  7245. for (var i = 0; i < 5; i++) {
  7246. var refinedT2 = refinedT * refinedT;
  7247. var refinedT3 = refinedT2 * refinedT;
  7248. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  7249. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  7250. refinedT -= (x - t) * slope;
  7251. refinedT = Math.min(1, Math.max(0, refinedT));
  7252. }
  7253. // Resolve cubic bezier for the given x
  7254. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  7255. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  7256. Math.pow(refinedT, 3);
  7257. };
  7258. return BezierCurve;
  7259. }());
  7260. BABYLON.BezierCurve = BezierCurve;
  7261. /**
  7262. * Defines potential orientation for back face culling
  7263. */
  7264. var Orientation;
  7265. (function (Orientation) {
  7266. /**
  7267. * Clockwise
  7268. */
  7269. Orientation[Orientation["CW"] = 0] = "CW";
  7270. /** Counter clockwise */
  7271. Orientation[Orientation["CCW"] = 1] = "CCW";
  7272. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  7273. /**
  7274. * Defines angle representation
  7275. */
  7276. var Angle = /** @class */ (function () {
  7277. /**
  7278. * Creates an Angle object of "radians" radians (float).
  7279. */
  7280. function Angle(radians) {
  7281. this._radians = radians;
  7282. if (this._radians < 0.0)
  7283. this._radians += (2.0 * Math.PI);
  7284. }
  7285. /**
  7286. * Get value in degrees
  7287. * @returns the Angle value in degrees (float)
  7288. */
  7289. Angle.prototype.degrees = function () {
  7290. return this._radians * 180.0 / Math.PI;
  7291. };
  7292. /**
  7293. * Get value in radians
  7294. * @returns the Angle value in radians (float)
  7295. */
  7296. Angle.prototype.radians = function () {
  7297. return this._radians;
  7298. };
  7299. /**
  7300. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  7301. * @param a defines first vector
  7302. * @param b defines second vector
  7303. * @returns a new Angle
  7304. */
  7305. Angle.BetweenTwoPoints = function (a, b) {
  7306. var delta = b.subtract(a);
  7307. var theta = Math.atan2(delta.y, delta.x);
  7308. return new Angle(theta);
  7309. };
  7310. /**
  7311. * Gets a new Angle object from the given float in radians
  7312. * @param radians defines the angle value in radians
  7313. * @returns a new Angle
  7314. */
  7315. Angle.FromRadians = function (radians) {
  7316. return new Angle(radians);
  7317. };
  7318. /**
  7319. * Gets a new Angle object from the given float in degrees
  7320. * @param degrees defines the angle value in degrees
  7321. * @returns a new Angle
  7322. */
  7323. Angle.FromDegrees = function (degrees) {
  7324. return new Angle(degrees * Math.PI / 180.0);
  7325. };
  7326. return Angle;
  7327. }());
  7328. BABYLON.Angle = Angle;
  7329. /**
  7330. * This represents an arc in a 2d space.
  7331. */
  7332. var Arc2 = /** @class */ (function () {
  7333. /**
  7334. * Creates an Arc object from the three given points : start, middle and end.
  7335. * @param startPoint Defines the start point of the arc
  7336. * @param midPoint Defines the midlle point of the arc
  7337. * @param endPoint Defines the end point of the arc
  7338. */
  7339. function Arc2(
  7340. /** Defines the start point of the arc */
  7341. startPoint,
  7342. /** Defines the mid point of the arc */
  7343. midPoint,
  7344. /** Defines the end point of the arc */
  7345. endPoint) {
  7346. this.startPoint = startPoint;
  7347. this.midPoint = midPoint;
  7348. this.endPoint = endPoint;
  7349. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  7350. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  7351. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  7352. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  7353. 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);
  7354. this.radius = this.centerPoint.subtract(this.startPoint).length();
  7355. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  7356. var a1 = this.startAngle.degrees();
  7357. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  7358. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  7359. // angles correction
  7360. if (a2 - a1 > +180.0)
  7361. a2 -= 360.0;
  7362. if (a2 - a1 < -180.0)
  7363. a2 += 360.0;
  7364. if (a3 - a2 > +180.0)
  7365. a3 -= 360.0;
  7366. if (a3 - a2 < -180.0)
  7367. a3 += 360.0;
  7368. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  7369. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  7370. }
  7371. return Arc2;
  7372. }());
  7373. BABYLON.Arc2 = Arc2;
  7374. /**
  7375. * Represents a 2D path made up of multiple 2D points
  7376. */
  7377. var Path2 = /** @class */ (function () {
  7378. /**
  7379. * Creates a Path2 object from the starting 2D coordinates x and y.
  7380. * @param x the starting points x value
  7381. * @param y the starting points y value
  7382. */
  7383. function Path2(x, y) {
  7384. this._points = new Array();
  7385. this._length = 0.0;
  7386. /**
  7387. * If the path start and end point are the same
  7388. */
  7389. this.closed = false;
  7390. this._points.push(new Vector2(x, y));
  7391. }
  7392. /**
  7393. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  7394. * @param x the added points x value
  7395. * @param y the added points y value
  7396. * @returns the updated Path2.
  7397. */
  7398. Path2.prototype.addLineTo = function (x, y) {
  7399. if (this.closed) {
  7400. return this;
  7401. }
  7402. var newPoint = new Vector2(x, y);
  7403. var previousPoint = this._points[this._points.length - 1];
  7404. this._points.push(newPoint);
  7405. this._length += newPoint.subtract(previousPoint).length();
  7406. return this;
  7407. };
  7408. /**
  7409. * 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.
  7410. * @param midX middle point x value
  7411. * @param midY middle point y value
  7412. * @param endX end point x value
  7413. * @param endY end point y value
  7414. * @param numberOfSegments (default: 36)
  7415. * @returns the updated Path2.
  7416. */
  7417. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  7418. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  7419. if (this.closed) {
  7420. return this;
  7421. }
  7422. var startPoint = this._points[this._points.length - 1];
  7423. var midPoint = new Vector2(midX, midY);
  7424. var endPoint = new Vector2(endX, endY);
  7425. var arc = new Arc2(startPoint, midPoint, endPoint);
  7426. var increment = arc.angle.radians() / numberOfSegments;
  7427. if (arc.orientation === Orientation.CW)
  7428. increment *= -1;
  7429. var currentAngle = arc.startAngle.radians() + increment;
  7430. for (var i = 0; i < numberOfSegments; i++) {
  7431. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  7432. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  7433. this.addLineTo(x, y);
  7434. currentAngle += increment;
  7435. }
  7436. return this;
  7437. };
  7438. /**
  7439. * Closes the Path2.
  7440. * @returns the Path2.
  7441. */
  7442. Path2.prototype.close = function () {
  7443. this.closed = true;
  7444. return this;
  7445. };
  7446. /**
  7447. * Gets the sum of the distance between each sequential point in the path
  7448. * @returns the Path2 total length (float).
  7449. */
  7450. Path2.prototype.length = function () {
  7451. var result = this._length;
  7452. if (!this.closed) {
  7453. var lastPoint = this._points[this._points.length - 1];
  7454. var firstPoint = this._points[0];
  7455. result += (firstPoint.subtract(lastPoint).length());
  7456. }
  7457. return result;
  7458. };
  7459. /**
  7460. * Gets the points which construct the path
  7461. * @returns the Path2 internal array of points.
  7462. */
  7463. Path2.prototype.getPoints = function () {
  7464. return this._points;
  7465. };
  7466. /**
  7467. * Retreives the point at the distance aways from the starting point
  7468. * @param normalizedLengthPosition the length along the path to retreive the point from
  7469. * @returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7470. */
  7471. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7472. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7473. return Vector2.Zero();
  7474. }
  7475. var lengthPosition = normalizedLengthPosition * this.length();
  7476. var previousOffset = 0;
  7477. for (var i = 0; i < this._points.length; i++) {
  7478. var j = (i + 1) % this._points.length;
  7479. var a = this._points[i];
  7480. var b = this._points[j];
  7481. var bToA = b.subtract(a);
  7482. var nextOffset = (bToA.length() + previousOffset);
  7483. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7484. var dir = bToA.normalize();
  7485. var localOffset = lengthPosition - previousOffset;
  7486. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7487. }
  7488. previousOffset = nextOffset;
  7489. }
  7490. return Vector2.Zero();
  7491. };
  7492. /**
  7493. * Creates a new path starting from an x and y position
  7494. * @param x starting x value
  7495. * @param y starting y value
  7496. * @returns a new Path2 starting at the coordinates (x, y).
  7497. */
  7498. Path2.StartingAt = function (x, y) {
  7499. return new Path2(x, y);
  7500. };
  7501. return Path2;
  7502. }());
  7503. BABYLON.Path2 = Path2;
  7504. /**
  7505. * Represents a 3D path made up of multiple 3D points
  7506. */
  7507. var Path3D = /** @class */ (function () {
  7508. /**
  7509. * new Path3D(path, normal, raw)
  7510. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7511. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7512. * @param path an array of Vector3, the curve axis of the Path3D
  7513. * @param normal (options) Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7514. * @param raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7515. */
  7516. function Path3D(
  7517. /**
  7518. * an array of Vector3, the curve axis of the Path3D
  7519. */
  7520. path, firstNormal, raw) {
  7521. if (firstNormal === void 0) { firstNormal = null; }
  7522. this.path = path;
  7523. this._curve = new Array();
  7524. this._distances = new Array();
  7525. this._tangents = new Array();
  7526. this._normals = new Array();
  7527. this._binormals = new Array();
  7528. for (var p = 0; p < path.length; p++) {
  7529. this._curve[p] = path[p].clone(); // hard copy
  7530. }
  7531. this._raw = raw || false;
  7532. this._compute(firstNormal);
  7533. }
  7534. /**
  7535. * Returns the Path3D array of successive Vector3 designing its curve.
  7536. * @returns the Path3D array of successive Vector3 designing its curve.
  7537. */
  7538. Path3D.prototype.getCurve = function () {
  7539. return this._curve;
  7540. };
  7541. /**
  7542. * Returns an array populated with tangent vectors on each Path3D curve point.
  7543. * @returns an array populated with tangent vectors on each Path3D curve point.
  7544. */
  7545. Path3D.prototype.getTangents = function () {
  7546. return this._tangents;
  7547. };
  7548. /**
  7549. * Returns an array populated with normal vectors on each Path3D curve point.
  7550. * @returns an array populated with normal vectors on each Path3D curve point.
  7551. */
  7552. Path3D.prototype.getNormals = function () {
  7553. return this._normals;
  7554. };
  7555. /**
  7556. * Returns an array populated with binormal vectors on each Path3D curve point.
  7557. * @returns an array populated with binormal vectors on each Path3D curve point.
  7558. */
  7559. Path3D.prototype.getBinormals = function () {
  7560. return this._binormals;
  7561. };
  7562. /**
  7563. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7564. * @returns an array populated with distances (float) of the i-th point from the first curve point.
  7565. */
  7566. Path3D.prototype.getDistances = function () {
  7567. return this._distances;
  7568. };
  7569. /**
  7570. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7571. * @param path path which all values are copied into the curves points
  7572. * @param firstNormal which should be projected onto the curve
  7573. * @returns the same object updated.
  7574. */
  7575. Path3D.prototype.update = function (path, firstNormal) {
  7576. if (firstNormal === void 0) { firstNormal = null; }
  7577. for (var p = 0; p < path.length; p++) {
  7578. this._curve[p].x = path[p].x;
  7579. this._curve[p].y = path[p].y;
  7580. this._curve[p].z = path[p].z;
  7581. }
  7582. this._compute(firstNormal);
  7583. return this;
  7584. };
  7585. // private function compute() : computes tangents, normals and binormals
  7586. Path3D.prototype._compute = function (firstNormal) {
  7587. var l = this._curve.length;
  7588. // first and last tangents
  7589. this._tangents[0] = this._getFirstNonNullVector(0);
  7590. if (!this._raw) {
  7591. this._tangents[0].normalize();
  7592. }
  7593. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7594. if (!this._raw) {
  7595. this._tangents[l - 1].normalize();
  7596. }
  7597. // normals and binormals at first point : arbitrary vector with _normalVector()
  7598. var tg0 = this._tangents[0];
  7599. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7600. this._normals[0] = pp0;
  7601. if (!this._raw) {
  7602. this._normals[0].normalize();
  7603. }
  7604. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7605. if (!this._raw) {
  7606. this._binormals[0].normalize();
  7607. }
  7608. this._distances[0] = 0.0;
  7609. // normals and binormals : next points
  7610. var prev; // previous vector (segment)
  7611. var cur; // current vector (segment)
  7612. var curTang; // current tangent
  7613. // previous normal
  7614. var prevBinor; // previous binormal
  7615. for (var i = 1; i < l; i++) {
  7616. // tangents
  7617. prev = this._getLastNonNullVector(i);
  7618. if (i < l - 1) {
  7619. cur = this._getFirstNonNullVector(i);
  7620. this._tangents[i] = prev.add(cur);
  7621. this._tangents[i].normalize();
  7622. }
  7623. this._distances[i] = this._distances[i - 1] + prev.length();
  7624. // normals and binormals
  7625. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7626. curTang = this._tangents[i];
  7627. prevBinor = this._binormals[i - 1];
  7628. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7629. if (!this._raw) {
  7630. this._normals[i].normalize();
  7631. }
  7632. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7633. if (!this._raw) {
  7634. this._binormals[i].normalize();
  7635. }
  7636. }
  7637. };
  7638. // private function getFirstNonNullVector(index)
  7639. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7640. Path3D.prototype._getFirstNonNullVector = function (index) {
  7641. var i = 1;
  7642. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7643. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7644. i++;
  7645. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7646. }
  7647. return nNVector;
  7648. };
  7649. // private function getLastNonNullVector(index)
  7650. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7651. Path3D.prototype._getLastNonNullVector = function (index) {
  7652. var i = 1;
  7653. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7654. while (nLVector.length() === 0 && index > i + 1) {
  7655. i++;
  7656. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7657. }
  7658. return nLVector;
  7659. };
  7660. // private function normalVector(v0, vt, va) :
  7661. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7662. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7663. Path3D.prototype._normalVector = function (v0, vt, va) {
  7664. var normal0;
  7665. var tgl = vt.length();
  7666. if (tgl === 0.0) {
  7667. tgl = 1.0;
  7668. }
  7669. if (va === undefined || va === null) {
  7670. var point;
  7671. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7672. point = new Vector3(0.0, -1.0, 0.0);
  7673. }
  7674. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7675. point = new Vector3(1.0, 0.0, 0.0);
  7676. }
  7677. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7678. point = new Vector3(0.0, 0.0, 1.0);
  7679. }
  7680. else {
  7681. point = Vector3.Zero();
  7682. }
  7683. normal0 = Vector3.Cross(vt, point);
  7684. }
  7685. else {
  7686. normal0 = Vector3.Cross(vt, va);
  7687. Vector3.CrossToRef(normal0, vt, normal0);
  7688. }
  7689. normal0.normalize();
  7690. return normal0;
  7691. };
  7692. return Path3D;
  7693. }());
  7694. BABYLON.Path3D = Path3D;
  7695. /**
  7696. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7697. * A Curve3 is designed from a series of successive Vector3.
  7698. * @see https://doc.babylonjs.com/how_to/how_to_use_curve3
  7699. */
  7700. var Curve3 = /** @class */ (function () {
  7701. /**
  7702. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7703. * A Curve3 is designed from a series of successive Vector3.
  7704. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7705. * @param points points which make up the curve
  7706. */
  7707. function Curve3(points) {
  7708. this._length = 0.0;
  7709. this._points = points;
  7710. this._length = this._computeLength(points);
  7711. }
  7712. /**
  7713. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7714. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7715. * @param v1 (Vector3) the control point
  7716. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7717. * @param nbPoints (integer) the wanted number of points in the curve
  7718. * @returns the created Curve3
  7719. */
  7720. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7721. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7722. var bez = new Array();
  7723. var equation = function (t, val0, val1, val2) {
  7724. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7725. return res;
  7726. };
  7727. for (var i = 0; i <= nbPoints; i++) {
  7728. 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)));
  7729. }
  7730. return new Curve3(bez);
  7731. };
  7732. /**
  7733. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7734. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7735. * @param v1 (Vector3) the first control point
  7736. * @param v2 (Vector3) the second control point
  7737. * @param v3 (Vector3) the end point of the Cubic Bezier
  7738. * @param nbPoints (integer) the wanted number of points in the curve
  7739. * @returns the created Curve3
  7740. */
  7741. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7742. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7743. var bez = new Array();
  7744. var equation = function (t, val0, val1, val2, val3) {
  7745. 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;
  7746. return res;
  7747. };
  7748. for (var i = 0; i <= nbPoints; i++) {
  7749. 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)));
  7750. }
  7751. return new Curve3(bez);
  7752. };
  7753. /**
  7754. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7755. * @param p1 (Vector3) the origin point of the Hermite Spline
  7756. * @param t1 (Vector3) the tangent vector at the origin point
  7757. * @param p2 (Vector3) the end point of the Hermite Spline
  7758. * @param t2 (Vector3) the tangent vector at the end point
  7759. * @param nbPoints (integer) the wanted number of points in the curve
  7760. * @returns the created Curve3
  7761. */
  7762. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7763. var hermite = new Array();
  7764. var step = 1.0 / nbPoints;
  7765. for (var i = 0; i <= nbPoints; i++) {
  7766. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7767. }
  7768. return new Curve3(hermite);
  7769. };
  7770. /**
  7771. * Returns a Curve3 object along a CatmullRom Spline curve :
  7772. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  7773. * @param nbPoints (integer) the wanted number of points between each curve control points
  7774. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  7775. * @returns the created Curve3
  7776. */
  7777. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  7778. var catmullRom = new Array();
  7779. var step = 1.0 / nbPoints;
  7780. var amount = 0.0;
  7781. if (closed) {
  7782. var pointsCount = points.length;
  7783. for (var i = 0; i < pointsCount; i++) {
  7784. amount = 0;
  7785. for (var c = 0; c < nbPoints; c++) {
  7786. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  7787. amount += step;
  7788. }
  7789. }
  7790. catmullRom.push(catmullRom[0]);
  7791. }
  7792. else {
  7793. var totalPoints = new Array();
  7794. totalPoints.push(points[0].clone());
  7795. Array.prototype.push.apply(totalPoints, points);
  7796. totalPoints.push(points[points.length - 1].clone());
  7797. for (var i = 0; i < totalPoints.length - 3; i++) {
  7798. amount = 0;
  7799. for (var c = 0; c < nbPoints; c++) {
  7800. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7801. amount += step;
  7802. }
  7803. }
  7804. i--;
  7805. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7806. }
  7807. return new Curve3(catmullRom);
  7808. };
  7809. /**
  7810. * @returns the Curve3 stored array of successive Vector3
  7811. */
  7812. Curve3.prototype.getPoints = function () {
  7813. return this._points;
  7814. };
  7815. /**
  7816. * @returns the computed length (float) of the curve.
  7817. */
  7818. Curve3.prototype.length = function () {
  7819. return this._length;
  7820. };
  7821. /**
  7822. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7823. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7824. * curveA and curveB keep unchanged.
  7825. * @param curve the curve to continue from this curve
  7826. * @returns the newly constructed curve
  7827. */
  7828. Curve3.prototype.continue = function (curve) {
  7829. var lastPoint = this._points[this._points.length - 1];
  7830. var continuedPoints = this._points.slice();
  7831. var curvePoints = curve.getPoints();
  7832. for (var i = 1; i < curvePoints.length; i++) {
  7833. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7834. }
  7835. var continuedCurve = new Curve3(continuedPoints);
  7836. return continuedCurve;
  7837. };
  7838. Curve3.prototype._computeLength = function (path) {
  7839. var l = 0;
  7840. for (var i = 1; i < path.length; i++) {
  7841. l += (path[i].subtract(path[i - 1])).length();
  7842. }
  7843. return l;
  7844. };
  7845. return Curve3;
  7846. }());
  7847. BABYLON.Curve3 = Curve3;
  7848. // Vertex formats
  7849. /**
  7850. * Contains position and normal vectors for a vertex
  7851. */
  7852. var PositionNormalVertex = /** @class */ (function () {
  7853. /**
  7854. * Creates a PositionNormalVertex
  7855. * @param position the position of the vertex (defaut: 0,0,0)
  7856. * @param normal the normal of the vertex (defaut: 0,1,0)
  7857. */
  7858. function PositionNormalVertex(
  7859. /** the position of the vertex (defaut: 0,0,0) */
  7860. position,
  7861. /** the normal of the vertex (defaut: 0,1,0) */
  7862. normal) {
  7863. if (position === void 0) { position = Vector3.Zero(); }
  7864. if (normal === void 0) { normal = Vector3.Up(); }
  7865. this.position = position;
  7866. this.normal = normal;
  7867. }
  7868. /**
  7869. * Clones the PositionNormalVertex
  7870. * @returns the cloned PositionNormalVertex
  7871. */
  7872. PositionNormalVertex.prototype.clone = function () {
  7873. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7874. };
  7875. return PositionNormalVertex;
  7876. }());
  7877. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7878. /**
  7879. * Contains position, normal and uv vectors for a vertex
  7880. */
  7881. var PositionNormalTextureVertex = /** @class */ (function () {
  7882. /**
  7883. * Creates a PositionNormalTextureVertex
  7884. * @param position the position of the vertex (defaut: 0,0,0)
  7885. * @param normal the normal of the vertex (defaut: 0,1,0)
  7886. * @param uv the uv of the vertex (default: 0,0)
  7887. */
  7888. function PositionNormalTextureVertex(
  7889. /** the position of the vertex (defaut: 0,0,0) */
  7890. position,
  7891. /** the normal of the vertex (defaut: 0,1,0) */
  7892. normal,
  7893. /** the uv of the vertex (default: 0,0) */
  7894. uv) {
  7895. if (position === void 0) { position = Vector3.Zero(); }
  7896. if (normal === void 0) { normal = Vector3.Up(); }
  7897. if (uv === void 0) { uv = Vector2.Zero(); }
  7898. this.position = position;
  7899. this.normal = normal;
  7900. this.uv = uv;
  7901. }
  7902. /**
  7903. * Clones the PositionNormalTextureVertex
  7904. * @returns the cloned PositionNormalTextureVertex
  7905. */
  7906. PositionNormalTextureVertex.prototype.clone = function () {
  7907. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7908. };
  7909. return PositionNormalTextureVertex;
  7910. }());
  7911. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7912. // Temporary pre-allocated objects for engine internal use
  7913. // usage in any internal function :
  7914. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7915. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7916. /**
  7917. * @hidden
  7918. */
  7919. var Tmp = /** @class */ (function () {
  7920. function Tmp() {
  7921. }
  7922. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7923. Tmp.Color4 = [new Color4(0, 0, 0, 0), new Color4(0, 0, 0, 0)];
  7924. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7925. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7926. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7927. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7928. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7929. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7930. Matrix.Zero(), Matrix.Zero(),
  7931. Matrix.Zero(), Matrix.Zero(),
  7932. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7933. return Tmp;
  7934. }());
  7935. BABYLON.Tmp = Tmp;
  7936. /**
  7937. * @hidden
  7938. * Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7939. */
  7940. var MathTmp = /** @class */ (function () {
  7941. function MathTmp() {
  7942. }
  7943. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7944. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7945. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7946. return MathTmp;
  7947. }());
  7948. })(BABYLON || (BABYLON = {}));
  7949. //# sourceMappingURL=babylon.math.js.map
  7950. var BABYLON;
  7951. (function (BABYLON) {
  7952. /**
  7953. * Scalar computation library
  7954. */
  7955. var Scalar = /** @class */ (function () {
  7956. function Scalar() {
  7957. }
  7958. /**
  7959. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7960. * @param a number
  7961. * @param b number
  7962. * @param epsilon (default = 1.401298E-45)
  7963. * @returns true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7964. */
  7965. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7966. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7967. var num = a - b;
  7968. return -epsilon <= num && num <= epsilon;
  7969. };
  7970. /**
  7971. * Returns a string : the upper case translation of the number i to hexadecimal.
  7972. * @param i number
  7973. * @returns the upper case translation of the number i to hexadecimal.
  7974. */
  7975. Scalar.ToHex = function (i) {
  7976. var str = i.toString(16);
  7977. if (i <= 15) {
  7978. return ("0" + str).toUpperCase();
  7979. }
  7980. return str.toUpperCase();
  7981. };
  7982. /**
  7983. * Returns -1 if value is negative and +1 is value is positive.
  7984. * @param value the value
  7985. * @returns the value itself if it's equal to zero.
  7986. */
  7987. Scalar.Sign = function (value) {
  7988. value = +value; // convert to a number
  7989. if (value === 0 || isNaN(value))
  7990. return value;
  7991. return value > 0 ? 1 : -1;
  7992. };
  7993. /**
  7994. * Returns the value itself if it's between min and max.
  7995. * Returns min if the value is lower than min.
  7996. * Returns max if the value is greater than max.
  7997. * @param value the value to clmap
  7998. * @param min the min value to clamp to (default: 0)
  7999. * @param max the max value to clamp to (default: 1)
  8000. * @returns the clamped value
  8001. */
  8002. Scalar.Clamp = function (value, min, max) {
  8003. if (min === void 0) { min = 0; }
  8004. if (max === void 0) { max = 1; }
  8005. return Math.min(max, Math.max(min, value));
  8006. };
  8007. /**
  8008. * the log2 of value.
  8009. * @param value the value to compute log2 of
  8010. * @returns the log2 of value.
  8011. */
  8012. Scalar.Log2 = function (value) {
  8013. return Math.log(value) * Math.LOG2E;
  8014. };
  8015. /**
  8016. * Loops the value, so that it is never larger than length and never smaller than 0.
  8017. *
  8018. * This is similar to the modulo operator but it works with floating point numbers.
  8019. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  8020. * With t = 5 and length = 2.5, the result would be 0.0.
  8021. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  8022. * @param value the value
  8023. * @param length the length
  8024. * @returns the looped value
  8025. */
  8026. Scalar.Repeat = function (value, length) {
  8027. return value - Math.floor(value / length) * length;
  8028. };
  8029. /**
  8030. * Normalize the value between 0.0 and 1.0 using min and max values
  8031. * @param value value to normalize
  8032. * @param min max to normalize between
  8033. * @param max min to normalize between
  8034. * @returns the normalized value
  8035. */
  8036. Scalar.Normalize = function (value, min, max) {
  8037. return (value - min) / (max - min);
  8038. };
  8039. /**
  8040. * Denormalize the value from 0.0 and 1.0 using min and max values
  8041. * @param normalized value to denormalize
  8042. * @param min max to denormalize between
  8043. * @param max min to denormalize between
  8044. * @returns the denormalized value
  8045. */
  8046. Scalar.Denormalize = function (normalized, min, max) {
  8047. return (normalized * (max - min) + min);
  8048. };
  8049. /**
  8050. * Calculates the shortest difference between two given angles given in degrees.
  8051. * @param current current angle in degrees
  8052. * @param target target angle in degrees
  8053. * @returns the delta
  8054. */
  8055. Scalar.DeltaAngle = function (current, target) {
  8056. var num = Scalar.Repeat(target - current, 360.0);
  8057. if (num > 180.0) {
  8058. num -= 360.0;
  8059. }
  8060. return num;
  8061. };
  8062. /**
  8063. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  8064. * @param tx value
  8065. * @param length length
  8066. * @returns The returned value will move back and forth between 0 and length
  8067. */
  8068. Scalar.PingPong = function (tx, length) {
  8069. var t = Scalar.Repeat(tx, length * 2.0);
  8070. return length - Math.abs(t - length);
  8071. };
  8072. /**
  8073. * Interpolates between min and max with smoothing at the limits.
  8074. *
  8075. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  8076. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  8077. * @param from from
  8078. * @param to to
  8079. * @param tx value
  8080. * @returns the smooth stepped value
  8081. */
  8082. Scalar.SmoothStep = function (from, to, tx) {
  8083. var t = Scalar.Clamp(tx);
  8084. t = -2.0 * t * t * t + 3.0 * t * t;
  8085. return to * t + from * (1.0 - t);
  8086. };
  8087. /**
  8088. * Moves a value current towards target.
  8089. *
  8090. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  8091. * Negative values of maxDelta pushes the value away from target.
  8092. * @param current current value
  8093. * @param target target value
  8094. * @param maxDelta max distance to move
  8095. * @returns resulting value
  8096. */
  8097. Scalar.MoveTowards = function (current, target, maxDelta) {
  8098. var result = 0;
  8099. if (Math.abs(target - current) <= maxDelta) {
  8100. result = target;
  8101. }
  8102. else {
  8103. result = current + Scalar.Sign(target - current) * maxDelta;
  8104. }
  8105. return result;
  8106. };
  8107. /**
  8108. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  8109. *
  8110. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  8111. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  8112. * @param current current value
  8113. * @param target target value
  8114. * @param maxDelta max distance to move
  8115. * @returns resulting angle
  8116. */
  8117. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  8118. var num = Scalar.DeltaAngle(current, target);
  8119. var result = 0;
  8120. if (-maxDelta < num && num < maxDelta) {
  8121. result = target;
  8122. }
  8123. else {
  8124. target = current + num;
  8125. result = Scalar.MoveTowards(current, target, maxDelta);
  8126. }
  8127. return result;
  8128. };
  8129. /**
  8130. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  8131. * @param start start value
  8132. * @param end target value
  8133. * @param amount amount to lerp between
  8134. * @returns the lerped value
  8135. */
  8136. Scalar.Lerp = function (start, end, amount) {
  8137. return start + ((end - start) * amount);
  8138. };
  8139. /**
  8140. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  8141. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  8142. * @param start start value
  8143. * @param end target value
  8144. * @param amount amount to lerp between
  8145. * @returns the lerped value
  8146. */
  8147. Scalar.LerpAngle = function (start, end, amount) {
  8148. var num = Scalar.Repeat(end - start, 360.0);
  8149. if (num > 180.0) {
  8150. num -= 360.0;
  8151. }
  8152. return start + num * Scalar.Clamp(amount);
  8153. };
  8154. /**
  8155. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  8156. * @param a start value
  8157. * @param b target value
  8158. * @param value value between a and b
  8159. * @returns the inverseLerp value
  8160. */
  8161. Scalar.InverseLerp = function (a, b, value) {
  8162. var result = 0;
  8163. if (a != b) {
  8164. result = Scalar.Clamp((value - a) / (b - a));
  8165. }
  8166. else {
  8167. result = 0.0;
  8168. }
  8169. return result;
  8170. };
  8171. /**
  8172. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  8173. * @see http://mathworld.wolfram.com/HermitePolynomial.html
  8174. * @param value1 spline value
  8175. * @param tangent1 spline value
  8176. * @param value2 spline value
  8177. * @param tangent2 spline value
  8178. * @param amount input value
  8179. * @returns hermite result
  8180. */
  8181. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  8182. var squared = amount * amount;
  8183. var cubed = amount * squared;
  8184. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  8185. var part2 = (-2.0 * cubed) + (3.0 * squared);
  8186. var part3 = (cubed - (2.0 * squared)) + amount;
  8187. var part4 = cubed - squared;
  8188. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  8189. };
  8190. /**
  8191. * Returns a random float number between and min and max values
  8192. * @param min min value of random
  8193. * @param max max value of random
  8194. * @returns random value
  8195. */
  8196. Scalar.RandomRange = function (min, max) {
  8197. if (min === max)
  8198. return min;
  8199. return ((Math.random() * (max - min)) + min);
  8200. };
  8201. /**
  8202. * This function returns percentage of a number in a given range.
  8203. *
  8204. * RangeToPercent(40,20,60) will return 0.5 (50%)
  8205. * RangeToPercent(34,0,100) will return 0.34 (34%)
  8206. * @param number to convert to percentage
  8207. * @param min min range
  8208. * @param max max range
  8209. * @returns the percentage
  8210. */
  8211. Scalar.RangeToPercent = function (number, min, max) {
  8212. return ((number - min) / (max - min));
  8213. };
  8214. /**
  8215. * This function returns number that corresponds to the percentage in a given range.
  8216. *
  8217. * PercentToRange(0.34,0,100) will return 34.
  8218. * @param percent to convert to number
  8219. * @param min min range
  8220. * @param max max range
  8221. * @returns the number
  8222. */
  8223. Scalar.PercentToRange = function (percent, min, max) {
  8224. return ((max - min) * percent + min);
  8225. };
  8226. /**
  8227. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  8228. * @param angle The angle to normalize in radian.
  8229. * @return The converted angle.
  8230. */
  8231. Scalar.NormalizeRadians = function (angle) {
  8232. // More precise but slower version kept for reference.
  8233. // angle = angle % Tools.TwoPi;
  8234. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  8235. //if (angle > Math.PI) {
  8236. // angle -= Tools.TwoPi;
  8237. //}
  8238. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  8239. return angle;
  8240. };
  8241. /**
  8242. * Two pi constants convenient for computation.
  8243. */
  8244. Scalar.TwoPi = Math.PI * 2;
  8245. return Scalar;
  8246. }());
  8247. BABYLON.Scalar = Scalar;
  8248. })(BABYLON || (BABYLON = {}));
  8249. //# sourceMappingURL=babylon.math.scalar.js.map
  8250. //# sourceMappingURL=babylon.mixins.js.map
  8251. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  8252. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  8253. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  8254. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  8255. //# sourceMappingURL=babylon.webgl2.js.map
  8256. var BABYLON;
  8257. (function (BABYLON) {
  8258. var __decoratorInitialStore = {};
  8259. var __mergedStore = {};
  8260. var _copySource = function (creationFunction, source, instanciate) {
  8261. var destination = creationFunction();
  8262. // Tags
  8263. if (BABYLON.Tags) {
  8264. BABYLON.Tags.AddTagsTo(destination, source.tags);
  8265. }
  8266. var classStore = getMergedStore(destination);
  8267. // Properties
  8268. for (var property in classStore) {
  8269. var propertyDescriptor = classStore[property];
  8270. var sourceProperty = source[property];
  8271. var propertyType = propertyDescriptor.type;
  8272. if (sourceProperty !== undefined && sourceProperty !== null) {
  8273. switch (propertyType) {
  8274. case 0: // Value
  8275. case 6: // Mesh reference
  8276. case 11: // Camera reference
  8277. destination[property] = sourceProperty;
  8278. break;
  8279. case 1: // Texture
  8280. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  8281. break;
  8282. case 2: // Color3
  8283. case 3: // FresnelParameters
  8284. case 4: // Vector2
  8285. case 5: // Vector3
  8286. case 7: // Color Curves
  8287. case 10: // Quaternion
  8288. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  8289. break;
  8290. }
  8291. }
  8292. }
  8293. return destination;
  8294. };
  8295. function getDirectStore(target) {
  8296. var classKey = target.getClassName();
  8297. if (!__decoratorInitialStore[classKey]) {
  8298. __decoratorInitialStore[classKey] = {};
  8299. }
  8300. return __decoratorInitialStore[classKey];
  8301. }
  8302. /**
  8303. * Return the list of properties flagged as serializable
  8304. * @param target: host object
  8305. */
  8306. function getMergedStore(target) {
  8307. var classKey = target.getClassName();
  8308. if (__mergedStore[classKey]) {
  8309. return __mergedStore[classKey];
  8310. }
  8311. __mergedStore[classKey] = {};
  8312. var store = __mergedStore[classKey];
  8313. var currentTarget = target;
  8314. var currentKey = classKey;
  8315. while (currentKey) {
  8316. var initialStore = __decoratorInitialStore[currentKey];
  8317. for (var property in initialStore) {
  8318. store[property] = initialStore[property];
  8319. }
  8320. var parent_1 = void 0;
  8321. var done = false;
  8322. do {
  8323. parent_1 = Object.getPrototypeOf(currentTarget);
  8324. if (!parent_1.getClassName) {
  8325. done = true;
  8326. break;
  8327. }
  8328. if (parent_1.getClassName() !== currentKey) {
  8329. break;
  8330. }
  8331. currentTarget = parent_1;
  8332. } while (parent_1);
  8333. if (done) {
  8334. break;
  8335. }
  8336. currentKey = parent_1.getClassName();
  8337. currentTarget = parent_1;
  8338. }
  8339. return store;
  8340. }
  8341. function generateSerializableMember(type, sourceName) {
  8342. return function (target, propertyKey) {
  8343. var classStore = getDirectStore(target);
  8344. if (!classStore[propertyKey]) {
  8345. classStore[propertyKey] = { type: type, sourceName: sourceName };
  8346. }
  8347. };
  8348. }
  8349. function generateExpandMember(setCallback, targetKey) {
  8350. if (targetKey === void 0) { targetKey = null; }
  8351. return function (target, propertyKey) {
  8352. var key = targetKey || ("_" + propertyKey);
  8353. Object.defineProperty(target, propertyKey, {
  8354. get: function () {
  8355. return this[key];
  8356. },
  8357. set: function (value) {
  8358. if (this[key] === value) {
  8359. return;
  8360. }
  8361. this[key] = value;
  8362. target[setCallback].apply(this);
  8363. },
  8364. enumerable: true,
  8365. configurable: true
  8366. });
  8367. };
  8368. }
  8369. function expandToProperty(callback, targetKey) {
  8370. if (targetKey === void 0) { targetKey = null; }
  8371. return generateExpandMember(callback, targetKey);
  8372. }
  8373. BABYLON.expandToProperty = expandToProperty;
  8374. function serialize(sourceName) {
  8375. return generateSerializableMember(0, sourceName); // value member
  8376. }
  8377. BABYLON.serialize = serialize;
  8378. function serializeAsTexture(sourceName) {
  8379. return generateSerializableMember(1, sourceName); // texture member
  8380. }
  8381. BABYLON.serializeAsTexture = serializeAsTexture;
  8382. function serializeAsColor3(sourceName) {
  8383. return generateSerializableMember(2, sourceName); // color3 member
  8384. }
  8385. BABYLON.serializeAsColor3 = serializeAsColor3;
  8386. function serializeAsFresnelParameters(sourceName) {
  8387. return generateSerializableMember(3, sourceName); // fresnel parameters member
  8388. }
  8389. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  8390. function serializeAsVector2(sourceName) {
  8391. return generateSerializableMember(4, sourceName); // vector2 member
  8392. }
  8393. BABYLON.serializeAsVector2 = serializeAsVector2;
  8394. function serializeAsVector3(sourceName) {
  8395. return generateSerializableMember(5, sourceName); // vector3 member
  8396. }
  8397. BABYLON.serializeAsVector3 = serializeAsVector3;
  8398. function serializeAsMeshReference(sourceName) {
  8399. return generateSerializableMember(6, sourceName); // mesh reference member
  8400. }
  8401. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  8402. function serializeAsColorCurves(sourceName) {
  8403. return generateSerializableMember(7, sourceName); // color curves
  8404. }
  8405. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  8406. function serializeAsColor4(sourceName) {
  8407. return generateSerializableMember(8, sourceName); // color 4
  8408. }
  8409. BABYLON.serializeAsColor4 = serializeAsColor4;
  8410. function serializeAsImageProcessingConfiguration(sourceName) {
  8411. return generateSerializableMember(9, sourceName); // image processing
  8412. }
  8413. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  8414. function serializeAsQuaternion(sourceName) {
  8415. return generateSerializableMember(10, sourceName); // quaternion member
  8416. }
  8417. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  8418. /**
  8419. * Decorator used to define property that can be serialized as reference to a camera
  8420. * @param sourceName defines the name of the property to decorate
  8421. */
  8422. function serializeAsCameraReference(sourceName) {
  8423. return generateSerializableMember(11, sourceName); // camera reference member
  8424. }
  8425. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  8426. /**
  8427. * Class used to help serialization objects
  8428. */
  8429. var SerializationHelper = /** @class */ (function () {
  8430. function SerializationHelper() {
  8431. }
  8432. /**
  8433. * Static function used to serialized a specific entity
  8434. * @param entity defines the entity to serialize
  8435. * @param serializationObject defines the optional target obecjt where serialization data will be stored
  8436. * @returns a JSON compatible object representing the serialization of the entity
  8437. */
  8438. SerializationHelper.Serialize = function (entity, serializationObject) {
  8439. if (!serializationObject) {
  8440. serializationObject = {};
  8441. }
  8442. // Tags
  8443. if (BABYLON.Tags) {
  8444. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  8445. }
  8446. var serializedProperties = getMergedStore(entity);
  8447. // Properties
  8448. for (var property in serializedProperties) {
  8449. var propertyDescriptor = serializedProperties[property];
  8450. var targetPropertyName = propertyDescriptor.sourceName || property;
  8451. var propertyType = propertyDescriptor.type;
  8452. var sourceProperty = entity[property];
  8453. if (sourceProperty !== undefined && sourceProperty !== null) {
  8454. switch (propertyType) {
  8455. case 0: // Value
  8456. serializationObject[targetPropertyName] = sourceProperty;
  8457. break;
  8458. case 1: // Texture
  8459. serializationObject[targetPropertyName] = sourceProperty.serialize();
  8460. break;
  8461. case 2: // Color3
  8462. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8463. break;
  8464. case 3: // FresnelParameters
  8465. serializationObject[targetPropertyName] = sourceProperty.serialize();
  8466. break;
  8467. case 4: // Vector2
  8468. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8469. break;
  8470. case 5: // Vector3
  8471. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8472. break;
  8473. case 6: // Mesh reference
  8474. serializationObject[targetPropertyName] = sourceProperty.id;
  8475. break;
  8476. case 7: // Color Curves
  8477. serializationObject[targetPropertyName] = sourceProperty.serialize();
  8478. break;
  8479. case 8: // Color 4
  8480. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8481. break;
  8482. case 9: // Image Processing
  8483. serializationObject[targetPropertyName] = sourceProperty.serialize();
  8484. break;
  8485. case 10: // Quaternion
  8486. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8487. break;
  8488. case 11: // Camera reference
  8489. serializationObject[targetPropertyName] = sourceProperty.id;
  8490. break;
  8491. }
  8492. }
  8493. }
  8494. return serializationObject;
  8495. };
  8496. /**
  8497. * Creates a new entity from a serialization data object
  8498. * @param creationFunction defines a function used to instanciated the new entity
  8499. * @param source defines the source serialization data
  8500. * @param scene defines the hosting scene
  8501. * @param rootUrl defines the root url for resources
  8502. * @returns a new entity
  8503. */
  8504. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  8505. if (rootUrl === void 0) { rootUrl = null; }
  8506. var destination = creationFunction();
  8507. if (!rootUrl) {
  8508. rootUrl = "";
  8509. }
  8510. // Tags
  8511. if (BABYLON.Tags) {
  8512. BABYLON.Tags.AddTagsTo(destination, source.tags);
  8513. }
  8514. var classStore = getMergedStore(destination);
  8515. // Properties
  8516. for (var property in classStore) {
  8517. var propertyDescriptor = classStore[property];
  8518. var sourceProperty = source[propertyDescriptor.sourceName || property];
  8519. var propertyType = propertyDescriptor.type;
  8520. if (sourceProperty !== undefined && sourceProperty !== null) {
  8521. var dest = destination;
  8522. switch (propertyType) {
  8523. case 0: // Value
  8524. dest[property] = sourceProperty;
  8525. break;
  8526. case 1: // Texture
  8527. if (scene) {
  8528. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  8529. }
  8530. break;
  8531. case 2: // Color3
  8532. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  8533. break;
  8534. case 3: // FresnelParameters
  8535. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  8536. break;
  8537. case 4: // Vector2
  8538. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  8539. break;
  8540. case 5: // Vector3
  8541. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  8542. break;
  8543. case 6: // Mesh reference
  8544. if (scene) {
  8545. dest[property] = scene.getLastMeshByID(sourceProperty);
  8546. }
  8547. break;
  8548. case 7: // Color Curves
  8549. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  8550. break;
  8551. case 8: // Color 4
  8552. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  8553. break;
  8554. case 9: // Image Processing
  8555. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  8556. break;
  8557. case 10: // Quaternion
  8558. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  8559. break;
  8560. case 11: // Camera reference
  8561. if (scene) {
  8562. dest[property] = scene.getCameraByID(sourceProperty);
  8563. }
  8564. break;
  8565. }
  8566. }
  8567. }
  8568. return destination;
  8569. };
  8570. /**
  8571. * Clones an object
  8572. * @param creationFunction defines the function used to instanciate the new object
  8573. * @param source defines the source object
  8574. * @returns the cloned object
  8575. */
  8576. SerializationHelper.Clone = function (creationFunction, source) {
  8577. return _copySource(creationFunction, source, false);
  8578. };
  8579. /**
  8580. * Instanciates a new object based on a source one (some data will be shared between both object)
  8581. * @param creationFunction defines the function used to instanciate the new object
  8582. * @param source defines the source object
  8583. * @returns the new object
  8584. */
  8585. SerializationHelper.Instanciate = function (creationFunction, source) {
  8586. return _copySource(creationFunction, source, true);
  8587. };
  8588. return SerializationHelper;
  8589. }());
  8590. BABYLON.SerializationHelper = SerializationHelper;
  8591. })(BABYLON || (BABYLON = {}));
  8592. //# sourceMappingURL=babylon.decorators.js.map
  8593. var BABYLON;
  8594. (function (BABYLON) {
  8595. /**
  8596. * Wrapper class for promise with external resolve and reject.
  8597. */
  8598. var Deferred = /** @class */ (function () {
  8599. /**
  8600. * Constructor for this deferred object.
  8601. */
  8602. function Deferred() {
  8603. var _this = this;
  8604. this.promise = new Promise(function (resolve, reject) {
  8605. _this._resolve = resolve;
  8606. _this._reject = reject;
  8607. });
  8608. }
  8609. Object.defineProperty(Deferred.prototype, "resolve", {
  8610. /**
  8611. * The resolve method of the promise associated with this deferred object.
  8612. */
  8613. get: function () {
  8614. return this._resolve;
  8615. },
  8616. enumerable: true,
  8617. configurable: true
  8618. });
  8619. Object.defineProperty(Deferred.prototype, "reject", {
  8620. /**
  8621. * The reject method of the promise associated with this deferred object.
  8622. */
  8623. get: function () {
  8624. return this._reject;
  8625. },
  8626. enumerable: true,
  8627. configurable: true
  8628. });
  8629. return Deferred;
  8630. }());
  8631. BABYLON.Deferred = Deferred;
  8632. })(BABYLON || (BABYLON = {}));
  8633. //# sourceMappingURL=babylon.deferred.js.map
  8634. var BABYLON;
  8635. (function (BABYLON) {
  8636. /**
  8637. * A class serves as a medium between the observable and its observers
  8638. */
  8639. var EventState = /** @class */ (function () {
  8640. /**
  8641. * Create a new EventState
  8642. * @param mask defines the mask associated with this state
  8643. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8644. * @param target defines the original target of the state
  8645. * @param currentTarget defines the current target of the state
  8646. */
  8647. function EventState(mask, skipNextObservers, target, currentTarget) {
  8648. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8649. this.initalize(mask, skipNextObservers, target, currentTarget);
  8650. }
  8651. /**
  8652. * Initialize the current event state
  8653. * @param mask defines the mask associated with this state
  8654. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8655. * @param target defines the original target of the state
  8656. * @param currentTarget defines the current target of the state
  8657. * @returns the current event state
  8658. */
  8659. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8660. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8661. this.mask = mask;
  8662. this.skipNextObservers = skipNextObservers;
  8663. this.target = target;
  8664. this.currentTarget = currentTarget;
  8665. return this;
  8666. };
  8667. return EventState;
  8668. }());
  8669. BABYLON.EventState = EventState;
  8670. /**
  8671. * Represent an Observer registered to a given Observable object.
  8672. */
  8673. var Observer = /** @class */ (function () {
  8674. /**
  8675. * Creates a new observer
  8676. * @param callback defines the callback to call when the observer is notified
  8677. * @param mask defines the mask of the observer (used to filter notifications)
  8678. * @param scope defines the current scope used to restore the JS context
  8679. */
  8680. function Observer(
  8681. /**
  8682. * Defines the callback to call when the observer is notified
  8683. */
  8684. callback,
  8685. /**
  8686. * Defines the mask of the observer (used to filter notifications)
  8687. */
  8688. mask,
  8689. /**
  8690. * Defines the current scope used to restore the JS context
  8691. */
  8692. scope) {
  8693. if (scope === void 0) { scope = null; }
  8694. this.callback = callback;
  8695. this.mask = mask;
  8696. this.scope = scope;
  8697. /** @hidden */
  8698. this._willBeUnregistered = false;
  8699. /**
  8700. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8701. */
  8702. this.unregisterOnNextCall = false;
  8703. }
  8704. return Observer;
  8705. }());
  8706. BABYLON.Observer = Observer;
  8707. /**
  8708. * Represent a list of observers registered to multiple Observables object.
  8709. */
  8710. var MultiObserver = /** @class */ (function () {
  8711. function MultiObserver() {
  8712. }
  8713. /**
  8714. * Release associated resources
  8715. */
  8716. MultiObserver.prototype.dispose = function () {
  8717. if (this._observers && this._observables) {
  8718. for (var index = 0; index < this._observers.length; index++) {
  8719. this._observables[index].remove(this._observers[index]);
  8720. }
  8721. }
  8722. this._observers = null;
  8723. this._observables = null;
  8724. };
  8725. /**
  8726. * Raise a callback when one of the observable will notify
  8727. * @param observables defines a list of observables to watch
  8728. * @param callback defines the callback to call on notification
  8729. * @param mask defines the mask used to filter notifications
  8730. * @param scope defines the current scope used to restore the JS context
  8731. * @returns the new MultiObserver
  8732. */
  8733. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8734. if (mask === void 0) { mask = -1; }
  8735. if (scope === void 0) { scope = null; }
  8736. var result = new MultiObserver();
  8737. result._observers = new Array();
  8738. result._observables = observables;
  8739. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8740. var observable = observables_1[_i];
  8741. var observer = observable.add(callback, mask, false, scope);
  8742. if (observer) {
  8743. result._observers.push(observer);
  8744. }
  8745. }
  8746. return result;
  8747. };
  8748. return MultiObserver;
  8749. }());
  8750. BABYLON.MultiObserver = MultiObserver;
  8751. /**
  8752. * The Observable class is a simple implementation of the Observable pattern.
  8753. *
  8754. * 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.
  8755. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8756. * 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).
  8757. * 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.
  8758. */
  8759. var Observable = /** @class */ (function () {
  8760. /**
  8761. * Creates a new observable
  8762. * @param onObserverAdded defines a callback to call when a new observer is added
  8763. */
  8764. function Observable(onObserverAdded) {
  8765. this._observers = new Array();
  8766. this._eventState = new EventState(0);
  8767. if (onObserverAdded) {
  8768. this._onObserverAdded = onObserverAdded;
  8769. }
  8770. }
  8771. /**
  8772. * Create a new Observer with the specified callback
  8773. * @param callback the callback that will be executed for that Observer
  8774. * @param mask the mask used to filter observers
  8775. * @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.
  8776. * @param scope optional scope for the callback to be called from
  8777. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8778. * @returns the new observer created for the callback
  8779. */
  8780. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8781. if (mask === void 0) { mask = -1; }
  8782. if (insertFirst === void 0) { insertFirst = false; }
  8783. if (scope === void 0) { scope = null; }
  8784. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8785. if (!callback) {
  8786. return null;
  8787. }
  8788. var observer = new Observer(callback, mask, scope);
  8789. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8790. if (insertFirst) {
  8791. this._observers.unshift(observer);
  8792. }
  8793. else {
  8794. this._observers.push(observer);
  8795. }
  8796. if (this._onObserverAdded) {
  8797. this._onObserverAdded(observer);
  8798. }
  8799. return observer;
  8800. };
  8801. /**
  8802. * Create a new Observer with the specified callback and unregisters after the next notification
  8803. * @param callback the callback that will be executed for that Observer
  8804. * @returns the new observer created for the callback
  8805. */
  8806. Observable.prototype.addOnce = function (callback) {
  8807. return this.add(callback, undefined, undefined, undefined, true);
  8808. };
  8809. /**
  8810. * Remove an Observer from the Observable object
  8811. * @param observer the instance of the Observer to remove
  8812. * @returns false if it doesn't belong to this Observable
  8813. */
  8814. Observable.prototype.remove = function (observer) {
  8815. if (!observer) {
  8816. return false;
  8817. }
  8818. var index = this._observers.indexOf(observer);
  8819. if (index !== -1) {
  8820. this._deferUnregister(observer);
  8821. return true;
  8822. }
  8823. return false;
  8824. };
  8825. /**
  8826. * Remove a callback from the Observable object
  8827. * @param callback the callback to remove
  8828. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8829. * @returns false if it doesn't belong to this Observable
  8830. */
  8831. Observable.prototype.removeCallback = function (callback, scope) {
  8832. for (var index = 0; index < this._observers.length; index++) {
  8833. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8834. this._deferUnregister(this._observers[index]);
  8835. return true;
  8836. }
  8837. }
  8838. return false;
  8839. };
  8840. Observable.prototype._deferUnregister = function (observer) {
  8841. var _this = this;
  8842. observer.unregisterOnNextCall = false;
  8843. observer._willBeUnregistered = true;
  8844. BABYLON.Tools.SetImmediate(function () {
  8845. _this._remove(observer);
  8846. });
  8847. };
  8848. // This should only be called when not iterating over _observers to avoid callback skipping.
  8849. // Removes an observer from the _observer Array.
  8850. Observable.prototype._remove = function (observer) {
  8851. if (!observer) {
  8852. return false;
  8853. }
  8854. var index = this._observers.indexOf(observer);
  8855. if (index !== -1) {
  8856. this._observers.splice(index, 1);
  8857. return true;
  8858. }
  8859. return false;
  8860. };
  8861. /**
  8862. * Notify all Observers by calling their respective callback with the given data
  8863. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8864. * @param eventData defines the data to send to all observers
  8865. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8866. * @param target defines the original target of the state
  8867. * @param currentTarget defines the current target of the state
  8868. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8869. */
  8870. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8871. if (mask === void 0) { mask = -1; }
  8872. if (!this._observers.length) {
  8873. return true;
  8874. }
  8875. var state = this._eventState;
  8876. state.mask = mask;
  8877. state.target = target;
  8878. state.currentTarget = currentTarget;
  8879. state.skipNextObservers = false;
  8880. state.lastReturnValue = eventData;
  8881. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8882. var obs = _a[_i];
  8883. if (obs._willBeUnregistered) {
  8884. continue;
  8885. }
  8886. if (obs.mask & mask) {
  8887. if (obs.scope) {
  8888. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8889. }
  8890. else {
  8891. state.lastReturnValue = obs.callback(eventData, state);
  8892. }
  8893. if (obs.unregisterOnNextCall) {
  8894. this._deferUnregister(obs);
  8895. }
  8896. }
  8897. if (state.skipNextObservers) {
  8898. return false;
  8899. }
  8900. }
  8901. return true;
  8902. };
  8903. /**
  8904. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8905. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8906. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8907. * and it is crucial that all callbacks will be executed.
  8908. * The order of the callbacks is kept, callbacks are not executed parallel.
  8909. *
  8910. * @param eventData The data to be sent to each callback
  8911. * @param mask is used to filter observers defaults to -1
  8912. * @param target defines the callback target (see EventState)
  8913. * @param currentTarget defines he current object in the bubbling phase
  8914. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8915. */
  8916. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8917. var _this = this;
  8918. if (mask === void 0) { mask = -1; }
  8919. // create an empty promise
  8920. var p = Promise.resolve(eventData);
  8921. // no observers? return this promise.
  8922. if (!this._observers.length) {
  8923. return p;
  8924. }
  8925. var state = this._eventState;
  8926. state.mask = mask;
  8927. state.target = target;
  8928. state.currentTarget = currentTarget;
  8929. state.skipNextObservers = false;
  8930. // execute one callback after another (not using Promise.all, the order is important)
  8931. this._observers.forEach(function (obs) {
  8932. if (state.skipNextObservers) {
  8933. return;
  8934. }
  8935. if (obs._willBeUnregistered) {
  8936. return;
  8937. }
  8938. if (obs.mask & mask) {
  8939. if (obs.scope) {
  8940. p = p.then(function (lastReturnedValue) {
  8941. state.lastReturnValue = lastReturnedValue;
  8942. return obs.callback.apply(obs.scope, [eventData, state]);
  8943. });
  8944. }
  8945. else {
  8946. p = p.then(function (lastReturnedValue) {
  8947. state.lastReturnValue = lastReturnedValue;
  8948. return obs.callback(eventData, state);
  8949. });
  8950. }
  8951. if (obs.unregisterOnNextCall) {
  8952. _this._deferUnregister(obs);
  8953. }
  8954. }
  8955. });
  8956. // return the eventData
  8957. return p.then(function () { return eventData; });
  8958. };
  8959. /**
  8960. * Notify a specific observer
  8961. * @param observer defines the observer to notify
  8962. * @param eventData defines the data to be sent to each callback
  8963. * @param mask is used to filter observers defaults to -1
  8964. */
  8965. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8966. if (mask === void 0) { mask = -1; }
  8967. var state = this._eventState;
  8968. state.mask = mask;
  8969. state.skipNextObservers = false;
  8970. observer.callback(eventData, state);
  8971. };
  8972. /**
  8973. * Gets a boolean indicating if the observable has at least one observer
  8974. * @returns true is the Observable has at least one Observer registered
  8975. */
  8976. Observable.prototype.hasObservers = function () {
  8977. return this._observers.length > 0;
  8978. };
  8979. /**
  8980. * Clear the list of observers
  8981. */
  8982. Observable.prototype.clear = function () {
  8983. this._observers = new Array();
  8984. this._onObserverAdded = null;
  8985. };
  8986. /**
  8987. * Clone the current observable
  8988. * @returns a new observable
  8989. */
  8990. Observable.prototype.clone = function () {
  8991. var result = new Observable();
  8992. result._observers = this._observers.slice(0);
  8993. return result;
  8994. };
  8995. /**
  8996. * Does this observable handles observer registered with a given mask
  8997. * @param mask defines the mask to be tested
  8998. * @return whether or not one observer registered with the given mask is handeled
  8999. **/
  9000. Observable.prototype.hasSpecificMask = function (mask) {
  9001. if (mask === void 0) { mask = -1; }
  9002. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  9003. var obs = _a[_i];
  9004. if (obs.mask & mask || obs.mask === mask) {
  9005. return true;
  9006. }
  9007. }
  9008. return false;
  9009. };
  9010. return Observable;
  9011. }());
  9012. BABYLON.Observable = Observable;
  9013. })(BABYLON || (BABYLON = {}));
  9014. //# sourceMappingURL=babylon.observable.js.map
  9015. var BABYLON;
  9016. (function (BABYLON) {
  9017. /**
  9018. * Defines an GC Friendly array where the backfield array do not shrink to prevent over allocations.
  9019. */
  9020. var SmartArray = /** @class */ (function () {
  9021. /**
  9022. * Instantiates a Smart Array.
  9023. * @param capacity defines the default capacity of the array.
  9024. */
  9025. function SmartArray(capacity) {
  9026. /**
  9027. * The active length of the array.
  9028. */
  9029. this.length = 0;
  9030. this.data = new Array(capacity);
  9031. this._id = SmartArray._GlobalId++;
  9032. }
  9033. /**
  9034. * Pushes a value at the end of the active data.
  9035. * @param value defines the object to push in the array.
  9036. */
  9037. SmartArray.prototype.push = function (value) {
  9038. this.data[this.length++] = value;
  9039. if (this.length > this.data.length) {
  9040. this.data.length *= 2;
  9041. }
  9042. };
  9043. /**
  9044. * Iterates over the active data and apply the lambda to them.
  9045. * @param func defines the action to apply on each value.
  9046. */
  9047. SmartArray.prototype.forEach = function (func) {
  9048. for (var index = 0; index < this.length; index++) {
  9049. func(this.data[index]);
  9050. }
  9051. };
  9052. /**
  9053. * Sorts the full sets of data.
  9054. * @param compareFn defines the comparison function to apply.
  9055. */
  9056. SmartArray.prototype.sort = function (compareFn) {
  9057. this.data.sort(compareFn);
  9058. };
  9059. /**
  9060. * Resets the active data to an empty array.
  9061. */
  9062. SmartArray.prototype.reset = function () {
  9063. this.length = 0;
  9064. };
  9065. /**
  9066. * Releases all the data from the array as well as the array.
  9067. */
  9068. SmartArray.prototype.dispose = function () {
  9069. this.reset();
  9070. if (this.data) {
  9071. this.data.length = 0;
  9072. this.data = [];
  9073. }
  9074. };
  9075. /**
  9076. * Concats the active data with a given array.
  9077. * @param array defines the data to concatenate with.
  9078. */
  9079. SmartArray.prototype.concat = function (array) {
  9080. if (array.length === 0) {
  9081. return;
  9082. }
  9083. if (this.length + array.length > this.data.length) {
  9084. this.data.length = (this.length + array.length) * 2;
  9085. }
  9086. for (var index = 0; index < array.length; index++) {
  9087. this.data[this.length++] = (array.data || array)[index];
  9088. }
  9089. };
  9090. /**
  9091. * Returns the position of a value in the active data.
  9092. * @param value defines the value to find the index for
  9093. * @returns the index if found in the active data otherwise -1
  9094. */
  9095. SmartArray.prototype.indexOf = function (value) {
  9096. var position = this.data.indexOf(value);
  9097. if (position >= this.length) {
  9098. return -1;
  9099. }
  9100. return position;
  9101. };
  9102. /**
  9103. * Returns whether an element is part of the active data.
  9104. * @param value defines the value to look for
  9105. * @returns true if found in the active data otherwise false
  9106. */
  9107. SmartArray.prototype.contains = function (value) {
  9108. return this.indexOf(value) !== -1;
  9109. };
  9110. // Statics
  9111. SmartArray._GlobalId = 0;
  9112. return SmartArray;
  9113. }());
  9114. BABYLON.SmartArray = SmartArray;
  9115. /**
  9116. * Defines an GC Friendly array where the backfield array do not shrink to prevent over allocations.
  9117. * The data in this array can only be present once
  9118. */
  9119. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  9120. __extends(SmartArrayNoDuplicate, _super);
  9121. function SmartArrayNoDuplicate() {
  9122. var _this = _super !== null && _super.apply(this, arguments) || this;
  9123. _this._duplicateId = 0;
  9124. return _this;
  9125. }
  9126. /**
  9127. * Pushes a value at the end of the active data.
  9128. * THIS DOES NOT PREVENT DUPPLICATE DATA
  9129. * @param value defines the object to push in the array.
  9130. */
  9131. SmartArrayNoDuplicate.prototype.push = function (value) {
  9132. _super.prototype.push.call(this, value);
  9133. if (!value.__smartArrayFlags) {
  9134. value.__smartArrayFlags = {};
  9135. }
  9136. value.__smartArrayFlags[this._id] = this._duplicateId;
  9137. };
  9138. /**
  9139. * Pushes a value at the end of the active data.
  9140. * If the data is already present, it won t be added again
  9141. * @param value defines the object to push in the array.
  9142. * @returns true if added false if it was already present
  9143. */
  9144. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  9145. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  9146. return false;
  9147. }
  9148. this.push(value);
  9149. return true;
  9150. };
  9151. /**
  9152. * Resets the active data to an empty array.
  9153. */
  9154. SmartArrayNoDuplicate.prototype.reset = function () {
  9155. _super.prototype.reset.call(this);
  9156. this._duplicateId++;
  9157. };
  9158. /**
  9159. * Concats the active data with a given array.
  9160. * This ensures no dupplicate will be present in the result.
  9161. * @param array defines the data to concatenate with.
  9162. */
  9163. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  9164. if (array.length === 0) {
  9165. return;
  9166. }
  9167. if (this.length + array.length > this.data.length) {
  9168. this.data.length = (this.length + array.length) * 2;
  9169. }
  9170. for (var index = 0; index < array.length; index++) {
  9171. var item = (array.data || array)[index];
  9172. this.pushNoDuplicate(item);
  9173. }
  9174. };
  9175. return SmartArrayNoDuplicate;
  9176. }(SmartArray));
  9177. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  9178. })(BABYLON || (BABYLON = {}));
  9179. //# sourceMappingURL=babylon.smartArray.js.map
  9180. var BABYLON;
  9181. (function (BABYLON) {
  9182. /** Class used to store color4 gradient */
  9183. var ColorGradient = /** @class */ (function () {
  9184. function ColorGradient() {
  9185. }
  9186. /**
  9187. * Will get a color picked randomly between color1 and color2.
  9188. * If color2 is undefined then color1 will be used
  9189. * @param result defines the target Color4 to store the result in
  9190. */
  9191. ColorGradient.prototype.getColorToRef = function (result) {
  9192. if (!this.color2) {
  9193. result.copyFrom(this.color1);
  9194. return;
  9195. }
  9196. BABYLON.Color4.LerpToRef(this.color1, this.color2, Math.random(), result);
  9197. };
  9198. return ColorGradient;
  9199. }());
  9200. BABYLON.ColorGradient = ColorGradient;
  9201. /** Class used to store color 3 gradient */
  9202. var Color3Gradient = /** @class */ (function () {
  9203. function Color3Gradient() {
  9204. }
  9205. return Color3Gradient;
  9206. }());
  9207. BABYLON.Color3Gradient = Color3Gradient;
  9208. /** Class used to store factor gradient */
  9209. var FactorGradient = /** @class */ (function () {
  9210. function FactorGradient() {
  9211. }
  9212. /**
  9213. * Will get a number picked randomly between factor1 and factor2.
  9214. * If factor2 is undefined then factor1 will be used
  9215. * @returns the picked number
  9216. */
  9217. FactorGradient.prototype.getFactor = function () {
  9218. if (this.factor2 === undefined) {
  9219. return this.factor1;
  9220. }
  9221. return BABYLON.Scalar.Lerp(this.factor1, this.factor2, Math.random());
  9222. };
  9223. return FactorGradient;
  9224. }());
  9225. BABYLON.FactorGradient = FactorGradient;
  9226. /**
  9227. * @ignore
  9228. * Application error to support additional information when loading a file
  9229. */
  9230. var LoadFileError = /** @class */ (function (_super) {
  9231. __extends(LoadFileError, _super);
  9232. /**
  9233. * Creates a new LoadFileError
  9234. * @param message defines the message of the error
  9235. * @param request defines the optional XHR request
  9236. */
  9237. function LoadFileError(message,
  9238. /** defines the optional XHR request */
  9239. request) {
  9240. var _this = _super.call(this, message) || this;
  9241. _this.request = request;
  9242. _this.name = "LoadFileError";
  9243. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  9244. return _this;
  9245. }
  9246. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  9247. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  9248. // Polyfill for Object.setPrototypeOf if necessary.
  9249. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  9250. return LoadFileError;
  9251. }(Error));
  9252. BABYLON.LoadFileError = LoadFileError;
  9253. /**
  9254. * Class used to define a retry strategy when error happens while loading assets
  9255. */
  9256. var RetryStrategy = /** @class */ (function () {
  9257. function RetryStrategy() {
  9258. }
  9259. /**
  9260. * Function used to defines an exponential back off strategy
  9261. * @param maxRetries defines the maximum number of retries (3 by default)
  9262. * @param baseInterval defines the interval between retries
  9263. * @returns the strategy function to use
  9264. */
  9265. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  9266. if (maxRetries === void 0) { maxRetries = 3; }
  9267. if (baseInterval === void 0) { baseInterval = 500; }
  9268. return function (url, request, retryIndex) {
  9269. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  9270. return -1;
  9271. }
  9272. return Math.pow(2, retryIndex) * baseInterval;
  9273. };
  9274. };
  9275. return RetryStrategy;
  9276. }());
  9277. BABYLON.RetryStrategy = RetryStrategy;
  9278. // Screenshots
  9279. var screenshotCanvas;
  9280. var cloneValue = function (source, destinationObject) {
  9281. if (!source)
  9282. return null;
  9283. if (source instanceof BABYLON.Mesh) {
  9284. return null;
  9285. }
  9286. if (source instanceof BABYLON.SubMesh) {
  9287. return source.clone(destinationObject);
  9288. }
  9289. else if (source.clone) {
  9290. return source.clone();
  9291. }
  9292. return null;
  9293. };
  9294. /**
  9295. * Class containing a set of static utilities functions
  9296. */
  9297. var Tools = /** @class */ (function () {
  9298. function Tools() {
  9299. }
  9300. /**
  9301. * Read the content of a byte array at a specified coordinates (taking in account wrapping)
  9302. * @param u defines the coordinate on X axis
  9303. * @param v defines the coordinate on Y axis
  9304. * @param width defines the width of the source data
  9305. * @param height defines the height of the source data
  9306. * @param pixels defines the source byte array
  9307. * @param color defines the output color
  9308. */
  9309. Tools.FetchToRef = function (u, v, width, height, pixels, color) {
  9310. var wrappedU = ((Math.abs(u) * width) % width) | 0;
  9311. var wrappedV = ((Math.abs(v) * height) % height) | 0;
  9312. var position = (wrappedU + wrappedV * width) * 4;
  9313. color.r = pixels[position] / 255;
  9314. color.g = pixels[position + 1] / 255;
  9315. color.b = pixels[position + 2] / 255;
  9316. color.a = pixels[position + 3] / 255;
  9317. };
  9318. /**
  9319. * Interpolates between a and b via alpha
  9320. * @param a The lower value (returned when alpha = 0)
  9321. * @param b The upper value (returned when alpha = 1)
  9322. * @param alpha The interpolation-factor
  9323. * @return The mixed value
  9324. */
  9325. Tools.Mix = function (a, b, alpha) {
  9326. return a * (1 - alpha) + b * alpha;
  9327. };
  9328. /**
  9329. * Tries to instantiate a new object from a given class name
  9330. * @param className defines the class name to instantiate
  9331. * @returns the new object or null if the system was not able to do the instantiation
  9332. */
  9333. Tools.Instantiate = function (className) {
  9334. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  9335. return Tools.RegisteredExternalClasses[className];
  9336. }
  9337. var arr = className.split(".");
  9338. var fn = (window || this);
  9339. for (var i = 0, len = arr.length; i < len; i++) {
  9340. fn = fn[arr[i]];
  9341. }
  9342. if (typeof fn !== "function") {
  9343. return null;
  9344. }
  9345. return fn;
  9346. };
  9347. /**
  9348. * Provides a slice function that will work even on IE
  9349. * @param data defines the array to slice
  9350. * @param start defines the start of the data (optional)
  9351. * @param end defines the end of the data (optional)
  9352. * @returns the new sliced array
  9353. */
  9354. Tools.Slice = function (data, start, end) {
  9355. if (data.slice) {
  9356. return data.slice(start, end);
  9357. }
  9358. return Array.prototype.slice.call(data, start, end);
  9359. };
  9360. /**
  9361. * Polyfill for setImmediate
  9362. * @param action defines the action to execute after the current execution block
  9363. */
  9364. Tools.SetImmediate = function (action) {
  9365. if (Tools.IsWindowObjectExist() && window.setImmediate) {
  9366. window.setImmediate(action);
  9367. }
  9368. else {
  9369. setTimeout(action, 1);
  9370. }
  9371. };
  9372. /**
  9373. * Function indicating if a number is an exponent of 2
  9374. * @param value defines the value to test
  9375. * @returns true if the value is an exponent of 2
  9376. */
  9377. Tools.IsExponentOfTwo = function (value) {
  9378. var count = 1;
  9379. do {
  9380. count *= 2;
  9381. } while (count < value);
  9382. return count === value;
  9383. };
  9384. /**
  9385. * Returns the nearest 32-bit single precision float representation of a Number
  9386. * @param value A Number. If the parameter is of a different type, it will get converted
  9387. * to a number or to NaN if it cannot be converted
  9388. * @returns number
  9389. */
  9390. Tools.FloatRound = function (value) {
  9391. if (Math.fround) {
  9392. return Math.fround(value);
  9393. }
  9394. return (Tools._tmpFloatArray[0] = value);
  9395. };
  9396. /**
  9397. * Find the next highest power of two.
  9398. * @param x Number to start search from.
  9399. * @return Next highest power of two.
  9400. */
  9401. Tools.CeilingPOT = function (x) {
  9402. x--;
  9403. x |= x >> 1;
  9404. x |= x >> 2;
  9405. x |= x >> 4;
  9406. x |= x >> 8;
  9407. x |= x >> 16;
  9408. x++;
  9409. return x;
  9410. };
  9411. /**
  9412. * Find the next lowest power of two.
  9413. * @param x Number to start search from.
  9414. * @return Next lowest power of two.
  9415. */
  9416. Tools.FloorPOT = function (x) {
  9417. x = x | (x >> 1);
  9418. x = x | (x >> 2);
  9419. x = x | (x >> 4);
  9420. x = x | (x >> 8);
  9421. x = x | (x >> 16);
  9422. return x - (x >> 1);
  9423. };
  9424. /**
  9425. * Find the nearest power of two.
  9426. * @param x Number to start search from.
  9427. * @return Next nearest power of two.
  9428. */
  9429. Tools.NearestPOT = function (x) {
  9430. var c = Tools.CeilingPOT(x);
  9431. var f = Tools.FloorPOT(x);
  9432. return (c - x) > (x - f) ? f : c;
  9433. };
  9434. /**
  9435. * Get the closest exponent of two
  9436. * @param value defines the value to approximate
  9437. * @param max defines the maximum value to return
  9438. * @param mode defines how to define the closest value
  9439. * @returns closest exponent of two of the given value
  9440. */
  9441. Tools.GetExponentOfTwo = function (value, max, mode) {
  9442. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  9443. var pot;
  9444. switch (mode) {
  9445. case BABYLON.Engine.SCALEMODE_FLOOR:
  9446. pot = Tools.FloorPOT(value);
  9447. break;
  9448. case BABYLON.Engine.SCALEMODE_NEAREST:
  9449. pot = Tools.NearestPOT(value);
  9450. break;
  9451. case BABYLON.Engine.SCALEMODE_CEILING:
  9452. default:
  9453. pot = Tools.CeilingPOT(value);
  9454. break;
  9455. }
  9456. return Math.min(pot, max);
  9457. };
  9458. /**
  9459. * Extracts the filename from a path
  9460. * @param path defines the path to use
  9461. * @returns the filename
  9462. */
  9463. Tools.GetFilename = function (path) {
  9464. var index = path.lastIndexOf("/");
  9465. if (index < 0)
  9466. return path;
  9467. return path.substring(index + 1);
  9468. };
  9469. /**
  9470. * Extracts the "folder" part of a path (everything before the filename).
  9471. * @param uri The URI to extract the info from
  9472. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  9473. * @returns The "folder" part of the path
  9474. */
  9475. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  9476. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  9477. var index = uri.lastIndexOf("/");
  9478. if (index < 0) {
  9479. if (returnUnchangedIfNoSlash) {
  9480. return uri;
  9481. }
  9482. return "";
  9483. }
  9484. return uri.substring(0, index + 1);
  9485. };
  9486. /**
  9487. * Extracts text content from a DOM element hierarchy
  9488. * @param element defines the root element
  9489. * @returns a string
  9490. */
  9491. Tools.GetDOMTextContent = function (element) {
  9492. var result = "";
  9493. var child = element.firstChild;
  9494. while (child) {
  9495. if (child.nodeType === 3) {
  9496. result += child.textContent;
  9497. }
  9498. child = child.nextSibling;
  9499. }
  9500. return result;
  9501. };
  9502. /**
  9503. * Convert an angle in radians to degrees
  9504. * @param angle defines the angle to convert
  9505. * @returns the angle in degrees
  9506. */
  9507. Tools.ToDegrees = function (angle) {
  9508. return angle * 180 / Math.PI;
  9509. };
  9510. /**
  9511. * Convert an angle in degrees to radians
  9512. * @param angle defines the angle to convert
  9513. * @returns the angle in radians
  9514. */
  9515. Tools.ToRadians = function (angle) {
  9516. return angle * Math.PI / 180;
  9517. };
  9518. /**
  9519. * Encode a buffer to a base64 string
  9520. * @param buffer defines the buffer to encode
  9521. * @returns the encoded string
  9522. */
  9523. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  9524. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  9525. var output = "";
  9526. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  9527. var i = 0;
  9528. var bytes = new Uint8Array(buffer);
  9529. while (i < bytes.length) {
  9530. chr1 = bytes[i++];
  9531. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  9532. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  9533. enc1 = chr1 >> 2;
  9534. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  9535. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  9536. enc4 = chr3 & 63;
  9537. if (isNaN(chr2)) {
  9538. enc3 = enc4 = 64;
  9539. }
  9540. else if (isNaN(chr3)) {
  9541. enc4 = 64;
  9542. }
  9543. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  9544. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  9545. }
  9546. return "data:image/png;base64," + output;
  9547. };
  9548. /**
  9549. * Extracts minimum and maximum values from a list of indexed positions
  9550. * @param positions defines the positions to use
  9551. * @param indices defines the indices to the positions
  9552. * @param indexStart defines the start index
  9553. * @param indexCount defines the end index
  9554. * @param bias defines bias value to add to the result
  9555. * @return minimum and maximum values
  9556. */
  9557. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  9558. if (bias === void 0) { bias = null; }
  9559. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9560. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  9561. for (var index = indexStart; index < indexStart + indexCount; index++) {
  9562. var offset = indices[index] * 3;
  9563. var x = positions[offset];
  9564. var y = positions[offset + 1];
  9565. var z = positions[offset + 2];
  9566. minimum.minimizeInPlaceFromFloats(x, y, z);
  9567. maximum.maximizeInPlaceFromFloats(x, y, z);
  9568. }
  9569. if (bias) {
  9570. minimum.x -= minimum.x * bias.x + bias.y;
  9571. minimum.y -= minimum.y * bias.x + bias.y;
  9572. minimum.z -= minimum.z * bias.x + bias.y;
  9573. maximum.x += maximum.x * bias.x + bias.y;
  9574. maximum.y += maximum.y * bias.x + bias.y;
  9575. maximum.z += maximum.z * bias.x + bias.y;
  9576. }
  9577. return {
  9578. minimum: minimum,
  9579. maximum: maximum
  9580. };
  9581. };
  9582. /**
  9583. * Extracts minimum and maximum values from a list of positions
  9584. * @param positions defines the positions to use
  9585. * @param start defines the start index in the positions array
  9586. * @param count defines the number of positions to handle
  9587. * @param bias defines bias value to add to the result
  9588. * @param stride defines the stride size to use (distance between two positions in the positions array)
  9589. * @return minimum and maximum values
  9590. */
  9591. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  9592. if (bias === void 0) { bias = null; }
  9593. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9594. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  9595. if (!stride) {
  9596. stride = 3;
  9597. }
  9598. for (var index = start, offset = start * stride; index < start + count; index++, offset += stride) {
  9599. var x = positions[offset];
  9600. var y = positions[offset + 1];
  9601. var z = positions[offset + 2];
  9602. minimum.minimizeInPlaceFromFloats(x, y, z);
  9603. maximum.maximizeInPlaceFromFloats(x, y, z);
  9604. }
  9605. if (bias) {
  9606. minimum.x -= minimum.x * bias.x + bias.y;
  9607. minimum.y -= minimum.y * bias.x + bias.y;
  9608. minimum.z -= minimum.z * bias.x + bias.y;
  9609. maximum.x += maximum.x * bias.x + bias.y;
  9610. maximum.y += maximum.y * bias.x + bias.y;
  9611. maximum.z += maximum.z * bias.x + bias.y;
  9612. }
  9613. return {
  9614. minimum: minimum,
  9615. maximum: maximum
  9616. };
  9617. };
  9618. /**
  9619. * Returns an array if obj is not an array
  9620. * @param obj defines the object to evaluate as an array
  9621. * @param allowsNullUndefined defines a boolean indicating if obj is allowed to be null or undefined
  9622. * @returns either obj directly if obj is an array or a new array containing obj
  9623. */
  9624. Tools.MakeArray = function (obj, allowsNullUndefined) {
  9625. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  9626. return null;
  9627. return Array.isArray(obj) ? obj : [obj];
  9628. };
  9629. /**
  9630. * Gets the pointer prefix to use
  9631. * @returns "pointer" if touch is enabled. Else returns "mouse"
  9632. */
  9633. Tools.GetPointerPrefix = function () {
  9634. var eventPrefix = "pointer";
  9635. // Check if pointer events are supported
  9636. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  9637. eventPrefix = "mouse";
  9638. }
  9639. return eventPrefix;
  9640. };
  9641. /**
  9642. * Queue a new function into the requested animation frame pool (ie. this function will be executed byt the browser for the next frame)
  9643. * @param func - the function to be called
  9644. * @param requester - the object that will request the next frame. Falls back to window.
  9645. * @returns frame number
  9646. */
  9647. Tools.QueueNewFrame = function (func, requester) {
  9648. if (!Tools.IsWindowObjectExist()) {
  9649. return setTimeout(func, 16);
  9650. }
  9651. if (!requester) {
  9652. requester = window;
  9653. }
  9654. if (requester.requestAnimationFrame) {
  9655. return requester.requestAnimationFrame(func);
  9656. }
  9657. else if (requester.msRequestAnimationFrame) {
  9658. return requester.msRequestAnimationFrame(func);
  9659. }
  9660. else if (requester.webkitRequestAnimationFrame) {
  9661. return requester.webkitRequestAnimationFrame(func);
  9662. }
  9663. else if (requester.mozRequestAnimationFrame) {
  9664. return requester.mozRequestAnimationFrame(func);
  9665. }
  9666. else if (requester.oRequestAnimationFrame) {
  9667. return requester.oRequestAnimationFrame(func);
  9668. }
  9669. else {
  9670. return window.setTimeout(func, 16);
  9671. }
  9672. };
  9673. /**
  9674. * Ask the browser to promote the current element to fullscreen rendering mode
  9675. * @param element defines the DOM element to promote
  9676. */
  9677. Tools.RequestFullscreen = function (element) {
  9678. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  9679. if (!requestFunction)
  9680. return;
  9681. requestFunction.call(element);
  9682. };
  9683. /**
  9684. * Asks the browser to exit fullscreen mode
  9685. */
  9686. Tools.ExitFullscreen = function () {
  9687. if (document.exitFullscreen) {
  9688. document.exitFullscreen();
  9689. }
  9690. else if (document.mozCancelFullScreen) {
  9691. document.mozCancelFullScreen();
  9692. }
  9693. else if (document.webkitCancelFullScreen) {
  9694. document.webkitCancelFullScreen();
  9695. }
  9696. else if (document.msCancelFullScreen) {
  9697. document.msCancelFullScreen();
  9698. }
  9699. };
  9700. /**
  9701. * Sets the cors behavior on a dom element. This will add the required Tools.CorsBehavior to the element.
  9702. * @param url define the url we are trying
  9703. * @param element define the dom element where to configure the cors policy
  9704. */
  9705. Tools.SetCorsBehavior = function (url, element) {
  9706. if (url && url.indexOf("data:") === 0) {
  9707. return;
  9708. }
  9709. if (Tools.CorsBehavior) {
  9710. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  9711. element.crossOrigin = Tools.CorsBehavior;
  9712. }
  9713. else {
  9714. var result = Tools.CorsBehavior(url);
  9715. if (result) {
  9716. element.crossOrigin = result;
  9717. }
  9718. }
  9719. }
  9720. };
  9721. // External files
  9722. /**
  9723. * Removes unwanted characters from an url
  9724. * @param url defines the url to clean
  9725. * @returns the cleaned url
  9726. */
  9727. Tools.CleanUrl = function (url) {
  9728. url = url.replace(/#/mg, "%23");
  9729. return url;
  9730. };
  9731. /**
  9732. * Loads an image as an HTMLImageElement.
  9733. * @param input url string, ArrayBuffer, or Blob to load
  9734. * @param onLoad callback called when the image successfully loads
  9735. * @param onError callback called when the image fails to load
  9736. * @param database database for caching
  9737. * @returns the HTMLImageElement of the loaded image
  9738. */
  9739. Tools.LoadImage = function (input, onLoad, onError, database) {
  9740. var url;
  9741. var usingObjectURL = false;
  9742. if (input instanceof ArrayBuffer) {
  9743. url = URL.createObjectURL(new Blob([input]));
  9744. usingObjectURL = true;
  9745. }
  9746. else if (input instanceof Blob) {
  9747. url = URL.createObjectURL(input);
  9748. usingObjectURL = true;
  9749. }
  9750. else {
  9751. url = Tools.CleanUrl(input);
  9752. url = Tools.PreprocessUrl(input);
  9753. }
  9754. var img = new Image();
  9755. Tools.SetCorsBehavior(url, img);
  9756. var loadHandler = function () {
  9757. if (usingObjectURL && img.src) {
  9758. URL.revokeObjectURL(img.src);
  9759. }
  9760. img.removeEventListener("load", loadHandler);
  9761. img.removeEventListener("error", errorHandler);
  9762. onLoad(img);
  9763. };
  9764. var errorHandler = function (err) {
  9765. if (usingObjectURL && img.src) {
  9766. URL.revokeObjectURL(img.src);
  9767. }
  9768. img.removeEventListener("load", loadHandler);
  9769. img.removeEventListener("error", errorHandler);
  9770. Tools.Error("Error while trying to load image: " + input);
  9771. if (onError) {
  9772. onError("Error while trying to load image: " + input, err);
  9773. }
  9774. };
  9775. img.addEventListener("load", loadHandler);
  9776. img.addEventListener("error", errorHandler);
  9777. var noIndexedDB = function () {
  9778. img.src = url;
  9779. };
  9780. var loadFromIndexedDB = function () {
  9781. if (database) {
  9782. database.loadImageFromDB(url, img);
  9783. }
  9784. };
  9785. //ANY database to do!
  9786. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  9787. database.openAsync(loadFromIndexedDB, noIndexedDB);
  9788. }
  9789. else {
  9790. if (url.indexOf("file:") !== -1) {
  9791. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  9792. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  9793. try {
  9794. var blobURL;
  9795. try {
  9796. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9797. }
  9798. catch (ex) {
  9799. // Chrome doesn't support oneTimeOnly parameter
  9800. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9801. }
  9802. img.src = blobURL;
  9803. usingObjectURL = true;
  9804. }
  9805. catch (e) {
  9806. img.src = "";
  9807. }
  9808. return img;
  9809. }
  9810. }
  9811. noIndexedDB();
  9812. }
  9813. return img;
  9814. };
  9815. /**
  9816. * Loads a file
  9817. * @param url url string, ArrayBuffer, or Blob to load
  9818. * @param onSuccess callback called when the file successfully loads
  9819. * @param onProgress callback called while file is loading (if the server supports this mode)
  9820. * @param database database for caching
  9821. * @param useArrayBuffer defines a boolean indicating that date must be returned as ArrayBuffer
  9822. * @param onError callback called when the file fails to load
  9823. * @returns a file request object
  9824. */
  9825. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  9826. url = Tools.CleanUrl(url);
  9827. url = Tools.PreprocessUrl(url);
  9828. // If file and file input are set
  9829. if (url.indexOf("file:") !== -1) {
  9830. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  9831. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  9832. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  9833. }
  9834. }
  9835. var loadUrl = Tools.BaseUrl + url;
  9836. var aborted = false;
  9837. var fileRequest = {
  9838. onCompleteObservable: new BABYLON.Observable(),
  9839. abort: function () { return aborted = true; },
  9840. };
  9841. var requestFile = function () {
  9842. var request = new XMLHttpRequest();
  9843. var retryHandle = null;
  9844. fileRequest.abort = function () {
  9845. aborted = true;
  9846. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  9847. request.abort();
  9848. }
  9849. if (retryHandle !== null) {
  9850. clearTimeout(retryHandle);
  9851. retryHandle = null;
  9852. }
  9853. };
  9854. var retryLoop = function (retryIndex) {
  9855. request.open('GET', loadUrl, true);
  9856. if (useArrayBuffer) {
  9857. request.responseType = "arraybuffer";
  9858. }
  9859. if (onProgress) {
  9860. request.addEventListener("progress", onProgress);
  9861. }
  9862. var onLoadEnd = function () {
  9863. request.removeEventListener("loadend", onLoadEnd);
  9864. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9865. fileRequest.onCompleteObservable.clear();
  9866. };
  9867. request.addEventListener("loadend", onLoadEnd);
  9868. var onReadyStateChange = function () {
  9869. if (aborted) {
  9870. return;
  9871. }
  9872. // In case of undefined state in some browsers.
  9873. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9874. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9875. request.removeEventListener("readystatechange", onReadyStateChange);
  9876. if ((request.status >= 200 && request.status < 300) || (request.status === 0 && (!Tools.IsWindowObjectExist() || Tools.IsFileURL()))) {
  9877. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9878. return;
  9879. }
  9880. var retryStrategy = Tools.DefaultRetryStrategy;
  9881. if (retryStrategy) {
  9882. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9883. if (waitTime !== -1) {
  9884. // Prevent the request from completing for retry.
  9885. request.removeEventListener("loadend", onLoadEnd);
  9886. request = new XMLHttpRequest();
  9887. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9888. return;
  9889. }
  9890. }
  9891. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9892. if (onError) {
  9893. onError(request, e);
  9894. }
  9895. else {
  9896. throw e;
  9897. }
  9898. }
  9899. };
  9900. request.addEventListener("readystatechange", onReadyStateChange);
  9901. request.send();
  9902. };
  9903. retryLoop(0);
  9904. };
  9905. // Caching all files
  9906. if (database && database.enableSceneOffline) {
  9907. var noIndexedDB_1 = function (request) {
  9908. if (request && request.status > 400) {
  9909. if (onError) {
  9910. onError(request);
  9911. }
  9912. }
  9913. else {
  9914. if (!aborted) {
  9915. requestFile();
  9916. }
  9917. }
  9918. };
  9919. var loadFromIndexedDB = function () {
  9920. // TODO: database needs to support aborting and should return a IFileRequest
  9921. if (aborted) {
  9922. return;
  9923. }
  9924. if (database) {
  9925. database.loadFileFromDB(url, function (data) {
  9926. if (!aborted) {
  9927. onSuccess(data);
  9928. }
  9929. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9930. }, onProgress ? function (event) {
  9931. if (!aborted) {
  9932. onProgress(event);
  9933. }
  9934. } : undefined, noIndexedDB_1, useArrayBuffer);
  9935. }
  9936. };
  9937. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9938. }
  9939. else {
  9940. requestFile();
  9941. }
  9942. return fileRequest;
  9943. };
  9944. /**
  9945. * Load a script (identified by an url). When the url returns, the
  9946. * content of this file is added into a new script element, attached to the DOM (body element)
  9947. * @param scriptUrl defines the url of the script to laod
  9948. * @param onSuccess defines the callback called when the script is loaded
  9949. * @param onError defines the callback to call if an error occurs
  9950. */
  9951. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9952. if (!Tools.IsWindowObjectExist()) {
  9953. return;
  9954. }
  9955. var head = document.getElementsByTagName('head')[0];
  9956. var script = document.createElement('script');
  9957. script.type = 'text/javascript';
  9958. script.src = scriptUrl;
  9959. script.onload = function () {
  9960. if (onSuccess) {
  9961. onSuccess();
  9962. }
  9963. };
  9964. script.onerror = function (e) {
  9965. if (onError) {
  9966. onError("Unable to load script '" + scriptUrl + "'", e);
  9967. }
  9968. };
  9969. head.appendChild(script);
  9970. };
  9971. /**
  9972. * Loads a file from a blob
  9973. * @param fileToLoad defines the blob to use
  9974. * @param callback defines the callback to call when data is loaded
  9975. * @param progressCallback defines the callback to call during loading process
  9976. * @returns a file request object
  9977. */
  9978. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9979. var reader = new FileReader();
  9980. var request = {
  9981. onCompleteObservable: new BABYLON.Observable(),
  9982. abort: function () { return reader.abort(); },
  9983. };
  9984. reader.onloadend = function (e) {
  9985. request.onCompleteObservable.notifyObservers(request);
  9986. };
  9987. reader.onload = function (e) {
  9988. //target doesn't have result from ts 1.3
  9989. callback(e.target['result']);
  9990. };
  9991. reader.onprogress = progressCallback;
  9992. reader.readAsDataURL(fileToLoad);
  9993. return request;
  9994. };
  9995. /**
  9996. * Loads a file
  9997. * @param fileToLoad defines the file to load
  9998. * @param callback defines the callback to call when data is loaded
  9999. * @param progressCallBack defines the callback to call during loading process
  10000. * @param useArrayBuffer defines a boolean indicating that data must be returned as an ArrayBuffer
  10001. * @returns a file request object
  10002. */
  10003. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  10004. var reader = new FileReader();
  10005. var request = {
  10006. onCompleteObservable: new BABYLON.Observable(),
  10007. abort: function () { return reader.abort(); },
  10008. };
  10009. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  10010. reader.onerror = function (e) {
  10011. Tools.Log("Error while reading file: " + fileToLoad.name);
  10012. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  10013. };
  10014. reader.onload = function (e) {
  10015. //target doesn't have result from ts 1.3
  10016. callback(e.target['result']);
  10017. };
  10018. if (progressCallBack) {
  10019. reader.onprogress = progressCallBack;
  10020. }
  10021. if (!useArrayBuffer) {
  10022. // Asynchronous read
  10023. reader.readAsText(fileToLoad);
  10024. }
  10025. else {
  10026. reader.readAsArrayBuffer(fileToLoad);
  10027. }
  10028. return request;
  10029. };
  10030. /**
  10031. * Creates a data url from a given string content
  10032. * @param content defines the content to convert
  10033. * @returns the new data url link
  10034. */
  10035. Tools.FileAsURL = function (content) {
  10036. var fileBlob = new Blob([content]);
  10037. var url = window.URL || window.webkitURL;
  10038. var link = url.createObjectURL(fileBlob);
  10039. return link;
  10040. };
  10041. /**
  10042. * Format the given number to a specific decimal format
  10043. * @param value defines the number to format
  10044. * @param decimals defines the number of decimals to use
  10045. * @returns the formatted string
  10046. */
  10047. Tools.Format = function (value, decimals) {
  10048. if (decimals === void 0) { decimals = 2; }
  10049. return value.toFixed(decimals);
  10050. };
  10051. /**
  10052. * Checks if a given vector is inside a specific range
  10053. * @param v defines the vector to test
  10054. * @param min defines the minimum range
  10055. * @param max defines the maximum range
  10056. */
  10057. Tools.CheckExtends = function (v, min, max) {
  10058. if (v.x < min.x)
  10059. min.x = v.x;
  10060. if (v.y < min.y)
  10061. min.y = v.y;
  10062. if (v.z < min.z)
  10063. min.z = v.z;
  10064. if (v.x > max.x)
  10065. max.x = v.x;
  10066. if (v.y > max.y)
  10067. max.y = v.y;
  10068. if (v.z > max.z)
  10069. max.z = v.z;
  10070. };
  10071. /**
  10072. * Tries to copy an object by duplicating every property
  10073. * @param source defines the source object
  10074. * @param destination defines the target object
  10075. * @param doNotCopyList defines a list of properties to avoid
  10076. * @param mustCopyList defines a list of properties to copy (even if they start with _)
  10077. */
  10078. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  10079. for (var prop in source) {
  10080. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  10081. continue;
  10082. }
  10083. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  10084. continue;
  10085. }
  10086. var sourceValue = source[prop];
  10087. var typeOfSourceValue = typeof sourceValue;
  10088. if (typeOfSourceValue === "function") {
  10089. continue;
  10090. }
  10091. try {
  10092. if (typeOfSourceValue === "object") {
  10093. if (sourceValue instanceof Array) {
  10094. destination[prop] = [];
  10095. if (sourceValue.length > 0) {
  10096. if (typeof sourceValue[0] == "object") {
  10097. for (var index = 0; index < sourceValue.length; index++) {
  10098. var clonedValue = cloneValue(sourceValue[index], destination);
  10099. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  10100. destination[prop].push(clonedValue);
  10101. }
  10102. }
  10103. }
  10104. else {
  10105. destination[prop] = sourceValue.slice(0);
  10106. }
  10107. }
  10108. }
  10109. else {
  10110. destination[prop] = cloneValue(sourceValue, destination);
  10111. }
  10112. }
  10113. else {
  10114. destination[prop] = sourceValue;
  10115. }
  10116. }
  10117. catch (e) {
  10118. // Just ignore error (it could be because of a read-only property)
  10119. }
  10120. }
  10121. };
  10122. /**
  10123. * Gets a boolean indicating if the given object has no own property
  10124. * @param obj defines the object to test
  10125. * @returns true if object has no own property
  10126. */
  10127. Tools.IsEmpty = function (obj) {
  10128. for (var i in obj) {
  10129. if (obj.hasOwnProperty(i)) {
  10130. return false;
  10131. }
  10132. }
  10133. return true;
  10134. };
  10135. /**
  10136. * Function used to register events at window level
  10137. * @param events defines the events to register
  10138. */
  10139. Tools.RegisterTopRootEvents = function (events) {
  10140. for (var index = 0; index < events.length; index++) {
  10141. var event = events[index];
  10142. window.addEventListener(event.name, event.handler, false);
  10143. try {
  10144. if (window.parent) {
  10145. window.parent.addEventListener(event.name, event.handler, false);
  10146. }
  10147. }
  10148. catch (e) {
  10149. // Silently fails...
  10150. }
  10151. }
  10152. };
  10153. /**
  10154. * Function used to unregister events from window level
  10155. * @param events defines the events to unregister
  10156. */
  10157. Tools.UnregisterTopRootEvents = function (events) {
  10158. for (var index = 0; index < events.length; index++) {
  10159. var event = events[index];
  10160. window.removeEventListener(event.name, event.handler);
  10161. try {
  10162. if (window.parent) {
  10163. window.parent.removeEventListener(event.name, event.handler);
  10164. }
  10165. }
  10166. catch (e) {
  10167. // Silently fails...
  10168. }
  10169. }
  10170. };
  10171. /**
  10172. * Dumps the current bound framebuffer
  10173. * @param width defines the rendering width
  10174. * @param height defines the rendering height
  10175. * @param engine defines the hosting engine
  10176. * @param successCallback defines the callback triggered once the data are available
  10177. * @param mimeType defines the mime type of the result
  10178. * @param fileName defines the filename to download. If present, the result will automatically be downloaded
  10179. */
  10180. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  10181. if (mimeType === void 0) { mimeType = "image/png"; }
  10182. // Read the contents of the framebuffer
  10183. var numberOfChannelsByLine = width * 4;
  10184. var halfHeight = height / 2;
  10185. //Reading datas from WebGL
  10186. var data = engine.readPixels(0, 0, width, height);
  10187. //To flip image on Y axis.
  10188. for (var i = 0; i < halfHeight; i++) {
  10189. for (var j = 0; j < numberOfChannelsByLine; j++) {
  10190. var currentCell = j + i * numberOfChannelsByLine;
  10191. var targetLine = height - i - 1;
  10192. var targetCell = j + targetLine * numberOfChannelsByLine;
  10193. var temp = data[currentCell];
  10194. data[currentCell] = data[targetCell];
  10195. data[targetCell] = temp;
  10196. }
  10197. }
  10198. // Create a 2D canvas to store the result
  10199. if (!screenshotCanvas) {
  10200. screenshotCanvas = document.createElement('canvas');
  10201. }
  10202. screenshotCanvas.width = width;
  10203. screenshotCanvas.height = height;
  10204. var context = screenshotCanvas.getContext('2d');
  10205. if (context) {
  10206. // Copy the pixels to a 2D canvas
  10207. var imageData = context.createImageData(width, height);
  10208. var castData = (imageData.data);
  10209. castData.set(data);
  10210. context.putImageData(imageData, 0, 0);
  10211. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  10212. }
  10213. };
  10214. /**
  10215. * Converts the canvas data to blob.
  10216. * This acts as a polyfill for browsers not supporting the to blob function.
  10217. * @param canvas Defines the canvas to extract the data from
  10218. * @param successCallback Defines the callback triggered once the data are available
  10219. * @param mimeType Defines the mime type of the result
  10220. */
  10221. Tools.ToBlob = function (canvas, successCallback, mimeType) {
  10222. if (mimeType === void 0) { mimeType = "image/png"; }
  10223. // We need HTMLCanvasElement.toBlob for HD screenshots
  10224. if (!canvas.toBlob) {
  10225. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  10226. canvas.toBlob = function (callback, type, quality) {
  10227. var _this = this;
  10228. setTimeout(function () {
  10229. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  10230. for (var i = 0; i < len; i++) {
  10231. arr[i] = binStr.charCodeAt(i);
  10232. }
  10233. callback(new Blob([arr]));
  10234. });
  10235. };
  10236. }
  10237. canvas.toBlob(function (blob) {
  10238. successCallback(blob);
  10239. }, mimeType);
  10240. };
  10241. /**
  10242. * Encodes the canvas data to base 64 or automatically download the result if filename is defined
  10243. * @param successCallback defines the callback triggered once the data are available
  10244. * @param mimeType defines the mime type of the result
  10245. * @param fileName defines he filename to download. If present, the result will automatically be downloaded
  10246. */
  10247. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  10248. if (mimeType === void 0) { mimeType = "image/png"; }
  10249. if (successCallback) {
  10250. var base64Image = screenshotCanvas.toDataURL(mimeType);
  10251. successCallback(base64Image);
  10252. }
  10253. else {
  10254. this.ToBlob(screenshotCanvas, function (blob) {
  10255. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  10256. if (("download" in document.createElement("a"))) {
  10257. if (!fileName) {
  10258. var date = new Date();
  10259. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  10260. fileName = "screenshot_" + stringDate + ".png";
  10261. }
  10262. Tools.Download(blob, fileName);
  10263. }
  10264. else {
  10265. var url = URL.createObjectURL(blob);
  10266. var newWindow = window.open("");
  10267. if (!newWindow)
  10268. return;
  10269. var img = newWindow.document.createElement("img");
  10270. img.onload = function () {
  10271. // no longer need to read the blob so it's revoked
  10272. URL.revokeObjectURL(url);
  10273. };
  10274. img.src = url;
  10275. newWindow.document.body.appendChild(img);
  10276. }
  10277. }, mimeType);
  10278. }
  10279. };
  10280. /**
  10281. * Downloads a blob in the browser
  10282. * @param blob defines the blob to download
  10283. * @param fileName defines the name of the downloaded file
  10284. */
  10285. Tools.Download = function (blob, fileName) {
  10286. if (navigator && navigator.msSaveBlob) {
  10287. navigator.msSaveBlob(blob, fileName);
  10288. return;
  10289. }
  10290. var url = window.URL.createObjectURL(blob);
  10291. var a = document.createElement("a");
  10292. document.body.appendChild(a);
  10293. a.style.display = "none";
  10294. a.href = url;
  10295. a.download = fileName;
  10296. a.addEventListener("click", function () {
  10297. if (a.parentElement) {
  10298. a.parentElement.removeChild(a);
  10299. }
  10300. });
  10301. a.click();
  10302. window.URL.revokeObjectURL(url);
  10303. };
  10304. /**
  10305. * Captures a screenshot of the current rendering
  10306. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_png
  10307. * @param engine defines the rendering engine
  10308. * @param camera defines the source camera
  10309. * @param size This parameter can be set to a single number or to an object with the
  10310. * following (optional) properties: precision, width, height. If a single number is passed,
  10311. * it will be used for both width and height. If an object is passed, the screenshot size
  10312. * will be derived from the parameters. The precision property is a multiplier allowing
  10313. * rendering at a higher or lower resolution
  10314. * @param successCallback defines the callback receives a single parameter which contains the
  10315. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  10316. * src parameter of an <img> to display it
  10317. * @param mimeType defines the MIME type of the screenshot image (default: image/png).
  10318. * Check your browser for supported MIME types
  10319. */
  10320. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  10321. if (mimeType === void 0) { mimeType = "image/png"; }
  10322. var width;
  10323. var height;
  10324. // If a precision value is specified
  10325. if (size.precision) {
  10326. width = Math.round(engine.getRenderWidth() * size.precision);
  10327. height = Math.round(width / engine.getAspectRatio(camera));
  10328. }
  10329. else if (size.width && size.height) {
  10330. width = size.width;
  10331. height = size.height;
  10332. }
  10333. //If passing only width, computing height to keep display canvas ratio.
  10334. else if (size.width && !size.height) {
  10335. width = size.width;
  10336. height = Math.round(width / engine.getAspectRatio(camera));
  10337. }
  10338. //If passing only height, computing width to keep display canvas ratio.
  10339. else if (size.height && !size.width) {
  10340. height = size.height;
  10341. width = Math.round(height * engine.getAspectRatio(camera));
  10342. }
  10343. //Assuming here that "size" parameter is a number
  10344. else if (!isNaN(size)) {
  10345. height = size;
  10346. width = size;
  10347. }
  10348. else {
  10349. Tools.Error("Invalid 'size' parameter !");
  10350. return;
  10351. }
  10352. if (!screenshotCanvas) {
  10353. screenshotCanvas = document.createElement('canvas');
  10354. }
  10355. screenshotCanvas.width = width;
  10356. screenshotCanvas.height = height;
  10357. var renderContext = screenshotCanvas.getContext("2d");
  10358. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  10359. var newWidth = width;
  10360. var newHeight = newWidth / ratio;
  10361. if (newHeight > height) {
  10362. newHeight = height;
  10363. newWidth = newHeight * ratio;
  10364. }
  10365. var offsetX = Math.max(0, width - newWidth) / 2;
  10366. var offsetY = Math.max(0, height - newHeight) / 2;
  10367. var renderingCanvas = engine.getRenderingCanvas();
  10368. if (renderContext && renderingCanvas) {
  10369. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  10370. }
  10371. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  10372. };
  10373. /**
  10374. * Generates an image screenshot from the specified camera.
  10375. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_png
  10376. * @param engine The engine to use for rendering
  10377. * @param camera The camera to use for rendering
  10378. * @param size This parameter can be set to a single number or to an object with the
  10379. * following (optional) properties: precision, width, height. If a single number is passed,
  10380. * it will be used for both width and height. If an object is passed, the screenshot size
  10381. * will be derived from the parameters. The precision property is a multiplier allowing
  10382. * rendering at a higher or lower resolution
  10383. * @param successCallback The callback receives a single parameter which contains the
  10384. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  10385. * src parameter of an <img> to display it
  10386. * @param mimeType The MIME type of the screenshot image (default: image/png).
  10387. * Check your browser for supported MIME types
  10388. * @param samples Texture samples (default: 1)
  10389. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  10390. * @param fileName A name for for the downloaded file.
  10391. */
  10392. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  10393. if (mimeType === void 0) { mimeType = "image/png"; }
  10394. if (samples === void 0) { samples = 1; }
  10395. if (antialiasing === void 0) { antialiasing = false; }
  10396. var width;
  10397. var height;
  10398. //If a precision value is specified
  10399. if (size.precision) {
  10400. width = Math.round(engine.getRenderWidth() * size.precision);
  10401. height = Math.round(width / engine.getAspectRatio(camera));
  10402. size = { width: width, height: height };
  10403. }
  10404. else if (size.width && size.height) {
  10405. width = size.width;
  10406. height = size.height;
  10407. }
  10408. //If passing only width, computing height to keep display canvas ratio.
  10409. else if (size.width && !size.height) {
  10410. width = size.width;
  10411. height = Math.round(width / engine.getAspectRatio(camera));
  10412. size = { width: width, height: height };
  10413. }
  10414. //If passing only height, computing width to keep display canvas ratio.
  10415. else if (size.height && !size.width) {
  10416. height = size.height;
  10417. width = Math.round(height * engine.getAspectRatio(camera));
  10418. size = { width: width, height: height };
  10419. }
  10420. //Assuming here that "size" parameter is a number
  10421. else if (!isNaN(size)) {
  10422. height = size;
  10423. width = size;
  10424. }
  10425. else {
  10426. Tools.Error("Invalid 'size' parameter !");
  10427. return;
  10428. }
  10429. var scene = camera.getScene();
  10430. var previousCamera = null;
  10431. if (scene.activeCamera !== camera) {
  10432. previousCamera = scene.activeCamera;
  10433. scene.activeCamera = camera;
  10434. }
  10435. // At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  10436. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10437. texture.renderList = null;
  10438. texture.samples = samples;
  10439. if (antialiasing) {
  10440. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  10441. }
  10442. texture.onAfterRenderObservable.add(function () {
  10443. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  10444. });
  10445. scene.incrementRenderId();
  10446. scene.resetCachedMaterial();
  10447. texture.render(true);
  10448. texture.dispose();
  10449. if (previousCamera) {
  10450. scene.activeCamera = previousCamera;
  10451. }
  10452. camera.getProjectionMatrix(true); // Force cache refresh;
  10453. };
  10454. /**
  10455. * Validates if xhr data is correct
  10456. * @param xhr defines the request to validate
  10457. * @param dataType defines the expected data type
  10458. * @returns true if data is correct
  10459. */
  10460. Tools.ValidateXHRData = function (xhr, dataType) {
  10461. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  10462. if (dataType === void 0) { dataType = 7; }
  10463. try {
  10464. if (dataType & 1) {
  10465. if (xhr.responseText && xhr.responseText.length > 0) {
  10466. return true;
  10467. }
  10468. else if (dataType === 1) {
  10469. return false;
  10470. }
  10471. }
  10472. if (dataType & 2) {
  10473. // Check header width and height since there is no "TGA" magic number
  10474. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  10475. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  10476. return true;
  10477. }
  10478. else if (dataType === 2) {
  10479. return false;
  10480. }
  10481. }
  10482. if (dataType & 4) {
  10483. // Check for the "DDS" magic number
  10484. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  10485. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  10486. return true;
  10487. }
  10488. else {
  10489. return false;
  10490. }
  10491. }
  10492. }
  10493. catch (e) {
  10494. // Global protection
  10495. }
  10496. return false;
  10497. };
  10498. /**
  10499. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  10500. * Be aware Math.random() could cause collisions, but:
  10501. * "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"
  10502. * @returns a pseudo random id
  10503. */
  10504. Tools.RandomId = function () {
  10505. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  10506. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  10507. return v.toString(16);
  10508. });
  10509. };
  10510. /**
  10511. * Test if the given uri is a base64 string
  10512. * @param uri The uri to test
  10513. * @return True if the uri is a base64 string or false otherwise
  10514. */
  10515. Tools.IsBase64 = function (uri) {
  10516. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  10517. };
  10518. /**
  10519. * Decode the given base64 uri.
  10520. * @param uri The uri to decode
  10521. * @return The decoded base64 data.
  10522. */
  10523. Tools.DecodeBase64 = function (uri) {
  10524. var decodedString = atob(uri.split(",")[1]);
  10525. var bufferLength = decodedString.length;
  10526. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  10527. for (var i = 0; i < bufferLength; i++) {
  10528. bufferView[i] = decodedString.charCodeAt(i);
  10529. }
  10530. return bufferView.buffer;
  10531. };
  10532. Tools._AddLogEntry = function (entry) {
  10533. Tools._LogCache = entry + Tools._LogCache;
  10534. if (Tools.OnNewCacheEntry) {
  10535. Tools.OnNewCacheEntry(entry);
  10536. }
  10537. };
  10538. Tools._FormatMessage = function (message) {
  10539. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  10540. var date = new Date();
  10541. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  10542. };
  10543. Tools._LogDisabled = function (message) {
  10544. // nothing to do
  10545. };
  10546. Tools._LogEnabled = function (message) {
  10547. var formattedMessage = Tools._FormatMessage(message);
  10548. console.log("BJS - " + formattedMessage);
  10549. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  10550. Tools._AddLogEntry(entry);
  10551. };
  10552. Tools._WarnDisabled = function (message) {
  10553. // nothing to do
  10554. };
  10555. Tools._WarnEnabled = function (message) {
  10556. var formattedMessage = Tools._FormatMessage(message);
  10557. console.warn("BJS - " + formattedMessage);
  10558. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  10559. Tools._AddLogEntry(entry);
  10560. };
  10561. Tools._ErrorDisabled = function (message) {
  10562. // nothing to do
  10563. };
  10564. Tools._ErrorEnabled = function (message) {
  10565. Tools.errorsCount++;
  10566. var formattedMessage = Tools._FormatMessage(message);
  10567. console.error("BJS - " + formattedMessage);
  10568. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  10569. Tools._AddLogEntry(entry);
  10570. };
  10571. Object.defineProperty(Tools, "LogCache", {
  10572. /**
  10573. * Gets current log cache (list of logs)
  10574. */
  10575. get: function () {
  10576. return Tools._LogCache;
  10577. },
  10578. enumerable: true,
  10579. configurable: true
  10580. });
  10581. /**
  10582. * Clears the log cache
  10583. */
  10584. Tools.ClearLogCache = function () {
  10585. Tools._LogCache = "";
  10586. Tools.errorsCount = 0;
  10587. };
  10588. Object.defineProperty(Tools, "LogLevels", {
  10589. /**
  10590. * Sets the current log level (MessageLogLevel / WarningLogLevel / ErrorLogLevel)
  10591. */
  10592. set: function (level) {
  10593. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  10594. Tools.Log = Tools._LogEnabled;
  10595. }
  10596. else {
  10597. Tools.Log = Tools._LogDisabled;
  10598. }
  10599. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  10600. Tools.Warn = Tools._WarnEnabled;
  10601. }
  10602. else {
  10603. Tools.Warn = Tools._WarnDisabled;
  10604. }
  10605. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  10606. Tools.Error = Tools._ErrorEnabled;
  10607. }
  10608. else {
  10609. Tools.Error = Tools._ErrorDisabled;
  10610. }
  10611. },
  10612. enumerable: true,
  10613. configurable: true
  10614. });
  10615. /**
  10616. * Checks if the loaded document was accessed via `file:`-Protocol.
  10617. * @returns boolean
  10618. */
  10619. Tools.IsFileURL = function () {
  10620. return location.protocol === "file:";
  10621. };
  10622. /**
  10623. * Checks if the window object exists
  10624. * @returns true if the window object exists
  10625. */
  10626. Tools.IsWindowObjectExist = function () {
  10627. return (typeof window) !== "undefined";
  10628. };
  10629. Object.defineProperty(Tools, "PerformanceLogLevel", {
  10630. /**
  10631. * Sets the current performance log level
  10632. */
  10633. set: function (level) {
  10634. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  10635. Tools.StartPerformanceCounter = Tools._StartUserMark;
  10636. Tools.EndPerformanceCounter = Tools._EndUserMark;
  10637. return;
  10638. }
  10639. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  10640. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  10641. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  10642. return;
  10643. }
  10644. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  10645. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  10646. },
  10647. enumerable: true,
  10648. configurable: true
  10649. });
  10650. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  10651. };
  10652. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  10653. };
  10654. Tools._StartUserMark = function (counterName, condition) {
  10655. if (condition === void 0) { condition = true; }
  10656. if (!Tools._performance) {
  10657. if (!Tools.IsWindowObjectExist()) {
  10658. return;
  10659. }
  10660. Tools._performance = window.performance;
  10661. }
  10662. if (!condition || !Tools._performance.mark) {
  10663. return;
  10664. }
  10665. Tools._performance.mark(counterName + "-Begin");
  10666. };
  10667. Tools._EndUserMark = function (counterName, condition) {
  10668. if (condition === void 0) { condition = true; }
  10669. if (!condition || !Tools._performance.mark) {
  10670. return;
  10671. }
  10672. Tools._performance.mark(counterName + "-End");
  10673. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  10674. };
  10675. Tools._StartPerformanceConsole = function (counterName, condition) {
  10676. if (condition === void 0) { condition = true; }
  10677. if (!condition) {
  10678. return;
  10679. }
  10680. Tools._StartUserMark(counterName, condition);
  10681. if (console.time) {
  10682. console.time(counterName);
  10683. }
  10684. };
  10685. Tools._EndPerformanceConsole = function (counterName, condition) {
  10686. if (condition === void 0) { condition = true; }
  10687. if (!condition) {
  10688. return;
  10689. }
  10690. Tools._EndUserMark(counterName, condition);
  10691. if (console.time) {
  10692. console.timeEnd(counterName);
  10693. }
  10694. };
  10695. Object.defineProperty(Tools, "Now", {
  10696. /**
  10697. * Gets either window.performance.now() if supported or Date.now() else
  10698. */
  10699. get: function () {
  10700. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  10701. return window.performance.now();
  10702. }
  10703. return Date.now();
  10704. },
  10705. enumerable: true,
  10706. configurable: true
  10707. });
  10708. /**
  10709. * This method will return the name of the class used to create the instance of the given object.
  10710. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  10711. * @param object the object to get the class name from
  10712. * @param isType defines if the object is actually a type
  10713. * @returns the name of the class, will be "object" for a custom data type not using the @className decorator
  10714. */
  10715. Tools.GetClassName = function (object, isType) {
  10716. if (isType === void 0) { isType = false; }
  10717. var name = null;
  10718. if (!isType && object.getClassName) {
  10719. name = object.getClassName();
  10720. }
  10721. else {
  10722. if (object instanceof Object) {
  10723. var classObj = isType ? object : Object.getPrototypeOf(object);
  10724. name = classObj.constructor["__bjsclassName__"];
  10725. }
  10726. if (!name) {
  10727. name = typeof object;
  10728. }
  10729. }
  10730. return name;
  10731. };
  10732. /**
  10733. * Gets the first element of an array satisfying a given predicate
  10734. * @param array defines the array to browse
  10735. * @param predicate defines the predicate to use
  10736. * @returns null if not found or the element
  10737. */
  10738. Tools.First = function (array, predicate) {
  10739. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  10740. var el = array_1[_i];
  10741. if (predicate(el)) {
  10742. return el;
  10743. }
  10744. }
  10745. return null;
  10746. };
  10747. /**
  10748. * This method will return the name of the full name of the class, including its owning module (if any).
  10749. * 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).
  10750. * @param object the object to get the class name from
  10751. * @param isType defines if the object is actually a type
  10752. * @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.
  10753. * @ignorenaming
  10754. */
  10755. Tools.getFullClassName = function (object, isType) {
  10756. if (isType === void 0) { isType = false; }
  10757. var className = null;
  10758. var moduleName = null;
  10759. if (!isType && object.getClassName) {
  10760. className = object.getClassName();
  10761. }
  10762. else {
  10763. if (object instanceof Object) {
  10764. var classObj = isType ? object : Object.getPrototypeOf(object);
  10765. className = classObj.constructor["__bjsclassName__"];
  10766. moduleName = classObj.constructor["__bjsmoduleName__"];
  10767. }
  10768. if (!className) {
  10769. className = typeof object;
  10770. }
  10771. }
  10772. if (!className) {
  10773. return null;
  10774. }
  10775. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  10776. };
  10777. /**
  10778. * Returns a promise that resolves after the given amount of time.
  10779. * @param delay Number of milliseconds to delay
  10780. * @returns Promise that resolves after the given amount of time
  10781. */
  10782. Tools.DelayAsync = function (delay) {
  10783. return new Promise(function (resolve) {
  10784. setTimeout(function () {
  10785. resolve();
  10786. }, delay);
  10787. });
  10788. };
  10789. /**
  10790. * Gets the current gradient from an array of IValueGradient
  10791. * @param ratio defines the current ratio to get
  10792. * @param gradients defines the array of IValueGradient
  10793. * @param updateFunc defines the callback function used to get the final value from the selected gradients
  10794. */
  10795. Tools.GetCurrentGradient = function (ratio, gradients, updateFunc) {
  10796. for (var gradientIndex = 0; gradientIndex < gradients.length - 1; gradientIndex++) {
  10797. var currentGradient = gradients[gradientIndex];
  10798. var nextGradient = gradients[gradientIndex + 1];
  10799. if (ratio >= currentGradient.gradient && ratio <= nextGradient.gradient) {
  10800. var scale = (ratio - currentGradient.gradient) / (nextGradient.gradient - currentGradient.gradient);
  10801. updateFunc(currentGradient, nextGradient, scale);
  10802. return;
  10803. }
  10804. }
  10805. // Use last index if over
  10806. var lastIndex = gradients.length - 1;
  10807. updateFunc(gradients[lastIndex], gradients[lastIndex], 1.0);
  10808. };
  10809. /**
  10810. * Gets or sets the base URL to use to load assets
  10811. */
  10812. Tools.BaseUrl = "";
  10813. /**
  10814. * Gets or sets the retry strategy to apply when an error happens while loading an asset
  10815. */
  10816. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  10817. /**
  10818. * Default behaviour for cors in the application.
  10819. * It can be a string if the expected behavior is identical in the entire app.
  10820. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  10821. */
  10822. Tools.CorsBehavior = "anonymous";
  10823. /**
  10824. * Gets or sets a global variable indicating if fallback texture must be used when a texture cannot be loaded
  10825. * @ignorenaming
  10826. */
  10827. Tools.UseFallbackTexture = true;
  10828. /**
  10829. * Use this object to register external classes like custom textures or material
  10830. * to allow the laoders to instantiate them
  10831. */
  10832. Tools.RegisteredExternalClasses = {};
  10833. /**
  10834. * Texture content used if a texture cannot loaded
  10835. * @ignorenaming
  10836. */
  10837. 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";
  10838. Tools._tmpFloatArray = new Float32Array(1);
  10839. /**
  10840. * Gets or sets a function used to pre-process url before using them to load assets
  10841. */
  10842. Tools.PreprocessUrl = function (url) {
  10843. return url;
  10844. };
  10845. // Logs
  10846. /**
  10847. * No log
  10848. */
  10849. Tools.NoneLogLevel = 0;
  10850. /**
  10851. * Only message logs
  10852. */
  10853. Tools.MessageLogLevel = 1;
  10854. /**
  10855. * Only warning logs
  10856. */
  10857. Tools.WarningLogLevel = 2;
  10858. /**
  10859. * Only error logs
  10860. */
  10861. Tools.ErrorLogLevel = 4;
  10862. /**
  10863. * All logs
  10864. */
  10865. Tools.AllLogLevel = 7;
  10866. Tools._LogCache = "";
  10867. /**
  10868. * Gets a value indicating the number of loading errors
  10869. * @ignorenaming
  10870. */
  10871. Tools.errorsCount = 0;
  10872. /**
  10873. * Log a message to the console
  10874. */
  10875. Tools.Log = Tools._LogEnabled;
  10876. /**
  10877. * Write a warning message to the console
  10878. */
  10879. Tools.Warn = Tools._WarnEnabled;
  10880. /**
  10881. * Write an error message to the console
  10882. */
  10883. Tools.Error = Tools._ErrorEnabled;
  10884. // Performances
  10885. /**
  10886. * No performance log
  10887. */
  10888. Tools.PerformanceNoneLogLevel = 0;
  10889. /**
  10890. * Use user marks to log performance
  10891. */
  10892. Tools.PerformanceUserMarkLogLevel = 1;
  10893. /**
  10894. * Log performance to the console
  10895. */
  10896. Tools.PerformanceConsoleLogLevel = 2;
  10897. /**
  10898. * Starts a performance counter
  10899. */
  10900. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  10901. /**
  10902. * Ends a specific performance coutner
  10903. */
  10904. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  10905. return Tools;
  10906. }());
  10907. BABYLON.Tools = Tools;
  10908. /**
  10909. * This class is used to track a performance counter which is number based.
  10910. * The user has access to many properties which give statistics of different nature.
  10911. *
  10912. * The implementer can track two kinds of Performance Counter: time and count.
  10913. * 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.
  10914. * 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.
  10915. */
  10916. var PerfCounter = /** @class */ (function () {
  10917. /**
  10918. * Creates a new counter
  10919. */
  10920. function PerfCounter() {
  10921. this._startMonitoringTime = 0;
  10922. this._min = 0;
  10923. this._max = 0;
  10924. this._average = 0;
  10925. this._lastSecAverage = 0;
  10926. this._current = 0;
  10927. this._totalValueCount = 0;
  10928. this._totalAccumulated = 0;
  10929. this._lastSecAccumulated = 0;
  10930. this._lastSecTime = 0;
  10931. this._lastSecValueCount = 0;
  10932. }
  10933. Object.defineProperty(PerfCounter.prototype, "min", {
  10934. /**
  10935. * Returns the smallest value ever
  10936. */
  10937. get: function () {
  10938. return this._min;
  10939. },
  10940. enumerable: true,
  10941. configurable: true
  10942. });
  10943. Object.defineProperty(PerfCounter.prototype, "max", {
  10944. /**
  10945. * Returns the biggest value ever
  10946. */
  10947. get: function () {
  10948. return this._max;
  10949. },
  10950. enumerable: true,
  10951. configurable: true
  10952. });
  10953. Object.defineProperty(PerfCounter.prototype, "average", {
  10954. /**
  10955. * Returns the average value since the performance counter is running
  10956. */
  10957. get: function () {
  10958. return this._average;
  10959. },
  10960. enumerable: true,
  10961. configurable: true
  10962. });
  10963. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  10964. /**
  10965. * Returns the average value of the last second the counter was monitored
  10966. */
  10967. get: function () {
  10968. return this._lastSecAverage;
  10969. },
  10970. enumerable: true,
  10971. configurable: true
  10972. });
  10973. Object.defineProperty(PerfCounter.prototype, "current", {
  10974. /**
  10975. * Returns the current value
  10976. */
  10977. get: function () {
  10978. return this._current;
  10979. },
  10980. enumerable: true,
  10981. configurable: true
  10982. });
  10983. Object.defineProperty(PerfCounter.prototype, "total", {
  10984. /**
  10985. * Gets the accumulated total
  10986. */
  10987. get: function () {
  10988. return this._totalAccumulated;
  10989. },
  10990. enumerable: true,
  10991. configurable: true
  10992. });
  10993. Object.defineProperty(PerfCounter.prototype, "count", {
  10994. /**
  10995. * Gets the total value count
  10996. */
  10997. get: function () {
  10998. return this._totalValueCount;
  10999. },
  11000. enumerable: true,
  11001. configurable: true
  11002. });
  11003. /**
  11004. * Call this method to start monitoring a new frame.
  11005. * 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.
  11006. */
  11007. PerfCounter.prototype.fetchNewFrame = function () {
  11008. this._totalValueCount++;
  11009. this._current = 0;
  11010. this._lastSecValueCount++;
  11011. };
  11012. /**
  11013. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  11014. * @param newCount the count value to add to the monitored count
  11015. * @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.
  11016. */
  11017. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  11018. if (!PerfCounter.Enabled) {
  11019. return;
  11020. }
  11021. this._current += newCount;
  11022. if (fetchResult) {
  11023. this._fetchResult();
  11024. }
  11025. };
  11026. /**
  11027. * Start monitoring this performance counter
  11028. */
  11029. PerfCounter.prototype.beginMonitoring = function () {
  11030. if (!PerfCounter.Enabled) {
  11031. return;
  11032. }
  11033. this._startMonitoringTime = Tools.Now;
  11034. };
  11035. /**
  11036. * Compute the time lapsed since the previous beginMonitoring() call.
  11037. * @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
  11038. */
  11039. PerfCounter.prototype.endMonitoring = function (newFrame) {
  11040. if (newFrame === void 0) { newFrame = true; }
  11041. if (!PerfCounter.Enabled) {
  11042. return;
  11043. }
  11044. if (newFrame) {
  11045. this.fetchNewFrame();
  11046. }
  11047. var currentTime = Tools.Now;
  11048. this._current = currentTime - this._startMonitoringTime;
  11049. if (newFrame) {
  11050. this._fetchResult();
  11051. }
  11052. };
  11053. PerfCounter.prototype._fetchResult = function () {
  11054. this._totalAccumulated += this._current;
  11055. this._lastSecAccumulated += this._current;
  11056. // Min/Max update
  11057. this._min = Math.min(this._min, this._current);
  11058. this._max = Math.max(this._max, this._current);
  11059. this._average = this._totalAccumulated / this._totalValueCount;
  11060. // Reset last sec?
  11061. var now = Tools.Now;
  11062. if ((now - this._lastSecTime) > 1000) {
  11063. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  11064. this._lastSecTime = now;
  11065. this._lastSecAccumulated = 0;
  11066. this._lastSecValueCount = 0;
  11067. }
  11068. };
  11069. /**
  11070. * Gets or sets a global boolean to turn on and off all the counters
  11071. */
  11072. PerfCounter.Enabled = true;
  11073. return PerfCounter;
  11074. }());
  11075. BABYLON.PerfCounter = PerfCounter;
  11076. /**
  11077. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  11078. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  11079. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  11080. * @param name The name of the class, case should be preserved
  11081. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  11082. */
  11083. function className(name, module) {
  11084. return function (target) {
  11085. target["__bjsclassName__"] = name;
  11086. target["__bjsmoduleName__"] = (module != null) ? module : null;
  11087. };
  11088. }
  11089. BABYLON.className = className;
  11090. /**
  11091. * An implementation of a loop for asynchronous functions.
  11092. */
  11093. var AsyncLoop = /** @class */ (function () {
  11094. /**
  11095. * Constructor.
  11096. * @param iterations the number of iterations.
  11097. * @param func the function to run each iteration
  11098. * @param successCallback the callback that will be called upon succesful execution
  11099. * @param offset starting offset.
  11100. */
  11101. function AsyncLoop(
  11102. /**
  11103. * Defines the number of iterations for the loop
  11104. */
  11105. iterations, func, successCallback, offset) {
  11106. if (offset === void 0) { offset = 0; }
  11107. this.iterations = iterations;
  11108. this.index = offset - 1;
  11109. this._done = false;
  11110. this._fn = func;
  11111. this._successCallback = successCallback;
  11112. }
  11113. /**
  11114. * Execute the next iteration. Must be called after the last iteration was finished.
  11115. */
  11116. AsyncLoop.prototype.executeNext = function () {
  11117. if (!this._done) {
  11118. if (this.index + 1 < this.iterations) {
  11119. ++this.index;
  11120. this._fn(this);
  11121. }
  11122. else {
  11123. this.breakLoop();
  11124. }
  11125. }
  11126. };
  11127. /**
  11128. * Break the loop and run the success callback.
  11129. */
  11130. AsyncLoop.prototype.breakLoop = function () {
  11131. this._done = true;
  11132. this._successCallback();
  11133. };
  11134. /**
  11135. * Create and run an async loop.
  11136. * @param iterations the number of iterations.
  11137. * @param fn the function to run each iteration
  11138. * @param successCallback the callback that will be called upon succesful execution
  11139. * @param offset starting offset.
  11140. * @returns the created async loop object
  11141. */
  11142. AsyncLoop.Run = function (iterations, fn, successCallback, offset) {
  11143. if (offset === void 0) { offset = 0; }
  11144. var loop = new AsyncLoop(iterations, fn, successCallback, offset);
  11145. loop.executeNext();
  11146. return loop;
  11147. };
  11148. /**
  11149. * A for-loop that will run a given number of iterations synchronous and the rest async.
  11150. * @param iterations total number of iterations
  11151. * @param syncedIterations number of synchronous iterations in each async iteration.
  11152. * @param fn the function to call each iteration.
  11153. * @param callback a success call back that will be called when iterating stops.
  11154. * @param breakFunction a break condition (optional)
  11155. * @param timeout timeout settings for the setTimeout function. default - 0.
  11156. * @returns the created async loop object
  11157. */
  11158. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  11159. if (timeout === void 0) { timeout = 0; }
  11160. return AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  11161. if (breakFunction && breakFunction())
  11162. loop.breakLoop();
  11163. else {
  11164. setTimeout(function () {
  11165. for (var i = 0; i < syncedIterations; ++i) {
  11166. var iteration = (loop.index * syncedIterations) + i;
  11167. if (iteration >= iterations)
  11168. break;
  11169. fn(iteration);
  11170. if (breakFunction && breakFunction()) {
  11171. loop.breakLoop();
  11172. break;
  11173. }
  11174. }
  11175. loop.executeNext();
  11176. }, timeout);
  11177. }
  11178. }, callback);
  11179. };
  11180. return AsyncLoop;
  11181. }());
  11182. BABYLON.AsyncLoop = AsyncLoop;
  11183. })(BABYLON || (BABYLON = {}));
  11184. //# sourceMappingURL=babylon.tools.js.map
  11185. var BABYLON;
  11186. (function (BABYLON) {
  11187. var PromiseStates;
  11188. (function (PromiseStates) {
  11189. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  11190. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  11191. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  11192. })(PromiseStates || (PromiseStates = {}));
  11193. var FulFillmentAgregator = /** @class */ (function () {
  11194. function FulFillmentAgregator() {
  11195. this.count = 0;
  11196. this.target = 0;
  11197. this.results = [];
  11198. }
  11199. return FulFillmentAgregator;
  11200. }());
  11201. var InternalPromise = /** @class */ (function () {
  11202. function InternalPromise(resolver) {
  11203. var _this = this;
  11204. this._state = PromiseStates.Pending;
  11205. this._children = new Array();
  11206. this._rejectWasConsumed = false;
  11207. if (!resolver) {
  11208. return;
  11209. }
  11210. try {
  11211. resolver(function (value) {
  11212. _this._resolve(value);
  11213. }, function (reason) {
  11214. _this._reject(reason);
  11215. });
  11216. }
  11217. catch (e) {
  11218. this._reject(e);
  11219. }
  11220. }
  11221. Object.defineProperty(InternalPromise.prototype, "_result", {
  11222. get: function () {
  11223. return this._resultValue;
  11224. },
  11225. set: function (value) {
  11226. this._resultValue = value;
  11227. if (this._parent && this._parent._result === undefined) {
  11228. this._parent._result = value;
  11229. }
  11230. },
  11231. enumerable: true,
  11232. configurable: true
  11233. });
  11234. InternalPromise.prototype.catch = function (onRejected) {
  11235. return this.then(undefined, onRejected);
  11236. };
  11237. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  11238. var _this = this;
  11239. var newPromise = new InternalPromise();
  11240. newPromise._onFulfilled = onFulfilled;
  11241. newPromise._onRejected = onRejected;
  11242. // Composition
  11243. this._children.push(newPromise);
  11244. newPromise._parent = this;
  11245. if (this._state !== PromiseStates.Pending) {
  11246. BABYLON.Tools.SetImmediate(function () {
  11247. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  11248. var returnedValue = newPromise._resolve(_this._result);
  11249. if (returnedValue !== undefined && returnedValue !== null) {
  11250. if (returnedValue._state !== undefined) {
  11251. var returnedPromise = returnedValue;
  11252. newPromise._children.push(returnedPromise);
  11253. returnedPromise._parent = newPromise;
  11254. newPromise = returnedPromise;
  11255. }
  11256. else {
  11257. newPromise._result = returnedValue;
  11258. }
  11259. }
  11260. }
  11261. else {
  11262. newPromise._reject(_this._reason);
  11263. }
  11264. });
  11265. }
  11266. return newPromise;
  11267. };
  11268. InternalPromise.prototype._moveChildren = function (children) {
  11269. var _this = this;
  11270. var _a;
  11271. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  11272. this._children.forEach(function (child) {
  11273. child._parent = _this;
  11274. });
  11275. if (this._state === PromiseStates.Fulfilled) {
  11276. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  11277. var child = _b[_i];
  11278. child._resolve(this._result);
  11279. }
  11280. }
  11281. else if (this._state === PromiseStates.Rejected) {
  11282. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  11283. var child = _d[_c];
  11284. child._reject(this._reason);
  11285. }
  11286. }
  11287. };
  11288. InternalPromise.prototype._resolve = function (value) {
  11289. try {
  11290. this._state = PromiseStates.Fulfilled;
  11291. var returnedValue = null;
  11292. if (this._onFulfilled) {
  11293. returnedValue = this._onFulfilled(value);
  11294. }
  11295. if (returnedValue !== undefined && returnedValue !== null) {
  11296. if (returnedValue._state !== undefined) {
  11297. // Transmit children
  11298. var returnedPromise = returnedValue;
  11299. returnedPromise._parent = this;
  11300. returnedPromise._moveChildren(this._children);
  11301. value = returnedPromise._result;
  11302. }
  11303. else {
  11304. value = returnedValue;
  11305. }
  11306. }
  11307. this._result = value;
  11308. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  11309. var child = _a[_i];
  11310. child._resolve(value);
  11311. }
  11312. this._children.length = 0;
  11313. delete this._onFulfilled;
  11314. delete this._onRejected;
  11315. }
  11316. catch (e) {
  11317. this._reject(e, true);
  11318. }
  11319. };
  11320. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  11321. if (onLocalThrow === void 0) { onLocalThrow = false; }
  11322. this._state = PromiseStates.Rejected;
  11323. this._reason = reason;
  11324. if (this._onRejected && !onLocalThrow) {
  11325. try {
  11326. this._onRejected(reason);
  11327. this._rejectWasConsumed = true;
  11328. }
  11329. catch (e) {
  11330. reason = e;
  11331. }
  11332. }
  11333. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  11334. var child = _a[_i];
  11335. if (this._rejectWasConsumed) {
  11336. child._resolve(null);
  11337. }
  11338. else {
  11339. child._reject(reason);
  11340. }
  11341. }
  11342. this._children.length = 0;
  11343. delete this._onFulfilled;
  11344. delete this._onRejected;
  11345. };
  11346. InternalPromise.resolve = function (value) {
  11347. var newPromise = new InternalPromise();
  11348. newPromise._resolve(value);
  11349. return newPromise;
  11350. };
  11351. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  11352. promise.then(function (value) {
  11353. agregator.results[index] = value;
  11354. agregator.count++;
  11355. if (agregator.count === agregator.target) {
  11356. agregator.rootPromise._resolve(agregator.results);
  11357. }
  11358. return null;
  11359. }, function (reason) {
  11360. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  11361. agregator.rootPromise._reject(reason);
  11362. }
  11363. });
  11364. };
  11365. InternalPromise.all = function (promises) {
  11366. var newPromise = new InternalPromise();
  11367. var agregator = new FulFillmentAgregator();
  11368. agregator.target = promises.length;
  11369. agregator.rootPromise = newPromise;
  11370. if (promises.length) {
  11371. for (var index = 0; index < promises.length; index++) {
  11372. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  11373. }
  11374. }
  11375. else {
  11376. newPromise._resolve([]);
  11377. }
  11378. return newPromise;
  11379. };
  11380. InternalPromise.race = function (promises) {
  11381. var newPromise = new InternalPromise();
  11382. if (promises.length) {
  11383. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  11384. var promise = promises_1[_i];
  11385. promise.then(function (value) {
  11386. if (newPromise) {
  11387. newPromise._resolve(value);
  11388. newPromise = null;
  11389. }
  11390. return null;
  11391. }, function (reason) {
  11392. if (newPromise) {
  11393. newPromise._reject(reason);
  11394. newPromise = null;
  11395. }
  11396. });
  11397. }
  11398. }
  11399. return newPromise;
  11400. };
  11401. return InternalPromise;
  11402. }());
  11403. /**
  11404. * Helper class that provides a small promise polyfill
  11405. */
  11406. var PromisePolyfill = /** @class */ (function () {
  11407. function PromisePolyfill() {
  11408. }
  11409. /**
  11410. * Static function used to check if the polyfill is required
  11411. * If this is the case then the function will inject the polyfill to window.Promise
  11412. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  11413. */
  11414. PromisePolyfill.Apply = function (force) {
  11415. if (force === void 0) { force = false; }
  11416. if (force || typeof Promise === 'undefined') {
  11417. var root = window;
  11418. root.Promise = InternalPromise;
  11419. }
  11420. };
  11421. return PromisePolyfill;
  11422. }());
  11423. BABYLON.PromisePolyfill = PromisePolyfill;
  11424. })(BABYLON || (BABYLON = {}));
  11425. //# sourceMappingURL=babylon.promise.js.map
  11426. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  11427. var BABYLON;
  11428. (function (BABYLON) {
  11429. /**
  11430. * Helper class to push actions to a pool of workers.
  11431. */
  11432. var WorkerPool = /** @class */ (function () {
  11433. /**
  11434. * Constructor
  11435. * @param workers Array of workers to use for actions
  11436. */
  11437. function WorkerPool(workers) {
  11438. this._pendingActions = new Array();
  11439. this._workerInfos = workers.map(function (worker) { return ({
  11440. worker: worker,
  11441. active: false
  11442. }); });
  11443. }
  11444. /**
  11445. * Terminates all workers and clears any pending actions.
  11446. */
  11447. WorkerPool.prototype.dispose = function () {
  11448. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  11449. var workerInfo = _a[_i];
  11450. workerInfo.worker.terminate();
  11451. }
  11452. delete this._workerInfos;
  11453. delete this._pendingActions;
  11454. };
  11455. /**
  11456. * Pushes an action to the worker pool. If all the workers are active, the action will be
  11457. * pended until a worker has completed its action.
  11458. * @param action The action to perform. Call onComplete when the action is complete.
  11459. */
  11460. WorkerPool.prototype.push = function (action) {
  11461. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  11462. var workerInfo = _a[_i];
  11463. if (!workerInfo.active) {
  11464. this._execute(workerInfo, action);
  11465. return;
  11466. }
  11467. }
  11468. this._pendingActions.push(action);
  11469. };
  11470. WorkerPool.prototype._execute = function (workerInfo, action) {
  11471. var _this = this;
  11472. workerInfo.active = true;
  11473. action(workerInfo.worker, function () {
  11474. workerInfo.active = false;
  11475. var nextAction = _this._pendingActions.shift();
  11476. if (nextAction) {
  11477. _this._execute(workerInfo, nextAction);
  11478. }
  11479. });
  11480. };
  11481. return WorkerPool;
  11482. }());
  11483. BABYLON.WorkerPool = WorkerPool;
  11484. })(BABYLON || (BABYLON = {}));
  11485. //# sourceMappingURL=babylon.workerPool.js.map
  11486. var BABYLON;
  11487. (function (BABYLON) {
  11488. /**
  11489. * @hidden
  11490. **/
  11491. var _AlphaState = /** @class */ (function () {
  11492. /**
  11493. * Initializes the state.
  11494. */
  11495. function _AlphaState() {
  11496. this._isAlphaBlendDirty = false;
  11497. this._isBlendFunctionParametersDirty = false;
  11498. this._isBlendEquationParametersDirty = false;
  11499. this._isBlendConstantsDirty = false;
  11500. this._alphaBlend = false;
  11501. this._blendFunctionParameters = new Array(4);
  11502. this._blendEquationParameters = new Array(2);
  11503. this._blendConstants = new Array(4);
  11504. this.reset();
  11505. }
  11506. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  11507. get: function () {
  11508. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  11509. },
  11510. enumerable: true,
  11511. configurable: true
  11512. });
  11513. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  11514. get: function () {
  11515. return this._alphaBlend;
  11516. },
  11517. set: function (value) {
  11518. if (this._alphaBlend === value) {
  11519. return;
  11520. }
  11521. this._alphaBlend = value;
  11522. this._isAlphaBlendDirty = true;
  11523. },
  11524. enumerable: true,
  11525. configurable: true
  11526. });
  11527. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  11528. if (this._blendConstants[0] === r &&
  11529. this._blendConstants[1] === g &&
  11530. this._blendConstants[2] === b &&
  11531. this._blendConstants[3] === a) {
  11532. return;
  11533. }
  11534. this._blendConstants[0] = r;
  11535. this._blendConstants[1] = g;
  11536. this._blendConstants[2] = b;
  11537. this._blendConstants[3] = a;
  11538. this._isBlendConstantsDirty = true;
  11539. };
  11540. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  11541. if (this._blendFunctionParameters[0] === value0 &&
  11542. this._blendFunctionParameters[1] === value1 &&
  11543. this._blendFunctionParameters[2] === value2 &&
  11544. this._blendFunctionParameters[3] === value3) {
  11545. return;
  11546. }
  11547. this._blendFunctionParameters[0] = value0;
  11548. this._blendFunctionParameters[1] = value1;
  11549. this._blendFunctionParameters[2] = value2;
  11550. this._blendFunctionParameters[3] = value3;
  11551. this._isBlendFunctionParametersDirty = true;
  11552. };
  11553. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  11554. if (this._blendEquationParameters[0] === rgb &&
  11555. this._blendEquationParameters[1] === alpha) {
  11556. return;
  11557. }
  11558. this._blendEquationParameters[0] = rgb;
  11559. this._blendEquationParameters[1] = alpha;
  11560. this._isBlendEquationParametersDirty = true;
  11561. };
  11562. _AlphaState.prototype.reset = function () {
  11563. this._alphaBlend = false;
  11564. this._blendFunctionParameters[0] = null;
  11565. this._blendFunctionParameters[1] = null;
  11566. this._blendFunctionParameters[2] = null;
  11567. this._blendFunctionParameters[3] = null;
  11568. this._blendEquationParameters[0] = null;
  11569. this._blendEquationParameters[1] = null;
  11570. this._blendConstants[0] = null;
  11571. this._blendConstants[1] = null;
  11572. this._blendConstants[2] = null;
  11573. this._blendConstants[3] = null;
  11574. this._isAlphaBlendDirty = true;
  11575. this._isBlendFunctionParametersDirty = false;
  11576. this._isBlendEquationParametersDirty = false;
  11577. this._isBlendConstantsDirty = false;
  11578. };
  11579. _AlphaState.prototype.apply = function (gl) {
  11580. if (!this.isDirty) {
  11581. return;
  11582. }
  11583. // Alpha blend
  11584. if (this._isAlphaBlendDirty) {
  11585. if (this._alphaBlend) {
  11586. gl.enable(gl.BLEND);
  11587. }
  11588. else {
  11589. gl.disable(gl.BLEND);
  11590. }
  11591. this._isAlphaBlendDirty = false;
  11592. }
  11593. // Alpha function
  11594. if (this._isBlendFunctionParametersDirty) {
  11595. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  11596. this._isBlendFunctionParametersDirty = false;
  11597. }
  11598. // Alpha equation
  11599. if (this._isBlendEquationParametersDirty) {
  11600. gl.blendEquationSeparate(this._blendEquationParameters[0], this._blendEquationParameters[1]);
  11601. this._isBlendEquationParametersDirty = false;
  11602. }
  11603. // Constants
  11604. if (this._isBlendConstantsDirty) {
  11605. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  11606. this._isBlendConstantsDirty = false;
  11607. }
  11608. };
  11609. return _AlphaState;
  11610. }());
  11611. BABYLON._AlphaState = _AlphaState;
  11612. })(BABYLON || (BABYLON = {}));
  11613. //# sourceMappingURL=babylon.alphaCullingState.js.map
  11614. var BABYLON;
  11615. (function (BABYLON) {
  11616. /**
  11617. * @hidden
  11618. **/
  11619. var _DepthCullingState = /** @class */ (function () {
  11620. /**
  11621. * Initializes the state.
  11622. */
  11623. function _DepthCullingState() {
  11624. this._isDepthTestDirty = false;
  11625. this._isDepthMaskDirty = false;
  11626. this._isDepthFuncDirty = false;
  11627. this._isCullFaceDirty = false;
  11628. this._isCullDirty = false;
  11629. this._isZOffsetDirty = false;
  11630. this._isFrontFaceDirty = false;
  11631. this.reset();
  11632. }
  11633. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  11634. get: function () {
  11635. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  11636. },
  11637. enumerable: true,
  11638. configurable: true
  11639. });
  11640. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  11641. get: function () {
  11642. return this._zOffset;
  11643. },
  11644. set: function (value) {
  11645. if (this._zOffset === value) {
  11646. return;
  11647. }
  11648. this._zOffset = value;
  11649. this._isZOffsetDirty = true;
  11650. },
  11651. enumerable: true,
  11652. configurable: true
  11653. });
  11654. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  11655. get: function () {
  11656. return this._cullFace;
  11657. },
  11658. set: function (value) {
  11659. if (this._cullFace === value) {
  11660. return;
  11661. }
  11662. this._cullFace = value;
  11663. this._isCullFaceDirty = true;
  11664. },
  11665. enumerable: true,
  11666. configurable: true
  11667. });
  11668. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  11669. get: function () {
  11670. return this._cull;
  11671. },
  11672. set: function (value) {
  11673. if (this._cull === value) {
  11674. return;
  11675. }
  11676. this._cull = value;
  11677. this._isCullDirty = true;
  11678. },
  11679. enumerable: true,
  11680. configurable: true
  11681. });
  11682. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  11683. get: function () {
  11684. return this._depthFunc;
  11685. },
  11686. set: function (value) {
  11687. if (this._depthFunc === value) {
  11688. return;
  11689. }
  11690. this._depthFunc = value;
  11691. this._isDepthFuncDirty = true;
  11692. },
  11693. enumerable: true,
  11694. configurable: true
  11695. });
  11696. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  11697. get: function () {
  11698. return this._depthMask;
  11699. },
  11700. set: function (value) {
  11701. if (this._depthMask === value) {
  11702. return;
  11703. }
  11704. this._depthMask = value;
  11705. this._isDepthMaskDirty = true;
  11706. },
  11707. enumerable: true,
  11708. configurable: true
  11709. });
  11710. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  11711. get: function () {
  11712. return this._depthTest;
  11713. },
  11714. set: function (value) {
  11715. if (this._depthTest === value) {
  11716. return;
  11717. }
  11718. this._depthTest = value;
  11719. this._isDepthTestDirty = true;
  11720. },
  11721. enumerable: true,
  11722. configurable: true
  11723. });
  11724. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  11725. get: function () {
  11726. return this._frontFace;
  11727. },
  11728. set: function (value) {
  11729. if (this._frontFace === value) {
  11730. return;
  11731. }
  11732. this._frontFace = value;
  11733. this._isFrontFaceDirty = true;
  11734. },
  11735. enumerable: true,
  11736. configurable: true
  11737. });
  11738. _DepthCullingState.prototype.reset = function () {
  11739. this._depthMask = true;
  11740. this._depthTest = true;
  11741. this._depthFunc = null;
  11742. this._cullFace = null;
  11743. this._cull = null;
  11744. this._zOffset = 0;
  11745. this._frontFace = null;
  11746. this._isDepthTestDirty = true;
  11747. this._isDepthMaskDirty = true;
  11748. this._isDepthFuncDirty = false;
  11749. this._isCullFaceDirty = false;
  11750. this._isCullDirty = false;
  11751. this._isZOffsetDirty = false;
  11752. this._isFrontFaceDirty = false;
  11753. };
  11754. _DepthCullingState.prototype.apply = function (gl) {
  11755. if (!this.isDirty) {
  11756. return;
  11757. }
  11758. // Cull
  11759. if (this._isCullDirty) {
  11760. if (this.cull) {
  11761. gl.enable(gl.CULL_FACE);
  11762. }
  11763. else {
  11764. gl.disable(gl.CULL_FACE);
  11765. }
  11766. this._isCullDirty = false;
  11767. }
  11768. // Cull face
  11769. if (this._isCullFaceDirty) {
  11770. gl.cullFace(this.cullFace);
  11771. this._isCullFaceDirty = false;
  11772. }
  11773. // Depth mask
  11774. if (this._isDepthMaskDirty) {
  11775. gl.depthMask(this.depthMask);
  11776. this._isDepthMaskDirty = false;
  11777. }
  11778. // Depth test
  11779. if (this._isDepthTestDirty) {
  11780. if (this.depthTest) {
  11781. gl.enable(gl.DEPTH_TEST);
  11782. }
  11783. else {
  11784. gl.disable(gl.DEPTH_TEST);
  11785. }
  11786. this._isDepthTestDirty = false;
  11787. }
  11788. // Depth func
  11789. if (this._isDepthFuncDirty) {
  11790. gl.depthFunc(this.depthFunc);
  11791. this._isDepthFuncDirty = false;
  11792. }
  11793. // zOffset
  11794. if (this._isZOffsetDirty) {
  11795. if (this.zOffset) {
  11796. gl.enable(gl.POLYGON_OFFSET_FILL);
  11797. gl.polygonOffset(this.zOffset, 0);
  11798. }
  11799. else {
  11800. gl.disable(gl.POLYGON_OFFSET_FILL);
  11801. }
  11802. this._isZOffsetDirty = false;
  11803. }
  11804. // Front face
  11805. if (this._isFrontFaceDirty) {
  11806. gl.frontFace(this.frontFace);
  11807. this._isFrontFaceDirty = false;
  11808. }
  11809. };
  11810. return _DepthCullingState;
  11811. }());
  11812. BABYLON._DepthCullingState = _DepthCullingState;
  11813. })(BABYLON || (BABYLON = {}));
  11814. //# sourceMappingURL=babylon.depthCullingState.js.map
  11815. var BABYLON;
  11816. (function (BABYLON) {
  11817. /**
  11818. * @hidden
  11819. **/
  11820. var _StencilState = /** @class */ (function () {
  11821. function _StencilState() {
  11822. this._isStencilTestDirty = false;
  11823. this._isStencilMaskDirty = false;
  11824. this._isStencilFuncDirty = false;
  11825. this._isStencilOpDirty = false;
  11826. this.reset();
  11827. }
  11828. Object.defineProperty(_StencilState.prototype, "isDirty", {
  11829. get: function () {
  11830. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  11831. },
  11832. enumerable: true,
  11833. configurable: true
  11834. });
  11835. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  11836. get: function () {
  11837. return this._stencilFunc;
  11838. },
  11839. set: function (value) {
  11840. if (this._stencilFunc === value) {
  11841. return;
  11842. }
  11843. this._stencilFunc = value;
  11844. this._isStencilFuncDirty = true;
  11845. },
  11846. enumerable: true,
  11847. configurable: true
  11848. });
  11849. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  11850. get: function () {
  11851. return this._stencilFuncRef;
  11852. },
  11853. set: function (value) {
  11854. if (this._stencilFuncRef === value) {
  11855. return;
  11856. }
  11857. this._stencilFuncRef = value;
  11858. this._isStencilFuncDirty = true;
  11859. },
  11860. enumerable: true,
  11861. configurable: true
  11862. });
  11863. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  11864. get: function () {
  11865. return this._stencilFuncMask;
  11866. },
  11867. set: function (value) {
  11868. if (this._stencilFuncMask === value) {
  11869. return;
  11870. }
  11871. this._stencilFuncMask = value;
  11872. this._isStencilFuncDirty = true;
  11873. },
  11874. enumerable: true,
  11875. configurable: true
  11876. });
  11877. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  11878. get: function () {
  11879. return this._stencilOpStencilFail;
  11880. },
  11881. set: function (value) {
  11882. if (this._stencilOpStencilFail === value) {
  11883. return;
  11884. }
  11885. this._stencilOpStencilFail = value;
  11886. this._isStencilOpDirty = true;
  11887. },
  11888. enumerable: true,
  11889. configurable: true
  11890. });
  11891. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  11892. get: function () {
  11893. return this._stencilOpDepthFail;
  11894. },
  11895. set: function (value) {
  11896. if (this._stencilOpDepthFail === value) {
  11897. return;
  11898. }
  11899. this._stencilOpDepthFail = value;
  11900. this._isStencilOpDirty = true;
  11901. },
  11902. enumerable: true,
  11903. configurable: true
  11904. });
  11905. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  11906. get: function () {
  11907. return this._stencilOpStencilDepthPass;
  11908. },
  11909. set: function (value) {
  11910. if (this._stencilOpStencilDepthPass === value) {
  11911. return;
  11912. }
  11913. this._stencilOpStencilDepthPass = value;
  11914. this._isStencilOpDirty = true;
  11915. },
  11916. enumerable: true,
  11917. configurable: true
  11918. });
  11919. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  11920. get: function () {
  11921. return this._stencilMask;
  11922. },
  11923. set: function (value) {
  11924. if (this._stencilMask === value) {
  11925. return;
  11926. }
  11927. this._stencilMask = value;
  11928. this._isStencilMaskDirty = true;
  11929. },
  11930. enumerable: true,
  11931. configurable: true
  11932. });
  11933. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  11934. get: function () {
  11935. return this._stencilTest;
  11936. },
  11937. set: function (value) {
  11938. if (this._stencilTest === value) {
  11939. return;
  11940. }
  11941. this._stencilTest = value;
  11942. this._isStencilTestDirty = true;
  11943. },
  11944. enumerable: true,
  11945. configurable: true
  11946. });
  11947. _StencilState.prototype.reset = function () {
  11948. this._stencilTest = false;
  11949. this._stencilMask = 0xFF;
  11950. this._stencilFunc = BABYLON.Engine.ALWAYS;
  11951. this._stencilFuncRef = 1;
  11952. this._stencilFuncMask = 0xFF;
  11953. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  11954. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  11955. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  11956. this._isStencilTestDirty = true;
  11957. this._isStencilMaskDirty = true;
  11958. this._isStencilFuncDirty = true;
  11959. this._isStencilOpDirty = true;
  11960. };
  11961. _StencilState.prototype.apply = function (gl) {
  11962. if (!this.isDirty) {
  11963. return;
  11964. }
  11965. // Stencil test
  11966. if (this._isStencilTestDirty) {
  11967. if (this.stencilTest) {
  11968. gl.enable(gl.STENCIL_TEST);
  11969. }
  11970. else {
  11971. gl.disable(gl.STENCIL_TEST);
  11972. }
  11973. this._isStencilTestDirty = false;
  11974. }
  11975. // Stencil mask
  11976. if (this._isStencilMaskDirty) {
  11977. gl.stencilMask(this.stencilMask);
  11978. this._isStencilMaskDirty = false;
  11979. }
  11980. // Stencil func
  11981. if (this._isStencilFuncDirty) {
  11982. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  11983. this._isStencilFuncDirty = false;
  11984. }
  11985. // Stencil op
  11986. if (this._isStencilOpDirty) {
  11987. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  11988. this._isStencilOpDirty = false;
  11989. }
  11990. };
  11991. return _StencilState;
  11992. }());
  11993. BABYLON._StencilState = _StencilState;
  11994. })(BABYLON || (BABYLON = {}));
  11995. //# sourceMappingURL=babylon.stencilState.js.map
  11996. var __assign = (this && this.__assign) || function () {
  11997. __assign = Object.assign || function(t) {
  11998. for (var s, i = 1, n = arguments.length; i < n; i++) {
  11999. s = arguments[i];
  12000. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  12001. t[p] = s[p];
  12002. }
  12003. return t;
  12004. };
  12005. return __assign.apply(this, arguments);
  12006. };
  12007. var BABYLON;
  12008. (function (BABYLON) {
  12009. /**
  12010. * Keeps track of all the buffer info used in engine.
  12011. */
  12012. var BufferPointer = /** @class */ (function () {
  12013. function BufferPointer() {
  12014. }
  12015. return BufferPointer;
  12016. }());
  12017. /**
  12018. * Interface for attribute information associated with buffer instanciation
  12019. */
  12020. var InstancingAttributeInfo = /** @class */ (function () {
  12021. function InstancingAttributeInfo() {
  12022. }
  12023. return InstancingAttributeInfo;
  12024. }());
  12025. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  12026. /**
  12027. * Define options used to create a render target texture
  12028. */
  12029. var RenderTargetCreationOptions = /** @class */ (function () {
  12030. function RenderTargetCreationOptions() {
  12031. }
  12032. return RenderTargetCreationOptions;
  12033. }());
  12034. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  12035. /**
  12036. * Define options used to create a depth texture
  12037. */
  12038. var DepthTextureCreationOptions = /** @class */ (function () {
  12039. function DepthTextureCreationOptions() {
  12040. }
  12041. return DepthTextureCreationOptions;
  12042. }());
  12043. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  12044. /**
  12045. * Class used to describe the capabilities of the engine relatively to the current browser
  12046. */
  12047. var EngineCapabilities = /** @class */ (function () {
  12048. function EngineCapabilities() {
  12049. }
  12050. return EngineCapabilities;
  12051. }());
  12052. BABYLON.EngineCapabilities = EngineCapabilities;
  12053. /**
  12054. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  12055. */
  12056. var Engine = /** @class */ (function () {
  12057. /**
  12058. * Creates a new engine
  12059. * @param canvasOrContext defines the canvas or WebGL context to use for rendering. If you provide a WebGL context, Babylon.js will not hook events on the canvas (like pointers, keyboards, etc...) so no event observables will be available. This is mostly used when Babylon.js is used as a plugin on a system which alreay used the WebGL context
  12060. * @param antialias defines enable antialiasing (default: false)
  12061. * @param options defines further options to be sent to the getContext() function
  12062. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  12063. */
  12064. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  12065. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  12066. var _this = this;
  12067. // Public members
  12068. /**
  12069. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  12070. */
  12071. this.forcePOTTextures = false;
  12072. /**
  12073. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  12074. */
  12075. this.isFullscreen = false;
  12076. /**
  12077. * Gets a boolean indicating if the pointer is currently locked
  12078. */
  12079. this.isPointerLock = false;
  12080. /**
  12081. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  12082. */
  12083. this.cullBackFaces = true;
  12084. /**
  12085. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  12086. */
  12087. this.renderEvenInBackground = true;
  12088. /**
  12089. * Gets or sets a boolean indicating that cache can be kept between frames
  12090. */
  12091. this.preventCacheWipeBetweenFrames = false;
  12092. /**
  12093. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  12094. **/
  12095. this.enableOfflineSupport = false;
  12096. /**
  12097. * 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)
  12098. **/
  12099. this.disableManifestCheck = false;
  12100. /**
  12101. * Gets the list of created scenes
  12102. */
  12103. this.scenes = new Array();
  12104. /**
  12105. * Gets the list of created postprocesses
  12106. */
  12107. this.postProcesses = new Array();
  12108. /** Gets or sets a boolean indicating if the engine should validate programs after compilation */
  12109. this.validateShaderPrograms = false;
  12110. // Observables
  12111. /**
  12112. * Observable event triggered each time the rendering canvas is resized
  12113. */
  12114. this.onResizeObservable = new BABYLON.Observable();
  12115. /**
  12116. * Observable event triggered each time the canvas loses focus
  12117. */
  12118. this.onCanvasBlurObservable = new BABYLON.Observable();
  12119. /**
  12120. * Observable event triggered each time the canvas gains focus
  12121. */
  12122. this.onCanvasFocusObservable = new BABYLON.Observable();
  12123. /**
  12124. * Observable event triggered each time the canvas receives pointerout event
  12125. */
  12126. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  12127. /**
  12128. * Observable event triggered before each texture is initialized
  12129. */
  12130. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  12131. //WebVR
  12132. this._vrDisplay = undefined;
  12133. this._vrSupported = false;
  12134. this._vrExclusivePointerMode = false;
  12135. // Uniform buffers list
  12136. /**
  12137. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  12138. */
  12139. this.disableUniformBuffers = false;
  12140. /** @hidden */
  12141. this._uniformBuffers = new Array();
  12142. // Observables
  12143. /**
  12144. * Observable raised when the engine begins a new frame
  12145. */
  12146. this.onBeginFrameObservable = new BABYLON.Observable();
  12147. /**
  12148. * Observable raised when the engine ends the current frame
  12149. */
  12150. this.onEndFrameObservable = new BABYLON.Observable();
  12151. /**
  12152. * Observable raised when the engine is about to compile a shader
  12153. */
  12154. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  12155. /**
  12156. * Observable raised when the engine has jsut compiled a shader
  12157. */
  12158. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  12159. this._windowIsBackground = false;
  12160. this._webGLVersion = 1.0;
  12161. /** @hidden */
  12162. this._badOS = false;
  12163. /** @hidden */
  12164. this._badDesktopOS = false;
  12165. /**
  12166. * Gets or sets a value indicating if we want to disable texture binding optmization.
  12167. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  12168. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  12169. */
  12170. this.disableTextureBindingOptimization = false;
  12171. /**
  12172. * Observable signaled when VR display mode changes
  12173. */
  12174. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  12175. /**
  12176. * Observable signaled when VR request present is complete
  12177. */
  12178. this.onVRRequestPresentComplete = new BABYLON.Observable();
  12179. /**
  12180. * Observable signaled when VR request present starts
  12181. */
  12182. this.onVRRequestPresentStart = new BABYLON.Observable();
  12183. this._colorWrite = true;
  12184. /** @hidden */
  12185. this._drawCalls = new BABYLON.PerfCounter();
  12186. /** @hidden */
  12187. this._textureCollisions = new BABYLON.PerfCounter();
  12188. this._renderingQueueLaunched = false;
  12189. this._activeRenderLoops = new Array();
  12190. // Deterministic lockstepMaxSteps
  12191. this._deterministicLockstep = false;
  12192. this._lockstepMaxSteps = 4;
  12193. // Lost context
  12194. /**
  12195. * Observable signaled when a context lost event is raised
  12196. */
  12197. this.onContextLostObservable = new BABYLON.Observable();
  12198. /**
  12199. * Observable signaled when a context restored event is raised
  12200. */
  12201. this.onContextRestoredObservable = new BABYLON.Observable();
  12202. this._contextWasLost = false;
  12203. this._doNotHandleContextLost = false;
  12204. // FPS
  12205. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  12206. this._fps = 60;
  12207. this._deltaTime = 0;
  12208. /**
  12209. * Turn this value on if you want to pause FPS computation when in background
  12210. */
  12211. this.disablePerformanceMonitorInBackground = false;
  12212. // States
  12213. /** @hidden */
  12214. this._depthCullingState = new BABYLON._DepthCullingState();
  12215. /** @hidden */
  12216. this._stencilState = new BABYLON._StencilState();
  12217. /** @hidden */
  12218. this._alphaState = new BABYLON._AlphaState();
  12219. /** @hidden */
  12220. this._alphaMode = Engine.ALPHA_DISABLE;
  12221. // Cache
  12222. this._internalTexturesCache = new Array();
  12223. /** @hidden */
  12224. this._activeChannel = 0;
  12225. this._currentTextureChannel = -1;
  12226. /** @hidden */
  12227. this._boundTexturesCache = {};
  12228. this._compiledEffects = {};
  12229. this._vertexAttribArraysEnabled = [];
  12230. this._uintIndicesCurrentlySet = false;
  12231. this._currentBoundBuffer = new Array();
  12232. /** @hidden */
  12233. this._currentFramebuffer = null;
  12234. this._currentBufferPointers = new Array();
  12235. this._currentInstanceLocations = new Array();
  12236. this._currentInstanceBuffers = new Array();
  12237. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  12238. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  12239. this._vaoRecordInProgress = false;
  12240. this._mustWipeVertexAttributes = false;
  12241. this._nextFreeTextureSlots = new Array();
  12242. this._maxSimultaneousTextures = 0;
  12243. this._activeRequests = new Array();
  12244. // Hardware supported Compressed Textures
  12245. this._texturesSupported = new Array();
  12246. /**
  12247. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  12248. */
  12249. this.premultipliedAlpha = true;
  12250. this._viewportCached = new BABYLON.Vector4(0, 0, 0, 0);
  12251. this._onVRFullScreenTriggered = function () {
  12252. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  12253. //get the old size before we change
  12254. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  12255. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  12256. //get the width and height, change the render size
  12257. var leftEye = _this._vrDisplay.getEyeParameters('left');
  12258. _this.setHardwareScalingLevel(1);
  12259. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  12260. }
  12261. else {
  12262. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  12263. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  12264. }
  12265. };
  12266. this._unpackFlipYCached = null;
  12267. /**
  12268. * In case you are sharing the context with other applications, it might
  12269. * be interested to not cache the unpack flip y state to ensure a consistent
  12270. * value would be set.
  12271. */
  12272. this.enableUnpackFlipYCached = true;
  12273. this._boundUniforms = {};
  12274. // Register promises
  12275. BABYLON.PromisePolyfill.Apply();
  12276. var canvas = null;
  12277. Engine.Instances.push(this);
  12278. if (!canvasOrContext) {
  12279. return;
  12280. }
  12281. options = options || {};
  12282. if (canvasOrContext.getContext) {
  12283. canvas = canvasOrContext;
  12284. this._renderingCanvas = canvas;
  12285. if (antialias != null) {
  12286. options.antialias = antialias;
  12287. }
  12288. if (options.deterministicLockstep === undefined) {
  12289. options.deterministicLockstep = false;
  12290. }
  12291. if (options.lockstepMaxSteps === undefined) {
  12292. options.lockstepMaxSteps = 4;
  12293. }
  12294. if (options.preserveDrawingBuffer === undefined) {
  12295. options.preserveDrawingBuffer = false;
  12296. }
  12297. if (options.audioEngine === undefined) {
  12298. options.audioEngine = true;
  12299. }
  12300. if (options.stencil === undefined) {
  12301. options.stencil = true;
  12302. }
  12303. if (options.premultipliedAlpha === false) {
  12304. this.premultipliedAlpha = false;
  12305. }
  12306. this._deterministicLockstep = options.deterministicLockstep;
  12307. this._lockstepMaxSteps = options.lockstepMaxSteps;
  12308. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  12309. // Exceptions
  12310. if (navigator && navigator.userAgent) {
  12311. var ua = navigator.userAgent;
  12312. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  12313. var exception = _a[_i];
  12314. var key = exception.key;
  12315. var targets = exception.targets;
  12316. if (ua.indexOf(key) > -1) {
  12317. if (exception.capture && exception.captureConstraint) {
  12318. var capture = exception.capture;
  12319. var constraint = exception.captureConstraint;
  12320. var regex = new RegExp(capture);
  12321. var matches = regex.exec(ua);
  12322. if (matches && matches.length > 0) {
  12323. var capturedValue = parseInt(matches[matches.length - 1]);
  12324. if (capturedValue >= constraint) {
  12325. continue;
  12326. }
  12327. }
  12328. }
  12329. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  12330. var target = targets_1[_b];
  12331. switch (target) {
  12332. case "uniformBuffer":
  12333. this.disableUniformBuffers = true;
  12334. break;
  12335. case "textureBindingOptimization":
  12336. this.disableTextureBindingOptimization = true;
  12337. break;
  12338. }
  12339. }
  12340. }
  12341. }
  12342. }
  12343. // GL
  12344. if (!options.disableWebGL2Support) {
  12345. try {
  12346. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  12347. if (this._gl) {
  12348. this._webGLVersion = 2.0;
  12349. }
  12350. }
  12351. catch (e) {
  12352. // Do nothing
  12353. }
  12354. }
  12355. if (!this._gl) {
  12356. if (!canvas) {
  12357. throw new Error("The provided canvas is null or undefined.");
  12358. }
  12359. try {
  12360. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  12361. }
  12362. catch (e) {
  12363. throw new Error("WebGL not supported");
  12364. }
  12365. }
  12366. if (!this._gl) {
  12367. throw new Error("WebGL not supported");
  12368. }
  12369. this._onCanvasFocus = function () {
  12370. _this.onCanvasFocusObservable.notifyObservers(_this);
  12371. };
  12372. this._onCanvasBlur = function () {
  12373. _this.onCanvasBlurObservable.notifyObservers(_this);
  12374. };
  12375. canvas.addEventListener("focus", this._onCanvasFocus);
  12376. canvas.addEventListener("blur", this._onCanvasBlur);
  12377. this._onBlur = function () {
  12378. if (_this.disablePerformanceMonitorInBackground) {
  12379. _this._performanceMonitor.disable();
  12380. }
  12381. _this._windowIsBackground = true;
  12382. };
  12383. this._onFocus = function () {
  12384. if (_this.disablePerformanceMonitorInBackground) {
  12385. _this._performanceMonitor.enable();
  12386. }
  12387. _this._windowIsBackground = false;
  12388. };
  12389. this._onCanvasPointerOut = function (ev) {
  12390. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  12391. };
  12392. window.addEventListener("blur", this._onBlur);
  12393. window.addEventListener("focus", this._onFocus);
  12394. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  12395. // Context lost
  12396. if (!this._doNotHandleContextLost) {
  12397. this._onContextLost = function (evt) {
  12398. evt.preventDefault();
  12399. _this._contextWasLost = true;
  12400. BABYLON.Tools.Warn("WebGL context lost.");
  12401. _this.onContextLostObservable.notifyObservers(_this);
  12402. };
  12403. this._onContextRestored = function (evt) {
  12404. // Adding a timeout to avoid race condition at browser level
  12405. setTimeout(function () {
  12406. // Rebuild gl context
  12407. _this._initGLContext();
  12408. // Rebuild effects
  12409. _this._rebuildEffects();
  12410. // Rebuild textures
  12411. _this._rebuildInternalTextures();
  12412. // Rebuild buffers
  12413. _this._rebuildBuffers();
  12414. // Cache
  12415. _this.wipeCaches(true);
  12416. BABYLON.Tools.Warn("WebGL context successfully restored.");
  12417. _this.onContextRestoredObservable.notifyObservers(_this);
  12418. _this._contextWasLost = false;
  12419. }, 0);
  12420. };
  12421. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  12422. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  12423. }
  12424. }
  12425. else {
  12426. this._gl = canvasOrContext;
  12427. this._renderingCanvas = this._gl.canvas;
  12428. if (this._gl.renderbufferStorageMultisample) {
  12429. this._webGLVersion = 2.0;
  12430. }
  12431. options.stencil = this._gl.getContextAttributes().stencil;
  12432. }
  12433. // Viewport
  12434. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  12435. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  12436. this.resize();
  12437. this._isStencilEnable = options.stencil ? true : false;
  12438. this._initGLContext();
  12439. if (canvas) {
  12440. // Fullscreen
  12441. this._onFullscreenChange = function () {
  12442. if (document.fullscreen !== undefined) {
  12443. _this.isFullscreen = document.fullscreen;
  12444. }
  12445. else if (document.mozFullScreen !== undefined) {
  12446. _this.isFullscreen = document.mozFullScreen;
  12447. }
  12448. else if (document.webkitIsFullScreen !== undefined) {
  12449. _this.isFullscreen = document.webkitIsFullScreen;
  12450. }
  12451. else if (document.msIsFullScreen !== undefined) {
  12452. _this.isFullscreen = document.msIsFullScreen;
  12453. }
  12454. // Pointer lock
  12455. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  12456. canvas.requestPointerLock = canvas.requestPointerLock ||
  12457. canvas.msRequestPointerLock ||
  12458. canvas.mozRequestPointerLock ||
  12459. canvas.webkitRequestPointerLock;
  12460. if (canvas.requestPointerLock) {
  12461. canvas.requestPointerLock();
  12462. }
  12463. }
  12464. };
  12465. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  12466. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  12467. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  12468. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  12469. // Pointer lock
  12470. this._onPointerLockChange = function () {
  12471. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  12472. document.webkitPointerLockElement === canvas ||
  12473. document.msPointerLockElement === canvas ||
  12474. document.pointerLockElement === canvas);
  12475. };
  12476. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  12477. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  12478. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  12479. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  12480. this._onVRDisplayPointerRestricted = function () {
  12481. if (canvas) {
  12482. canvas.requestPointerLock();
  12483. }
  12484. };
  12485. this._onVRDisplayPointerUnrestricted = function () {
  12486. document.exitPointerLock();
  12487. };
  12488. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  12489. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  12490. }
  12491. // Create Audio Engine if needed.
  12492. if (!Engine.audioEngine && options.audioEngine && Engine.AudioEngineFactory) {
  12493. Engine.audioEngine = Engine.AudioEngineFactory(this);
  12494. }
  12495. // Prepare buffer pointers
  12496. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  12497. this._currentBufferPointers[i] = new BufferPointer();
  12498. }
  12499. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  12500. // Load WebVR Devices
  12501. if (options.autoEnableWebVR) {
  12502. this.initWebVR();
  12503. }
  12504. // Detect if we are running on a faulty buggy OS.
  12505. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  12506. // Detect if we are running on a faulty buggy desktop OS.
  12507. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  12508. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  12509. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  12510. }
  12511. Object.defineProperty(Engine, "LastCreatedEngine", {
  12512. /**
  12513. * Gets the latest created engine
  12514. */
  12515. get: function () {
  12516. if (Engine.Instances.length === 0) {
  12517. return null;
  12518. }
  12519. return Engine.Instances[Engine.Instances.length - 1];
  12520. },
  12521. enumerable: true,
  12522. configurable: true
  12523. });
  12524. Object.defineProperty(Engine, "LastCreatedScene", {
  12525. /**
  12526. * Gets the latest created scene
  12527. */
  12528. get: function () {
  12529. var lastCreatedEngine = Engine.LastCreatedEngine;
  12530. if (!lastCreatedEngine) {
  12531. return null;
  12532. }
  12533. if (lastCreatedEngine.scenes.length === 0) {
  12534. return null;
  12535. }
  12536. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  12537. },
  12538. enumerable: true,
  12539. configurable: true
  12540. });
  12541. /**
  12542. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  12543. * @param flag defines which part of the materials must be marked as dirty
  12544. * @param predicate defines a predicate used to filter which materials should be affected
  12545. */
  12546. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  12547. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  12548. var engine = Engine.Instances[engineIndex];
  12549. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  12550. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  12551. }
  12552. }
  12553. };
  12554. Object.defineProperty(Engine, "Version", {
  12555. /**
  12556. * Returns the current version of the framework
  12557. */
  12558. get: function () {
  12559. return "3.3.0-rc.4";
  12560. },
  12561. enumerable: true,
  12562. configurable: true
  12563. });
  12564. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  12565. /**
  12566. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  12567. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  12568. */
  12569. get: function () {
  12570. return this._vrExclusivePointerMode;
  12571. },
  12572. enumerable: true,
  12573. configurable: true
  12574. });
  12575. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  12576. /**
  12577. * Gets a boolean indicating that the engine supports uniform buffers
  12578. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12579. */
  12580. get: function () {
  12581. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  12582. },
  12583. enumerable: true,
  12584. configurable: true
  12585. });
  12586. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  12587. /**
  12588. * Gets a boolean indicating that only power of 2 textures are supported
  12589. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  12590. */
  12591. get: function () {
  12592. return this._webGLVersion < 2 || this.forcePOTTextures;
  12593. },
  12594. enumerable: true,
  12595. configurable: true
  12596. });
  12597. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  12598. /**
  12599. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  12600. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  12601. */
  12602. get: function () {
  12603. return this._doNotHandleContextLost;
  12604. },
  12605. set: function (value) {
  12606. this._doNotHandleContextLost = value;
  12607. },
  12608. enumerable: true,
  12609. configurable: true
  12610. });
  12611. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  12612. /**
  12613. * Gets the performance monitor attached to this engine
  12614. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  12615. */
  12616. get: function () {
  12617. return this._performanceMonitor;
  12618. },
  12619. enumerable: true,
  12620. configurable: true
  12621. });
  12622. Object.defineProperty(Engine.prototype, "texturesSupported", {
  12623. /**
  12624. * Gets the list of texture formats supported
  12625. */
  12626. get: function () {
  12627. return this._texturesSupported;
  12628. },
  12629. enumerable: true,
  12630. configurable: true
  12631. });
  12632. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  12633. /**
  12634. * Gets the list of texture formats in use
  12635. */
  12636. get: function () {
  12637. return this._textureFormatInUse;
  12638. },
  12639. enumerable: true,
  12640. configurable: true
  12641. });
  12642. Object.defineProperty(Engine.prototype, "currentViewport", {
  12643. /**
  12644. * Gets the current viewport
  12645. */
  12646. get: function () {
  12647. return this._cachedViewport;
  12648. },
  12649. enumerable: true,
  12650. configurable: true
  12651. });
  12652. Object.defineProperty(Engine.prototype, "emptyTexture", {
  12653. /**
  12654. * Gets the default empty texture
  12655. */
  12656. get: function () {
  12657. if (!this._emptyTexture) {
  12658. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  12659. }
  12660. return this._emptyTexture;
  12661. },
  12662. enumerable: true,
  12663. configurable: true
  12664. });
  12665. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  12666. /**
  12667. * Gets the default empty 3D texture
  12668. */
  12669. get: function () {
  12670. if (!this._emptyTexture3D) {
  12671. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  12672. }
  12673. return this._emptyTexture3D;
  12674. },
  12675. enumerable: true,
  12676. configurable: true
  12677. });
  12678. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  12679. /**
  12680. * Gets the default empty cube texture
  12681. */
  12682. get: function () {
  12683. if (!this._emptyCubeTexture) {
  12684. var faceData = new Uint8Array(4);
  12685. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  12686. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  12687. }
  12688. return this._emptyCubeTexture;
  12689. },
  12690. enumerable: true,
  12691. configurable: true
  12692. });
  12693. Engine.prototype._rebuildInternalTextures = function () {
  12694. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  12695. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  12696. var internalTexture = currentState_1[_i];
  12697. internalTexture._rebuild();
  12698. }
  12699. };
  12700. Engine.prototype._rebuildEffects = function () {
  12701. for (var key in this._compiledEffects) {
  12702. var effect = this._compiledEffects[key];
  12703. effect._prepareEffect();
  12704. }
  12705. BABYLON.Effect.ResetCache();
  12706. };
  12707. Engine.prototype._rebuildBuffers = function () {
  12708. // Index / Vertex
  12709. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  12710. var scene = _a[_i];
  12711. scene.resetCachedMaterial();
  12712. scene._rebuildGeometries();
  12713. scene._rebuildTextures();
  12714. }
  12715. // Uniforms
  12716. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  12717. var uniformBuffer = _c[_b];
  12718. uniformBuffer._rebuild();
  12719. }
  12720. };
  12721. Engine.prototype._initGLContext = function () {
  12722. // Caps
  12723. this._caps = new EngineCapabilities();
  12724. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  12725. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12726. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  12727. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  12728. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  12729. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  12730. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  12731. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12732. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12733. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12734. // Infos
  12735. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12736. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12737. if (rendererInfo != null) {
  12738. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12739. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12740. }
  12741. if (!this._glVendor) {
  12742. this._glVendor = "Unknown vendor";
  12743. }
  12744. if (!this._glRenderer) {
  12745. this._glRenderer = "Unknown renderer";
  12746. }
  12747. // Constants
  12748. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12749. if (this._gl.RGBA16F !== 0x881A) {
  12750. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12751. }
  12752. if (this._gl.RGBA32F !== 0x8814) {
  12753. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12754. }
  12755. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12756. this._gl.DEPTH24_STENCIL8 = 35056;
  12757. }
  12758. // Extensions
  12759. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12760. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12761. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12762. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12763. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12764. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12765. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12766. 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');
  12767. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12768. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12769. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12770. this._caps.highPrecisionShaderSupported = true;
  12771. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12772. if (this._caps.timerQuery) {
  12773. if (this._webGLVersion === 1) {
  12774. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12775. }
  12776. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12777. }
  12778. // Checks if some of the format renders first to allow the use of webgl inspector.
  12779. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12780. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12781. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12782. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12783. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12784. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12785. if (this._webGLVersion > 1) {
  12786. this._gl.HALF_FLOAT_OES = 0x140B;
  12787. }
  12788. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12789. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12790. // Draw buffers
  12791. if (this._webGLVersion > 1) {
  12792. this._caps.drawBuffersExtension = true;
  12793. }
  12794. else {
  12795. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12796. if (drawBuffersExtension !== null) {
  12797. this._caps.drawBuffersExtension = true;
  12798. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12799. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12800. for (var i = 0; i < 16; i++) {
  12801. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12802. }
  12803. }
  12804. else {
  12805. this._caps.drawBuffersExtension = false;
  12806. }
  12807. }
  12808. // Depth Texture
  12809. if (this._webGLVersion > 1) {
  12810. this._caps.depthTextureExtension = true;
  12811. }
  12812. else {
  12813. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12814. if (depthTextureExtension != null) {
  12815. this._caps.depthTextureExtension = true;
  12816. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12817. }
  12818. }
  12819. // Vertex array object
  12820. if (this._webGLVersion > 1) {
  12821. this._caps.vertexArrayObject = true;
  12822. }
  12823. else {
  12824. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12825. if (vertexArrayObjectExtension != null) {
  12826. this._caps.vertexArrayObject = true;
  12827. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12828. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12829. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12830. }
  12831. else {
  12832. this._caps.vertexArrayObject = false;
  12833. }
  12834. }
  12835. // Instances count
  12836. if (this._webGLVersion > 1) {
  12837. this._caps.instancedArrays = true;
  12838. }
  12839. else {
  12840. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12841. if (instanceExtension != null) {
  12842. this._caps.instancedArrays = true;
  12843. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12844. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12845. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12846. }
  12847. else {
  12848. this._caps.instancedArrays = false;
  12849. }
  12850. }
  12851. // Intelligently add supported compressed formats in order to check for.
  12852. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12853. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12854. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12855. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12856. if (this._caps.astc)
  12857. this.texturesSupported.push('-astc.ktx');
  12858. if (this._caps.s3tc)
  12859. this.texturesSupported.push('-dxt.ktx');
  12860. if (this._caps.pvrtc)
  12861. this.texturesSupported.push('-pvrtc.ktx');
  12862. if (this._caps.etc2)
  12863. this.texturesSupported.push('-etc2.ktx');
  12864. if (this._caps.etc1)
  12865. this.texturesSupported.push('-etc1.ktx');
  12866. if (this._gl.getShaderPrecisionFormat) {
  12867. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12868. if (highp) {
  12869. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12870. }
  12871. }
  12872. // Depth buffer
  12873. this.setDepthBuffer(true);
  12874. this.setDepthFunctionToLessOrEqual();
  12875. this.setDepthWrite(true);
  12876. // Texture maps
  12877. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12878. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12879. this._nextFreeTextureSlots.push(slot);
  12880. }
  12881. };
  12882. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12883. /**
  12884. * Gets version of the current webGL context
  12885. */
  12886. get: function () {
  12887. return this._webGLVersion;
  12888. },
  12889. enumerable: true,
  12890. configurable: true
  12891. });
  12892. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12893. /**
  12894. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12895. */
  12896. get: function () {
  12897. return this._isStencilEnable;
  12898. },
  12899. enumerable: true,
  12900. configurable: true
  12901. });
  12902. Engine.prototype._prepareWorkingCanvas = function () {
  12903. if (this._workingCanvas) {
  12904. return;
  12905. }
  12906. this._workingCanvas = document.createElement("canvas");
  12907. var context = this._workingCanvas.getContext("2d");
  12908. if (context) {
  12909. this._workingContext = context;
  12910. }
  12911. };
  12912. /**
  12913. * Reset the texture cache to empty state
  12914. */
  12915. Engine.prototype.resetTextureCache = function () {
  12916. for (var key in this._boundTexturesCache) {
  12917. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12918. continue;
  12919. }
  12920. var boundTexture = this._boundTexturesCache[key];
  12921. if (boundTexture) {
  12922. this._removeDesignatedSlot(boundTexture);
  12923. }
  12924. this._boundTexturesCache[key] = null;
  12925. }
  12926. if (!this.disableTextureBindingOptimization) {
  12927. this._nextFreeTextureSlots = [];
  12928. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12929. this._nextFreeTextureSlots.push(slot);
  12930. }
  12931. }
  12932. this._currentTextureChannel = -1;
  12933. };
  12934. /**
  12935. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12936. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12937. * @returns true if engine is in deterministic lock step mode
  12938. */
  12939. Engine.prototype.isDeterministicLockStep = function () {
  12940. return this._deterministicLockstep;
  12941. };
  12942. /**
  12943. * Gets the max steps when engine is running in deterministic lock step
  12944. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12945. * @returns the max steps
  12946. */
  12947. Engine.prototype.getLockstepMaxSteps = function () {
  12948. return this._lockstepMaxSteps;
  12949. };
  12950. /**
  12951. * Gets an object containing information about the current webGL context
  12952. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12953. */
  12954. Engine.prototype.getGlInfo = function () {
  12955. return {
  12956. vendor: this._glVendor,
  12957. renderer: this._glRenderer,
  12958. version: this._glVersion
  12959. };
  12960. };
  12961. /**
  12962. * Gets current aspect ratio
  12963. * @param camera defines the camera to use to get the aspect ratio
  12964. * @param useScreen defines if screen size must be used (or the current render target if any)
  12965. * @returns a number defining the aspect ratio
  12966. */
  12967. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12968. if (useScreen === void 0) { useScreen = false; }
  12969. var viewport = camera.viewport;
  12970. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12971. };
  12972. /**
  12973. * Gets current screen aspect ratio
  12974. * @returns a number defining the aspect ratio
  12975. */
  12976. Engine.prototype.getScreenAspectRatio = function () {
  12977. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  12978. };
  12979. /**
  12980. * Gets the current render width
  12981. * @param useScreen defines if screen size must be used (or the current render target if any)
  12982. * @returns a number defining the current render width
  12983. */
  12984. Engine.prototype.getRenderWidth = function (useScreen) {
  12985. if (useScreen === void 0) { useScreen = false; }
  12986. if (!useScreen && this._currentRenderTarget) {
  12987. return this._currentRenderTarget.width;
  12988. }
  12989. return this._gl.drawingBufferWidth;
  12990. };
  12991. /**
  12992. * Gets the current render height
  12993. * @param useScreen defines if screen size must be used (or the current render target if any)
  12994. * @returns a number defining the current render height
  12995. */
  12996. Engine.prototype.getRenderHeight = function (useScreen) {
  12997. if (useScreen === void 0) { useScreen = false; }
  12998. if (!useScreen && this._currentRenderTarget) {
  12999. return this._currentRenderTarget.height;
  13000. }
  13001. return this._gl.drawingBufferHeight;
  13002. };
  13003. /**
  13004. * Gets the HTML canvas attached with the current webGL context
  13005. * @returns a HTML canvas
  13006. */
  13007. Engine.prototype.getRenderingCanvas = function () {
  13008. return this._renderingCanvas;
  13009. };
  13010. /**
  13011. * Gets the client rect of the HTML canvas attached with the current webGL context
  13012. * @returns a client rectanglee
  13013. */
  13014. Engine.prototype.getRenderingCanvasClientRect = function () {
  13015. if (!this._renderingCanvas) {
  13016. return null;
  13017. }
  13018. return this._renderingCanvas.getBoundingClientRect();
  13019. };
  13020. /**
  13021. * Defines the hardware scaling level.
  13022. * By default the hardware scaling level is computed from the window device ratio.
  13023. * 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.
  13024. * @param level defines the level to use
  13025. */
  13026. Engine.prototype.setHardwareScalingLevel = function (level) {
  13027. this._hardwareScalingLevel = level;
  13028. this.resize();
  13029. };
  13030. /**
  13031. * Gets the current hardware scaling level.
  13032. * By default the hardware scaling level is computed from the window device ratio.
  13033. * 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.
  13034. * @returns a number indicating the current hardware scaling level
  13035. */
  13036. Engine.prototype.getHardwareScalingLevel = function () {
  13037. return this._hardwareScalingLevel;
  13038. };
  13039. /**
  13040. * Gets the list of loaded textures
  13041. * @returns an array containing all loaded textures
  13042. */
  13043. Engine.prototype.getLoadedTexturesCache = function () {
  13044. return this._internalTexturesCache;
  13045. };
  13046. /**
  13047. * Gets the object containing all engine capabilities
  13048. * @returns the EngineCapabilities object
  13049. */
  13050. Engine.prototype.getCaps = function () {
  13051. return this._caps;
  13052. };
  13053. Object.defineProperty(Engine.prototype, "drawCalls", {
  13054. /** @hidden */
  13055. get: function () {
  13056. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  13057. return 0;
  13058. },
  13059. enumerable: true,
  13060. configurable: true
  13061. });
  13062. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  13063. /** @hidden */
  13064. get: function () {
  13065. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  13066. return null;
  13067. },
  13068. enumerable: true,
  13069. configurable: true
  13070. });
  13071. /**
  13072. * Gets the current depth function
  13073. * @returns a number defining the depth function
  13074. */
  13075. Engine.prototype.getDepthFunction = function () {
  13076. return this._depthCullingState.depthFunc;
  13077. };
  13078. /**
  13079. * Sets the current depth function
  13080. * @param depthFunc defines the function to use
  13081. */
  13082. Engine.prototype.setDepthFunction = function (depthFunc) {
  13083. this._depthCullingState.depthFunc = depthFunc;
  13084. };
  13085. /**
  13086. * Sets the current depth function to GREATER
  13087. */
  13088. Engine.prototype.setDepthFunctionToGreater = function () {
  13089. this._depthCullingState.depthFunc = this._gl.GREATER;
  13090. };
  13091. /**
  13092. * Sets the current depth function to GEQUAL
  13093. */
  13094. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  13095. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  13096. };
  13097. /**
  13098. * Sets the current depth function to LESS
  13099. */
  13100. Engine.prototype.setDepthFunctionToLess = function () {
  13101. this._depthCullingState.depthFunc = this._gl.LESS;
  13102. };
  13103. /**
  13104. * Sets the current depth function to LEQUAL
  13105. */
  13106. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  13107. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  13108. };
  13109. /**
  13110. * Gets a boolean indicating if stencil buffer is enabled
  13111. * @returns the current stencil buffer state
  13112. */
  13113. Engine.prototype.getStencilBuffer = function () {
  13114. return this._stencilState.stencilTest;
  13115. };
  13116. /**
  13117. * Enable or disable the stencil buffer
  13118. * @param enable defines if the stencil buffer must be enabled or disabled
  13119. */
  13120. Engine.prototype.setStencilBuffer = function (enable) {
  13121. this._stencilState.stencilTest = enable;
  13122. };
  13123. /**
  13124. * Gets the current stencil mask
  13125. * @returns a number defining the new stencil mask to use
  13126. */
  13127. Engine.prototype.getStencilMask = function () {
  13128. return this._stencilState.stencilMask;
  13129. };
  13130. /**
  13131. * Sets the current stencil mask
  13132. * @param mask defines the new stencil mask to use
  13133. */
  13134. Engine.prototype.setStencilMask = function (mask) {
  13135. this._stencilState.stencilMask = mask;
  13136. };
  13137. /**
  13138. * Gets the current stencil function
  13139. * @returns a number defining the stencil function to use
  13140. */
  13141. Engine.prototype.getStencilFunction = function () {
  13142. return this._stencilState.stencilFunc;
  13143. };
  13144. /**
  13145. * Gets the current stencil reference value
  13146. * @returns a number defining the stencil reference value to use
  13147. */
  13148. Engine.prototype.getStencilFunctionReference = function () {
  13149. return this._stencilState.stencilFuncRef;
  13150. };
  13151. /**
  13152. * Gets the current stencil mask
  13153. * @returns a number defining the stencil mask to use
  13154. */
  13155. Engine.prototype.getStencilFunctionMask = function () {
  13156. return this._stencilState.stencilFuncMask;
  13157. };
  13158. /**
  13159. * Sets the current stencil function
  13160. * @param stencilFunc defines the new stencil function to use
  13161. */
  13162. Engine.prototype.setStencilFunction = function (stencilFunc) {
  13163. this._stencilState.stencilFunc = stencilFunc;
  13164. };
  13165. /**
  13166. * Sets the current stencil reference
  13167. * @param reference defines the new stencil reference to use
  13168. */
  13169. Engine.prototype.setStencilFunctionReference = function (reference) {
  13170. this._stencilState.stencilFuncRef = reference;
  13171. };
  13172. /**
  13173. * Sets the current stencil mask
  13174. * @param mask defines the new stencil mask to use
  13175. */
  13176. Engine.prototype.setStencilFunctionMask = function (mask) {
  13177. this._stencilState.stencilFuncMask = mask;
  13178. };
  13179. /**
  13180. * Gets the current stencil operation when stencil fails
  13181. * @returns a number defining stencil operation to use when stencil fails
  13182. */
  13183. Engine.prototype.getStencilOperationFail = function () {
  13184. return this._stencilState.stencilOpStencilFail;
  13185. };
  13186. /**
  13187. * Gets the current stencil operation when depth fails
  13188. * @returns a number defining stencil operation to use when depth fails
  13189. */
  13190. Engine.prototype.getStencilOperationDepthFail = function () {
  13191. return this._stencilState.stencilOpDepthFail;
  13192. };
  13193. /**
  13194. * Gets the current stencil operation when stencil passes
  13195. * @returns a number defining stencil operation to use when stencil passes
  13196. */
  13197. Engine.prototype.getStencilOperationPass = function () {
  13198. return this._stencilState.stencilOpStencilDepthPass;
  13199. };
  13200. /**
  13201. * Sets the stencil operation to use when stencil fails
  13202. * @param operation defines the stencil operation to use when stencil fails
  13203. */
  13204. Engine.prototype.setStencilOperationFail = function (operation) {
  13205. this._stencilState.stencilOpStencilFail = operation;
  13206. };
  13207. /**
  13208. * Sets the stencil operation to use when depth fails
  13209. * @param operation defines the stencil operation to use when depth fails
  13210. */
  13211. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  13212. this._stencilState.stencilOpDepthFail = operation;
  13213. };
  13214. /**
  13215. * Sets the stencil operation to use when stencil passes
  13216. * @param operation defines the stencil operation to use when stencil passes
  13217. */
  13218. Engine.prototype.setStencilOperationPass = function (operation) {
  13219. this._stencilState.stencilOpStencilDepthPass = operation;
  13220. };
  13221. /**
  13222. * Sets a boolean indicating if the dithering state is enabled or disabled
  13223. * @param value defines the dithering state
  13224. */
  13225. Engine.prototype.setDitheringState = function (value) {
  13226. if (value) {
  13227. this._gl.enable(this._gl.DITHER);
  13228. }
  13229. else {
  13230. this._gl.disable(this._gl.DITHER);
  13231. }
  13232. };
  13233. /**
  13234. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  13235. * @param value defines the rasterizer state
  13236. */
  13237. Engine.prototype.setRasterizerState = function (value) {
  13238. if (value) {
  13239. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  13240. }
  13241. else {
  13242. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  13243. }
  13244. };
  13245. /**
  13246. * stop executing a render loop function and remove it from the execution array
  13247. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  13248. */
  13249. Engine.prototype.stopRenderLoop = function (renderFunction) {
  13250. if (!renderFunction) {
  13251. this._activeRenderLoops = [];
  13252. return;
  13253. }
  13254. var index = this._activeRenderLoops.indexOf(renderFunction);
  13255. if (index >= 0) {
  13256. this._activeRenderLoops.splice(index, 1);
  13257. }
  13258. };
  13259. /** @hidden */
  13260. Engine.prototype._renderLoop = function () {
  13261. if (!this._contextWasLost) {
  13262. var shouldRender = true;
  13263. if (!this.renderEvenInBackground && this._windowIsBackground) {
  13264. shouldRender = false;
  13265. }
  13266. if (shouldRender) {
  13267. // Start new frame
  13268. this.beginFrame();
  13269. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  13270. var renderFunction = this._activeRenderLoops[index];
  13271. renderFunction();
  13272. }
  13273. // Present
  13274. this.endFrame();
  13275. }
  13276. }
  13277. if (this._activeRenderLoops.length > 0) {
  13278. // Register new frame
  13279. var requester = null;
  13280. if (this._vrDisplay && this._vrDisplay.isPresenting)
  13281. requester = this._vrDisplay;
  13282. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  13283. }
  13284. else {
  13285. this._renderingQueueLaunched = false;
  13286. }
  13287. };
  13288. /**
  13289. * Register and execute a render loop. The engine can have more than one render function
  13290. * @param renderFunction defines the function to continuously execute
  13291. */
  13292. Engine.prototype.runRenderLoop = function (renderFunction) {
  13293. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  13294. return;
  13295. }
  13296. this._activeRenderLoops.push(renderFunction);
  13297. if (!this._renderingQueueLaunched) {
  13298. this._renderingQueueLaunched = true;
  13299. this._bindedRenderFunction = this._renderLoop.bind(this);
  13300. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  13301. }
  13302. };
  13303. /**
  13304. * Toggle full screen mode
  13305. * @param requestPointerLock defines if a pointer lock should be requested from the user
  13306. */
  13307. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  13308. if (this.isFullscreen) {
  13309. BABYLON.Tools.ExitFullscreen();
  13310. }
  13311. else {
  13312. this._pointerLockRequested = requestPointerLock;
  13313. if (this._renderingCanvas) {
  13314. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  13315. }
  13316. }
  13317. };
  13318. /**
  13319. * Clear the current render buffer or the current render target (if any is set up)
  13320. * @param color defines the color to use
  13321. * @param backBuffer defines if the back buffer must be cleared
  13322. * @param depth defines if the depth buffer must be cleared
  13323. * @param stencil defines if the stencil buffer must be cleared
  13324. */
  13325. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  13326. if (stencil === void 0) { stencil = false; }
  13327. this.applyStates();
  13328. var mode = 0;
  13329. if (backBuffer && color) {
  13330. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  13331. mode |= this._gl.COLOR_BUFFER_BIT;
  13332. }
  13333. if (depth) {
  13334. this._gl.clearDepth(1.0);
  13335. mode |= this._gl.DEPTH_BUFFER_BIT;
  13336. }
  13337. if (stencil) {
  13338. this._gl.clearStencil(0);
  13339. mode |= this._gl.STENCIL_BUFFER_BIT;
  13340. }
  13341. this._gl.clear(mode);
  13342. };
  13343. /**
  13344. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  13345. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  13346. * @param y defines the y-coordinate of the corner of the clear rectangle
  13347. * @param width defines the width of the clear rectangle
  13348. * @param height defines the height of the clear rectangle
  13349. * @param clearColor defines the clear color
  13350. */
  13351. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  13352. var gl = this._gl;
  13353. // Save state
  13354. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  13355. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  13356. // Change state
  13357. gl.enable(gl.SCISSOR_TEST);
  13358. gl.scissor(x, y, width, height);
  13359. // Clear
  13360. this.clear(clearColor, true, true, true);
  13361. // Restore state
  13362. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  13363. if (curScissor === true) {
  13364. gl.enable(gl.SCISSOR_TEST);
  13365. }
  13366. else {
  13367. gl.disable(gl.SCISSOR_TEST);
  13368. }
  13369. };
  13370. /** @hidden */
  13371. Engine.prototype._viewport = function (x, y, width, height) {
  13372. if (x !== this._viewportCached.x ||
  13373. y !== this._viewportCached.y ||
  13374. width !== this._viewportCached.z ||
  13375. height !== this._viewportCached.w) {
  13376. this._viewportCached.x = x;
  13377. this._viewportCached.y = y;
  13378. this._viewportCached.z = width;
  13379. this._viewportCached.w = height;
  13380. this._gl.viewport(x, y, width, height);
  13381. }
  13382. };
  13383. /**
  13384. * Set the WebGL's viewport
  13385. * @param viewport defines the viewport element to be used
  13386. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  13387. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  13388. */
  13389. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  13390. var width = requiredWidth || this.getRenderWidth();
  13391. var height = requiredHeight || this.getRenderHeight();
  13392. var x = viewport.x || 0;
  13393. var y = viewport.y || 0;
  13394. this._cachedViewport = viewport;
  13395. this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  13396. };
  13397. /**
  13398. * Directly set the WebGL Viewport
  13399. * @param x defines the x coordinate of the viewport (in screen space)
  13400. * @param y defines the y coordinate of the viewport (in screen space)
  13401. * @param width defines the width of the viewport (in screen space)
  13402. * @param height defines the height of the viewport (in screen space)
  13403. * @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
  13404. */
  13405. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  13406. var currentViewport = this._cachedViewport;
  13407. this._cachedViewport = null;
  13408. this._viewport(x, y, width, height);
  13409. return currentViewport;
  13410. };
  13411. /**
  13412. * Begin a new frame
  13413. */
  13414. Engine.prototype.beginFrame = function () {
  13415. this.onBeginFrameObservable.notifyObservers(this);
  13416. this._measureFps();
  13417. };
  13418. /**
  13419. * Enf the current frame
  13420. */
  13421. Engine.prototype.endFrame = function () {
  13422. // Force a flush in case we are using a bad OS.
  13423. if (this._badOS) {
  13424. this.flushFramebuffer();
  13425. }
  13426. // Submit frame to the vr device, if enabled
  13427. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13428. // TODO: We should only submit the frame if we read frameData successfully.
  13429. this._vrDisplay.submitFrame();
  13430. }
  13431. this.onEndFrameObservable.notifyObservers(this);
  13432. };
  13433. /**
  13434. * Resize the view according to the canvas' size
  13435. */
  13436. Engine.prototype.resize = function () {
  13437. // We're not resizing the size of the canvas while in VR mode & presenting
  13438. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  13439. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  13440. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  13441. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  13442. }
  13443. };
  13444. /**
  13445. * Force a specific size of the canvas
  13446. * @param width defines the new canvas' width
  13447. * @param height defines the new canvas' height
  13448. */
  13449. Engine.prototype.setSize = function (width, height) {
  13450. if (!this._renderingCanvas) {
  13451. return;
  13452. }
  13453. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  13454. return;
  13455. }
  13456. this._renderingCanvas.width = width;
  13457. this._renderingCanvas.height = height;
  13458. for (var index = 0; index < this.scenes.length; index++) {
  13459. var scene = this.scenes[index];
  13460. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  13461. var cam = scene.cameras[camIndex];
  13462. cam._currentRenderId = 0;
  13463. }
  13464. }
  13465. if (this.onResizeObservable.hasObservers) {
  13466. this.onResizeObservable.notifyObservers(this);
  13467. }
  13468. };
  13469. // WebVR functions
  13470. /**
  13471. * Gets a boolean indicating if a webVR device was detected
  13472. * @returns true if a webVR device was detected
  13473. */
  13474. Engine.prototype.isVRDevicePresent = function () {
  13475. return !!this._vrDisplay;
  13476. };
  13477. /**
  13478. * Gets the current webVR device
  13479. * @returns the current webVR device (or null)
  13480. */
  13481. Engine.prototype.getVRDevice = function () {
  13482. return this._vrDisplay;
  13483. };
  13484. /**
  13485. * Initializes a webVR display and starts listening to display change events
  13486. * The onVRDisplayChangedObservable will be notified upon these changes
  13487. * @returns The onVRDisplayChangedObservable
  13488. */
  13489. Engine.prototype.initWebVR = function () {
  13490. this.initWebVRAsync();
  13491. return this.onVRDisplayChangedObservable;
  13492. };
  13493. /**
  13494. * Initializes a webVR display and starts listening to display change events
  13495. * The onVRDisplayChangedObservable will be notified upon these changes
  13496. * @returns A promise containing a VRDisplay and if vr is supported
  13497. */
  13498. Engine.prototype.initWebVRAsync = function () {
  13499. var _this = this;
  13500. var notifyObservers = function () {
  13501. var eventArgs = {
  13502. vrDisplay: _this._vrDisplay,
  13503. vrSupported: _this._vrSupported
  13504. };
  13505. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  13506. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  13507. };
  13508. if (!this._onVrDisplayConnect) {
  13509. this._onVrDisplayConnect = function (event) {
  13510. _this._vrDisplay = event.display;
  13511. notifyObservers();
  13512. };
  13513. this._onVrDisplayDisconnect = function () {
  13514. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  13515. _this._vrDisplay = undefined;
  13516. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  13517. notifyObservers();
  13518. };
  13519. this._onVrDisplayPresentChange = function () {
  13520. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  13521. };
  13522. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  13523. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  13524. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  13525. }
  13526. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  13527. this._webVRInitPromise.then(notifyObservers);
  13528. return this._webVRInitPromise;
  13529. };
  13530. /**
  13531. * Call this function to switch to webVR mode
  13532. * Will do nothing if webVR is not supported or if there is no webVR device
  13533. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13534. */
  13535. Engine.prototype.enableVR = function () {
  13536. var _this = this;
  13537. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  13538. var onResolved = function () {
  13539. _this.onVRRequestPresentComplete.notifyObservers(true);
  13540. _this._onVRFullScreenTriggered();
  13541. };
  13542. var onRejected = function () {
  13543. _this.onVRRequestPresentComplete.notifyObservers(false);
  13544. };
  13545. this.onVRRequestPresentStart.notifyObservers(this);
  13546. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  13547. }
  13548. };
  13549. /**
  13550. * Call this function to leave webVR mode
  13551. * Will do nothing if webVR is not supported or if there is no webVR device
  13552. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13553. */
  13554. Engine.prototype.disableVR = function () {
  13555. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13556. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  13557. }
  13558. };
  13559. Engine.prototype._getVRDisplaysAsync = function () {
  13560. var _this = this;
  13561. return new Promise(function (res, rej) {
  13562. if (navigator.getVRDisplays) {
  13563. navigator.getVRDisplays().then(function (devices) {
  13564. _this._vrSupported = true;
  13565. // note that devices may actually be an empty array. This is fine;
  13566. // we expect this._vrDisplay to be undefined in this case.
  13567. _this._vrDisplay = devices[0];
  13568. res({
  13569. vrDisplay: _this._vrDisplay,
  13570. vrSupported: _this._vrSupported
  13571. });
  13572. });
  13573. }
  13574. else {
  13575. _this._vrDisplay = undefined;
  13576. _this._vrSupported = false;
  13577. res({
  13578. vrDisplay: _this._vrDisplay,
  13579. vrSupported: _this._vrSupported
  13580. });
  13581. }
  13582. });
  13583. };
  13584. /**
  13585. * Binds the frame buffer to the specified texture.
  13586. * @param texture The texture to render to or null for the default canvas
  13587. * @param faceIndex The face of the texture to render to in case of cube texture
  13588. * @param requiredWidth The width of the target to render to
  13589. * @param requiredHeight The height of the target to render to
  13590. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  13591. * @param depthStencilTexture The depth stencil texture to use to render
  13592. * @param lodLevel defines le lod level to bind to the frame buffer
  13593. */
  13594. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
  13595. if (lodLevel === void 0) { lodLevel = 0; }
  13596. if (this._currentRenderTarget) {
  13597. this.unBindFramebuffer(this._currentRenderTarget);
  13598. }
  13599. this._currentRenderTarget = texture;
  13600. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  13601. var gl = this._gl;
  13602. if (texture.isCube) {
  13603. if (faceIndex === undefined) {
  13604. faceIndex = 0;
  13605. }
  13606. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  13607. if (depthStencilTexture) {
  13608. if (depthStencilTexture._generateStencilBuffer) {
  13609. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13610. }
  13611. else {
  13612. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13613. }
  13614. }
  13615. }
  13616. if (this._cachedViewport && !forceFullscreenViewport) {
  13617. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  13618. }
  13619. else {
  13620. if (!requiredWidth) {
  13621. requiredWidth = texture.width;
  13622. if (lodLevel) {
  13623. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  13624. }
  13625. }
  13626. if (!requiredHeight) {
  13627. requiredHeight = texture.height;
  13628. if (lodLevel) {
  13629. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  13630. }
  13631. }
  13632. this._viewport(0, 0, requiredWidth, requiredHeight);
  13633. }
  13634. this.wipeCaches();
  13635. };
  13636. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  13637. if (this._currentFramebuffer !== framebuffer) {
  13638. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  13639. this._currentFramebuffer = framebuffer;
  13640. }
  13641. };
  13642. /**
  13643. * Unbind the current render target texture from the webGL context
  13644. * @param texture defines the render target texture to unbind
  13645. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13646. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13647. */
  13648. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  13649. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13650. this._currentRenderTarget = null;
  13651. // If MSAA, we need to bitblt back to main texture
  13652. var gl = this._gl;
  13653. if (texture._MSAAFramebuffer) {
  13654. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  13655. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  13656. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13657. }
  13658. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13659. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13660. gl.generateMipmap(gl.TEXTURE_2D);
  13661. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13662. }
  13663. if (onBeforeUnbind) {
  13664. if (texture._MSAAFramebuffer) {
  13665. // Bind the correct framebuffer
  13666. this.bindUnboundFramebuffer(texture._framebuffer);
  13667. }
  13668. onBeforeUnbind();
  13669. }
  13670. this.bindUnboundFramebuffer(null);
  13671. };
  13672. /**
  13673. * Unbind a list of render target textures from the webGL context
  13674. * This is used only when drawBuffer extension or webGL2 are active
  13675. * @param textures defines the render target textures to unbind
  13676. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13677. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13678. */
  13679. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  13680. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13681. this._currentRenderTarget = null;
  13682. // If MSAA, we need to bitblt back to main texture
  13683. var gl = this._gl;
  13684. if (textures[0]._MSAAFramebuffer) {
  13685. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  13686. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  13687. var attachments = textures[0]._attachments;
  13688. if (!attachments) {
  13689. attachments = new Array(textures.length);
  13690. textures[0]._attachments = attachments;
  13691. }
  13692. for (var i = 0; i < textures.length; i++) {
  13693. var texture = textures[i];
  13694. for (var j = 0; j < attachments.length; j++) {
  13695. attachments[j] = gl.NONE;
  13696. }
  13697. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13698. gl.readBuffer(attachments[i]);
  13699. gl.drawBuffers(attachments);
  13700. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13701. }
  13702. for (var i = 0; i < attachments.length; i++) {
  13703. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13704. }
  13705. gl.drawBuffers(attachments);
  13706. }
  13707. for (var i = 0; i < textures.length; i++) {
  13708. var texture = textures[i];
  13709. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13710. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  13711. gl.generateMipmap(gl.TEXTURE_2D);
  13712. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13713. }
  13714. }
  13715. if (onBeforeUnbind) {
  13716. if (textures[0]._MSAAFramebuffer) {
  13717. // Bind the correct framebuffer
  13718. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13719. }
  13720. onBeforeUnbind();
  13721. }
  13722. this.bindUnboundFramebuffer(null);
  13723. };
  13724. /**
  13725. * Force the mipmap generation for the given render target texture
  13726. * @param texture defines the render target texture to use
  13727. */
  13728. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  13729. if (texture.generateMipMaps) {
  13730. var gl = this._gl;
  13731. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13732. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13733. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13734. }
  13735. };
  13736. /**
  13737. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13738. */
  13739. Engine.prototype.flushFramebuffer = function () {
  13740. this._gl.flush();
  13741. };
  13742. /**
  13743. * Unbind the current render target and bind the default framebuffer
  13744. */
  13745. Engine.prototype.restoreDefaultFramebuffer = function () {
  13746. if (this._currentRenderTarget) {
  13747. this.unBindFramebuffer(this._currentRenderTarget);
  13748. }
  13749. else {
  13750. this.bindUnboundFramebuffer(null);
  13751. }
  13752. if (this._cachedViewport) {
  13753. this.setViewport(this._cachedViewport);
  13754. }
  13755. this.wipeCaches();
  13756. };
  13757. // UBOs
  13758. /**
  13759. * Create an uniform buffer
  13760. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13761. * @param elements defines the content of the uniform buffer
  13762. * @returns the webGL uniform buffer
  13763. */
  13764. Engine.prototype.createUniformBuffer = function (elements) {
  13765. var ubo = this._gl.createBuffer();
  13766. if (!ubo) {
  13767. throw new Error("Unable to create uniform buffer");
  13768. }
  13769. this.bindUniformBuffer(ubo);
  13770. if (elements instanceof Float32Array) {
  13771. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13772. }
  13773. else {
  13774. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13775. }
  13776. this.bindUniformBuffer(null);
  13777. ubo.references = 1;
  13778. return ubo;
  13779. };
  13780. /**
  13781. * Create a dynamic uniform buffer
  13782. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13783. * @param elements defines the content of the uniform buffer
  13784. * @returns the webGL uniform buffer
  13785. */
  13786. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13787. var ubo = this._gl.createBuffer();
  13788. if (!ubo) {
  13789. throw new Error("Unable to create dynamic uniform buffer");
  13790. }
  13791. this.bindUniformBuffer(ubo);
  13792. if (elements instanceof Float32Array) {
  13793. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13794. }
  13795. else {
  13796. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13797. }
  13798. this.bindUniformBuffer(null);
  13799. ubo.references = 1;
  13800. return ubo;
  13801. };
  13802. /**
  13803. * Update an existing uniform buffer
  13804. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13805. * @param uniformBuffer defines the target uniform buffer
  13806. * @param elements defines the content to update
  13807. * @param offset defines the offset in the uniform buffer where update should start
  13808. * @param count defines the size of the data to update
  13809. */
  13810. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13811. this.bindUniformBuffer(uniformBuffer);
  13812. if (offset === undefined) {
  13813. offset = 0;
  13814. }
  13815. if (count === undefined) {
  13816. if (elements instanceof Float32Array) {
  13817. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13818. }
  13819. else {
  13820. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13821. }
  13822. }
  13823. else {
  13824. if (elements instanceof Float32Array) {
  13825. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13826. }
  13827. else {
  13828. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13829. }
  13830. }
  13831. this.bindUniformBuffer(null);
  13832. };
  13833. // VBOs
  13834. Engine.prototype._resetVertexBufferBinding = function () {
  13835. this.bindArrayBuffer(null);
  13836. this._cachedVertexBuffers = null;
  13837. };
  13838. /**
  13839. * Creates a vertex buffer
  13840. * @param data the data for the vertex buffer
  13841. * @returns the new WebGL static buffer
  13842. */
  13843. Engine.prototype.createVertexBuffer = function (data) {
  13844. var vbo = this._gl.createBuffer();
  13845. if (!vbo) {
  13846. throw new Error("Unable to create vertex buffer");
  13847. }
  13848. this.bindArrayBuffer(vbo);
  13849. if (data instanceof Array) {
  13850. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13851. }
  13852. else {
  13853. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13854. }
  13855. this._resetVertexBufferBinding();
  13856. vbo.references = 1;
  13857. return vbo;
  13858. };
  13859. /**
  13860. * Creates a dynamic vertex buffer
  13861. * @param data the data for the dynamic vertex buffer
  13862. * @returns the new WebGL dynamic buffer
  13863. */
  13864. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13865. var vbo = this._gl.createBuffer();
  13866. if (!vbo) {
  13867. throw new Error("Unable to create dynamic vertex buffer");
  13868. }
  13869. this.bindArrayBuffer(vbo);
  13870. if (data instanceof Array) {
  13871. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13872. }
  13873. else {
  13874. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13875. }
  13876. this._resetVertexBufferBinding();
  13877. vbo.references = 1;
  13878. return vbo;
  13879. };
  13880. /**
  13881. * Update a dynamic index buffer
  13882. * @param indexBuffer defines the target index buffer
  13883. * @param indices defines the data to update
  13884. * @param offset defines the offset in the target index buffer where update should start
  13885. */
  13886. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13887. if (offset === void 0) { offset = 0; }
  13888. // Force cache update
  13889. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13890. this.bindIndexBuffer(indexBuffer);
  13891. var arrayBuffer;
  13892. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13893. arrayBuffer = indices;
  13894. }
  13895. else {
  13896. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13897. }
  13898. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13899. this._resetIndexBufferBinding();
  13900. };
  13901. /**
  13902. * Updates a dynamic vertex buffer.
  13903. * @param vertexBuffer the vertex buffer to update
  13904. * @param data the data used to update the vertex buffer
  13905. * @param byteOffset the byte offset of the data
  13906. * @param byteLength the byte length of the data
  13907. */
  13908. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13909. this.bindArrayBuffer(vertexBuffer);
  13910. if (byteOffset === undefined) {
  13911. byteOffset = 0;
  13912. }
  13913. if (byteLength === undefined) {
  13914. if (data instanceof Array) {
  13915. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13916. }
  13917. else {
  13918. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13919. }
  13920. }
  13921. else {
  13922. if (data instanceof Array) {
  13923. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13924. }
  13925. else {
  13926. if (data instanceof ArrayBuffer) {
  13927. data = new Uint8Array(data, byteOffset, byteLength);
  13928. }
  13929. else {
  13930. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13931. }
  13932. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13933. }
  13934. }
  13935. this._resetVertexBufferBinding();
  13936. };
  13937. Engine.prototype._resetIndexBufferBinding = function () {
  13938. this.bindIndexBuffer(null);
  13939. this._cachedIndexBuffer = null;
  13940. };
  13941. /**
  13942. * Creates a new index buffer
  13943. * @param indices defines the content of the index buffer
  13944. * @param updatable defines if the index buffer must be updatable
  13945. * @returns a new webGL buffer
  13946. */
  13947. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13948. var vbo = this._gl.createBuffer();
  13949. if (!vbo) {
  13950. throw new Error("Unable to create index buffer");
  13951. }
  13952. this.bindIndexBuffer(vbo);
  13953. // Check for 32 bits indices
  13954. var arrayBuffer;
  13955. var need32Bits = false;
  13956. if (indices instanceof Uint16Array) {
  13957. arrayBuffer = indices;
  13958. }
  13959. else {
  13960. //check 32 bit support
  13961. if (this._caps.uintIndices) {
  13962. if (indices instanceof Uint32Array) {
  13963. arrayBuffer = indices;
  13964. need32Bits = true;
  13965. }
  13966. else {
  13967. //number[] or Int32Array, check if 32 bit is necessary
  13968. for (var index = 0; index < indices.length; index++) {
  13969. if (indices[index] > 65535) {
  13970. need32Bits = true;
  13971. break;
  13972. }
  13973. }
  13974. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13975. }
  13976. }
  13977. else {
  13978. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13979. arrayBuffer = new Uint16Array(indices);
  13980. }
  13981. }
  13982. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13983. this._resetIndexBufferBinding();
  13984. vbo.references = 1;
  13985. vbo.is32Bits = need32Bits;
  13986. return vbo;
  13987. };
  13988. /**
  13989. * Bind a webGL buffer to the webGL context
  13990. * @param buffer defines the buffer to bind
  13991. */
  13992. Engine.prototype.bindArrayBuffer = function (buffer) {
  13993. if (!this._vaoRecordInProgress) {
  13994. this._unbindVertexArrayObject();
  13995. }
  13996. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13997. };
  13998. /**
  13999. * Bind an uniform buffer to the current webGL context
  14000. * @param buffer defines the buffer to bind
  14001. */
  14002. Engine.prototype.bindUniformBuffer = function (buffer) {
  14003. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  14004. };
  14005. /**
  14006. * Bind a buffer to the current webGL context at a given location
  14007. * @param buffer defines the buffer to bind
  14008. * @param location defines the index where to bind the buffer
  14009. */
  14010. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  14011. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  14012. };
  14013. /**
  14014. * Bind a specific block at a given index in a specific shader program
  14015. * @param shaderProgram defines the shader program
  14016. * @param blockName defines the block name
  14017. * @param index defines the index where to bind the block
  14018. */
  14019. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  14020. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  14021. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  14022. };
  14023. ;
  14024. Engine.prototype.bindIndexBuffer = function (buffer) {
  14025. if (!this._vaoRecordInProgress) {
  14026. this._unbindVertexArrayObject();
  14027. }
  14028. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  14029. };
  14030. Engine.prototype.bindBuffer = function (buffer, target) {
  14031. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  14032. this._gl.bindBuffer(target, buffer);
  14033. this._currentBoundBuffer[target] = buffer;
  14034. }
  14035. };
  14036. /**
  14037. * update the bound buffer with the given data
  14038. * @param data defines the data to update
  14039. */
  14040. Engine.prototype.updateArrayBuffer = function (data) {
  14041. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  14042. };
  14043. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  14044. var pointer = this._currentBufferPointers[indx];
  14045. var changed = false;
  14046. if (!pointer.active) {
  14047. changed = true;
  14048. pointer.active = true;
  14049. pointer.index = indx;
  14050. pointer.size = size;
  14051. pointer.type = type;
  14052. pointer.normalized = normalized;
  14053. pointer.stride = stride;
  14054. pointer.offset = offset;
  14055. pointer.buffer = buffer;
  14056. }
  14057. else {
  14058. if (pointer.buffer !== buffer) {
  14059. pointer.buffer = buffer;
  14060. changed = true;
  14061. }
  14062. if (pointer.size !== size) {
  14063. pointer.size = size;
  14064. changed = true;
  14065. }
  14066. if (pointer.type !== type) {
  14067. pointer.type = type;
  14068. changed = true;
  14069. }
  14070. if (pointer.normalized !== normalized) {
  14071. pointer.normalized = normalized;
  14072. changed = true;
  14073. }
  14074. if (pointer.stride !== stride) {
  14075. pointer.stride = stride;
  14076. changed = true;
  14077. }
  14078. if (pointer.offset !== offset) {
  14079. pointer.offset = offset;
  14080. changed = true;
  14081. }
  14082. }
  14083. if (changed || this._vaoRecordInProgress) {
  14084. this.bindArrayBuffer(buffer);
  14085. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  14086. }
  14087. };
  14088. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  14089. if (indexBuffer == null) {
  14090. return;
  14091. }
  14092. if (this._cachedIndexBuffer !== indexBuffer) {
  14093. this._cachedIndexBuffer = indexBuffer;
  14094. this.bindIndexBuffer(indexBuffer);
  14095. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  14096. }
  14097. };
  14098. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  14099. var attributes = effect.getAttributesNames();
  14100. if (!this._vaoRecordInProgress) {
  14101. this._unbindVertexArrayObject();
  14102. }
  14103. this.unbindAllAttributes();
  14104. for (var index = 0; index < attributes.length; index++) {
  14105. var order = effect.getAttributeLocation(index);
  14106. if (order >= 0) {
  14107. var vertexBuffer = vertexBuffers[attributes[index]];
  14108. if (!vertexBuffer) {
  14109. continue;
  14110. }
  14111. this._gl.enableVertexAttribArray(order);
  14112. if (!this._vaoRecordInProgress) {
  14113. this._vertexAttribArraysEnabled[order] = true;
  14114. }
  14115. var buffer = vertexBuffer.getBuffer();
  14116. if (buffer) {
  14117. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  14118. if (vertexBuffer.getIsInstanced()) {
  14119. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  14120. if (!this._vaoRecordInProgress) {
  14121. this._currentInstanceLocations.push(order);
  14122. this._currentInstanceBuffers.push(buffer);
  14123. }
  14124. }
  14125. }
  14126. }
  14127. }
  14128. };
  14129. /**
  14130. * Records a vertex array object
  14131. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  14132. * @param vertexBuffers defines the list of vertex buffers to store
  14133. * @param indexBuffer defines the index buffer to store
  14134. * @param effect defines the effect to store
  14135. * @returns the new vertex array object
  14136. */
  14137. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  14138. var vao = this._gl.createVertexArray();
  14139. this._vaoRecordInProgress = true;
  14140. this._gl.bindVertexArray(vao);
  14141. this._mustWipeVertexAttributes = true;
  14142. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  14143. this.bindIndexBuffer(indexBuffer);
  14144. this._vaoRecordInProgress = false;
  14145. this._gl.bindVertexArray(null);
  14146. return vao;
  14147. };
  14148. /**
  14149. * Bind a specific vertex array object
  14150. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  14151. * @param vertexArrayObject defines the vertex array object to bind
  14152. * @param indexBuffer defines the index buffer to bind
  14153. */
  14154. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  14155. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  14156. this._cachedVertexArrayObject = vertexArrayObject;
  14157. this._gl.bindVertexArray(vertexArrayObject);
  14158. this._cachedVertexBuffers = null;
  14159. this._cachedIndexBuffer = null;
  14160. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  14161. this._mustWipeVertexAttributes = true;
  14162. }
  14163. };
  14164. /**
  14165. * Bind webGl buffers directly to the webGL context
  14166. * @param vertexBuffer defines the vertex buffer to bind
  14167. * @param indexBuffer defines the index buffer to bind
  14168. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  14169. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  14170. * @param effect defines the effect associated with the vertex buffer
  14171. */
  14172. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  14173. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  14174. this._cachedVertexBuffers = vertexBuffer;
  14175. this._cachedEffectForVertexBuffers = effect;
  14176. var attributesCount = effect.getAttributesCount();
  14177. this._unbindVertexArrayObject();
  14178. this.unbindAllAttributes();
  14179. var offset = 0;
  14180. for (var index = 0; index < attributesCount; index++) {
  14181. if (index < vertexDeclaration.length) {
  14182. var order = effect.getAttributeLocation(index);
  14183. if (order >= 0) {
  14184. this._gl.enableVertexAttribArray(order);
  14185. this._vertexAttribArraysEnabled[order] = true;
  14186. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  14187. }
  14188. offset += vertexDeclaration[index] * 4;
  14189. }
  14190. }
  14191. }
  14192. this._bindIndexBufferWithCache(indexBuffer);
  14193. };
  14194. Engine.prototype._unbindVertexArrayObject = function () {
  14195. if (!this._cachedVertexArrayObject) {
  14196. return;
  14197. }
  14198. this._cachedVertexArrayObject = null;
  14199. this._gl.bindVertexArray(null);
  14200. };
  14201. /**
  14202. * Bind a list of vertex buffers to the webGL context
  14203. * @param vertexBuffers defines the list of vertex buffers to bind
  14204. * @param indexBuffer defines the index buffer to bind
  14205. * @param effect defines the effect associated with the vertex buffers
  14206. */
  14207. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  14208. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  14209. this._cachedVertexBuffers = vertexBuffers;
  14210. this._cachedEffectForVertexBuffers = effect;
  14211. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  14212. }
  14213. this._bindIndexBufferWithCache(indexBuffer);
  14214. };
  14215. /**
  14216. * Unbind all instance attributes
  14217. */
  14218. Engine.prototype.unbindInstanceAttributes = function () {
  14219. var boundBuffer;
  14220. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  14221. var instancesBuffer = this._currentInstanceBuffers[i];
  14222. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  14223. boundBuffer = instancesBuffer;
  14224. this.bindArrayBuffer(instancesBuffer);
  14225. }
  14226. var offsetLocation = this._currentInstanceLocations[i];
  14227. this._gl.vertexAttribDivisor(offsetLocation, 0);
  14228. }
  14229. this._currentInstanceBuffers.length = 0;
  14230. this._currentInstanceLocations.length = 0;
  14231. };
  14232. /**
  14233. * Release and free the memory of a vertex array object
  14234. * @param vao defines the vertex array object to delete
  14235. */
  14236. Engine.prototype.releaseVertexArrayObject = function (vao) {
  14237. this._gl.deleteVertexArray(vao);
  14238. };
  14239. /** @hidden */
  14240. Engine.prototype._releaseBuffer = function (buffer) {
  14241. buffer.references--;
  14242. if (buffer.references === 0) {
  14243. this._gl.deleteBuffer(buffer);
  14244. return true;
  14245. }
  14246. return false;
  14247. };
  14248. /**
  14249. * Creates a webGL buffer to use with instanciation
  14250. * @param capacity defines the size of the buffer
  14251. * @returns the webGL buffer
  14252. */
  14253. Engine.prototype.createInstancesBuffer = function (capacity) {
  14254. var buffer = this._gl.createBuffer();
  14255. if (!buffer) {
  14256. throw new Error("Unable to create instance buffer");
  14257. }
  14258. buffer.capacity = capacity;
  14259. this.bindArrayBuffer(buffer);
  14260. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  14261. return buffer;
  14262. };
  14263. /**
  14264. * Delete a webGL buffer used with instanciation
  14265. * @param buffer defines the webGL buffer to delete
  14266. */
  14267. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  14268. this._gl.deleteBuffer(buffer);
  14269. };
  14270. /**
  14271. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  14272. * @param instancesBuffer defines the webGL buffer to update and bind
  14273. * @param data defines the data to store in the buffer
  14274. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  14275. */
  14276. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  14277. this.bindArrayBuffer(instancesBuffer);
  14278. if (data) {
  14279. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  14280. }
  14281. if (offsetLocations[0].index !== undefined) {
  14282. var stride = 0;
  14283. for (var i = 0; i < offsetLocations.length; i++) {
  14284. var ai = offsetLocations[i];
  14285. stride += ai.attributeSize * 4;
  14286. }
  14287. for (var i = 0; i < offsetLocations.length; i++) {
  14288. var ai = offsetLocations[i];
  14289. if (!this._vertexAttribArraysEnabled[ai.index]) {
  14290. this._gl.enableVertexAttribArray(ai.index);
  14291. this._vertexAttribArraysEnabled[ai.index] = true;
  14292. }
  14293. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  14294. this._gl.vertexAttribDivisor(ai.index, 1);
  14295. this._currentInstanceLocations.push(ai.index);
  14296. this._currentInstanceBuffers.push(instancesBuffer);
  14297. }
  14298. }
  14299. else {
  14300. for (var index = 0; index < 4; index++) {
  14301. var offsetLocation = offsetLocations[index];
  14302. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  14303. this._gl.enableVertexAttribArray(offsetLocation);
  14304. this._vertexAttribArraysEnabled[offsetLocation] = true;
  14305. }
  14306. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  14307. this._gl.vertexAttribDivisor(offsetLocation, 1);
  14308. this._currentInstanceLocations.push(offsetLocation);
  14309. this._currentInstanceBuffers.push(instancesBuffer);
  14310. }
  14311. }
  14312. };
  14313. /**
  14314. * Apply all cached states (depth, culling, stencil and alpha)
  14315. */
  14316. Engine.prototype.applyStates = function () {
  14317. this._depthCullingState.apply(this._gl);
  14318. this._stencilState.apply(this._gl);
  14319. this._alphaState.apply(this._gl);
  14320. };
  14321. /**
  14322. * Send a draw order
  14323. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  14324. * @param indexStart defines the starting index
  14325. * @param indexCount defines the number of index to draw
  14326. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14327. */
  14328. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  14329. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  14330. };
  14331. /**
  14332. * Draw a list of points
  14333. * @param verticesStart defines the index of first vertex to draw
  14334. * @param verticesCount defines the count of vertices to draw
  14335. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14336. */
  14337. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  14338. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  14339. };
  14340. /**
  14341. * Draw a list of unindexed primitives
  14342. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  14343. * @param verticesStart defines the index of first vertex to draw
  14344. * @param verticesCount defines the count of vertices to draw
  14345. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14346. */
  14347. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  14348. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  14349. };
  14350. /**
  14351. * Draw a list of indexed primitives
  14352. * @param fillMode defines the primitive to use
  14353. * @param indexStart defines the starting index
  14354. * @param indexCount defines the number of index to draw
  14355. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14356. */
  14357. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  14358. // Apply states
  14359. this.applyStates();
  14360. this._drawCalls.addCount(1, false);
  14361. // Render
  14362. var drawMode = this._drawMode(fillMode);
  14363. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  14364. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  14365. if (instancesCount) {
  14366. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  14367. }
  14368. else {
  14369. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  14370. }
  14371. };
  14372. /**
  14373. * Draw a list of unindexed primitives
  14374. * @param fillMode defines the primitive to use
  14375. * @param verticesStart defines the index of first vertex to draw
  14376. * @param verticesCount defines the count of vertices to draw
  14377. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14378. */
  14379. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  14380. // Apply states
  14381. this.applyStates();
  14382. this._drawCalls.addCount(1, false);
  14383. var drawMode = this._drawMode(fillMode);
  14384. if (instancesCount) {
  14385. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  14386. }
  14387. else {
  14388. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  14389. }
  14390. };
  14391. Engine.prototype._drawMode = function (fillMode) {
  14392. switch (fillMode) {
  14393. // Triangle views
  14394. case BABYLON.Material.TriangleFillMode:
  14395. return this._gl.TRIANGLES;
  14396. case BABYLON.Material.PointFillMode:
  14397. return this._gl.POINTS;
  14398. case BABYLON.Material.WireFrameFillMode:
  14399. return this._gl.LINES;
  14400. // Draw modes
  14401. case BABYLON.Material.PointListDrawMode:
  14402. return this._gl.POINTS;
  14403. case BABYLON.Material.LineListDrawMode:
  14404. return this._gl.LINES;
  14405. case BABYLON.Material.LineLoopDrawMode:
  14406. return this._gl.LINE_LOOP;
  14407. case BABYLON.Material.LineStripDrawMode:
  14408. return this._gl.LINE_STRIP;
  14409. case BABYLON.Material.TriangleStripDrawMode:
  14410. return this._gl.TRIANGLE_STRIP;
  14411. case BABYLON.Material.TriangleFanDrawMode:
  14412. return this._gl.TRIANGLE_FAN;
  14413. default:
  14414. return this._gl.TRIANGLES;
  14415. }
  14416. };
  14417. // Shaders
  14418. /** @hidden */
  14419. Engine.prototype._releaseEffect = function (effect) {
  14420. if (this._compiledEffects[effect._key]) {
  14421. delete this._compiledEffects[effect._key];
  14422. this._deleteProgram(effect.getProgram());
  14423. }
  14424. };
  14425. /** @hidden */
  14426. Engine.prototype._deleteProgram = function (program) {
  14427. if (program) {
  14428. program.__SPECTOR_rebuildProgram = null;
  14429. if (program.transformFeedback) {
  14430. this.deleteTransformFeedback(program.transformFeedback);
  14431. program.transformFeedback = null;
  14432. }
  14433. this._gl.deleteProgram(program);
  14434. }
  14435. };
  14436. /**
  14437. * Create a new effect (used to store vertex/fragment shaders)
  14438. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  14439. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  14440. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  14441. * @param samplers defines an array of string used to represent textures
  14442. * @param defines defines the string containing the defines to use to compile the shaders
  14443. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  14444. * @param onCompiled defines a function to call when the effect creation is successful
  14445. * @param onError defines a function to call when the effect creation has failed
  14446. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  14447. * @returns the new Effect
  14448. */
  14449. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  14450. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  14451. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  14452. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  14453. if (this._compiledEffects[name]) {
  14454. var compiledEffect = this._compiledEffects[name];
  14455. if (onCompiled && compiledEffect.isReady()) {
  14456. onCompiled(compiledEffect);
  14457. }
  14458. return compiledEffect;
  14459. }
  14460. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  14461. effect._key = name;
  14462. this._compiledEffects[name] = effect;
  14463. return effect;
  14464. };
  14465. Engine.prototype._compileShader = function (source, type, defines, shaderVersion) {
  14466. return this._compileRawShader(shaderVersion + (defines ? defines + "\n" : "") + source, type);
  14467. };
  14468. ;
  14469. Engine.prototype._compileRawShader = function (source, type) {
  14470. var gl = this._gl;
  14471. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  14472. gl.shaderSource(shader, source);
  14473. gl.compileShader(shader);
  14474. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  14475. var log = gl.getShaderInfoLog(shader);
  14476. if (log) {
  14477. throw new Error(log);
  14478. }
  14479. }
  14480. if (!shader) {
  14481. throw new Error("Something went wrong while compile the shader.");
  14482. }
  14483. return shader;
  14484. };
  14485. ;
  14486. /**
  14487. * Directly creates a webGL program
  14488. * @param vertexCode defines the vertex shader code to use
  14489. * @param fragmentCode defines the fragment shader code to use
  14490. * @param context defines the webGL context to use (if not set, the current one will be used)
  14491. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  14492. * @returns the new webGL program
  14493. */
  14494. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  14495. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14496. context = context || this._gl;
  14497. var vertexShader = this._compileRawShader(vertexCode, "vertex");
  14498. var fragmentShader = this._compileRawShader(fragmentCode, "fragment");
  14499. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  14500. };
  14501. /**
  14502. * Creates a webGL program
  14503. * @param vertexCode defines the vertex shader code to use
  14504. * @param fragmentCode defines the fragment shader code to use
  14505. * @param defines defines the string containing the defines to use to compile the shaders
  14506. * @param context defines the webGL context to use (if not set, the current one will be used)
  14507. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  14508. * @returns the new webGL program
  14509. */
  14510. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  14511. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14512. context = context || this._gl;
  14513. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  14514. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  14515. var vertexShader = this._compileShader(vertexCode, "vertex", defines, shaderVersion);
  14516. var fragmentShader = this._compileShader(fragmentCode, "fragment", defines, shaderVersion);
  14517. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  14518. this.onAfterShaderCompilationObservable.notifyObservers(this);
  14519. return program;
  14520. };
  14521. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  14522. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14523. var shaderProgram = context.createProgram();
  14524. if (!shaderProgram) {
  14525. throw new Error("Unable to create program");
  14526. }
  14527. context.attachShader(shaderProgram, vertexShader);
  14528. context.attachShader(shaderProgram, fragmentShader);
  14529. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14530. var transformFeedback = this.createTransformFeedback();
  14531. this.bindTransformFeedback(transformFeedback);
  14532. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  14533. shaderProgram.transformFeedback = transformFeedback;
  14534. }
  14535. context.linkProgram(shaderProgram);
  14536. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14537. this.bindTransformFeedback(null);
  14538. }
  14539. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  14540. if (!linked) {
  14541. var error = context.getProgramInfoLog(shaderProgram);
  14542. if (error) {
  14543. throw new Error(error);
  14544. }
  14545. }
  14546. if (this.validateShaderPrograms) {
  14547. context.validateProgram(shaderProgram);
  14548. var validated = context.getProgramParameter(shaderProgram, context.VALIDATE_STATUS);
  14549. if (!validated) {
  14550. var error = context.getProgramInfoLog(shaderProgram);
  14551. if (error) {
  14552. throw new Error(error);
  14553. }
  14554. }
  14555. }
  14556. context.deleteShader(vertexShader);
  14557. context.deleteShader(fragmentShader);
  14558. return shaderProgram;
  14559. };
  14560. /**
  14561. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  14562. * @param shaderProgram defines the webGL program to use
  14563. * @param uniformsNames defines the list of uniform names
  14564. * @returns an array of webGL uniform locations
  14565. */
  14566. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  14567. var results = new Array();
  14568. for (var index = 0; index < uniformsNames.length; index++) {
  14569. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  14570. }
  14571. return results;
  14572. };
  14573. /**
  14574. * Gets the lsit of active attributes for a given webGL program
  14575. * @param shaderProgram defines the webGL program to use
  14576. * @param attributesNames defines the list of attribute names to get
  14577. * @returns an array of indices indicating the offset of each attribute
  14578. */
  14579. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  14580. var results = [];
  14581. for (var index = 0; index < attributesNames.length; index++) {
  14582. try {
  14583. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  14584. }
  14585. catch (e) {
  14586. results.push(-1);
  14587. }
  14588. }
  14589. return results;
  14590. };
  14591. /**
  14592. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  14593. * @param effect defines the effect to activate
  14594. */
  14595. Engine.prototype.enableEffect = function (effect) {
  14596. if (!effect || effect === this._currentEffect) {
  14597. return;
  14598. }
  14599. // Use program
  14600. this.bindSamplers(effect);
  14601. this._currentEffect = effect;
  14602. if (effect.onBind) {
  14603. effect.onBind(effect);
  14604. }
  14605. if (effect._onBindObservable) {
  14606. effect._onBindObservable.notifyObservers(effect);
  14607. }
  14608. };
  14609. /**
  14610. * Set the value of an uniform to an array of int32
  14611. * @param uniform defines the webGL uniform location where to store the value
  14612. * @param array defines the array of int32 to store
  14613. */
  14614. Engine.prototype.setIntArray = function (uniform, array) {
  14615. if (!uniform)
  14616. return;
  14617. this._gl.uniform1iv(uniform, array);
  14618. };
  14619. /**
  14620. * Set the value of an uniform to an array of int32 (stored as vec2)
  14621. * @param uniform defines the webGL uniform location where to store the value
  14622. * @param array defines the array of int32 to store
  14623. */
  14624. Engine.prototype.setIntArray2 = function (uniform, array) {
  14625. if (!uniform || array.length % 2 !== 0)
  14626. return;
  14627. this._gl.uniform2iv(uniform, array);
  14628. };
  14629. /**
  14630. * Set the value of an uniform to an array of int32 (stored as vec3)
  14631. * @param uniform defines the webGL uniform location where to store the value
  14632. * @param array defines the array of int32 to store
  14633. */
  14634. Engine.prototype.setIntArray3 = function (uniform, array) {
  14635. if (!uniform || array.length % 3 !== 0)
  14636. return;
  14637. this._gl.uniform3iv(uniform, array);
  14638. };
  14639. /**
  14640. * Set the value of an uniform to an array of int32 (stored as vec4)
  14641. * @param uniform defines the webGL uniform location where to store the value
  14642. * @param array defines the array of int32 to store
  14643. */
  14644. Engine.prototype.setIntArray4 = function (uniform, array) {
  14645. if (!uniform || array.length % 4 !== 0)
  14646. return;
  14647. this._gl.uniform4iv(uniform, array);
  14648. };
  14649. /**
  14650. * Set the value of an uniform to an array of float32
  14651. * @param uniform defines the webGL uniform location where to store the value
  14652. * @param array defines the array of float32 to store
  14653. */
  14654. Engine.prototype.setFloatArray = function (uniform, array) {
  14655. if (!uniform)
  14656. return;
  14657. this._gl.uniform1fv(uniform, array);
  14658. };
  14659. /**
  14660. * Set the value of an uniform to an array of float32 (stored as vec2)
  14661. * @param uniform defines the webGL uniform location where to store the value
  14662. * @param array defines the array of float32 to store
  14663. */
  14664. Engine.prototype.setFloatArray2 = function (uniform, array) {
  14665. if (!uniform || array.length % 2 !== 0)
  14666. return;
  14667. this._gl.uniform2fv(uniform, array);
  14668. };
  14669. /**
  14670. * Set the value of an uniform to an array of float32 (stored as vec3)
  14671. * @param uniform defines the webGL uniform location where to store the value
  14672. * @param array defines the array of float32 to store
  14673. */
  14674. Engine.prototype.setFloatArray3 = function (uniform, array) {
  14675. if (!uniform || array.length % 3 !== 0)
  14676. return;
  14677. this._gl.uniform3fv(uniform, array);
  14678. };
  14679. /**
  14680. * Set the value of an uniform to an array of float32 (stored as vec4)
  14681. * @param uniform defines the webGL uniform location where to store the value
  14682. * @param array defines the array of float32 to store
  14683. */
  14684. Engine.prototype.setFloatArray4 = function (uniform, array) {
  14685. if (!uniform || array.length % 4 !== 0)
  14686. return;
  14687. this._gl.uniform4fv(uniform, array);
  14688. };
  14689. /**
  14690. * Set the value of an uniform to an array of number
  14691. * @param uniform defines the webGL uniform location where to store the value
  14692. * @param array defines the array of number to store
  14693. */
  14694. Engine.prototype.setArray = function (uniform, array) {
  14695. if (!uniform)
  14696. return;
  14697. this._gl.uniform1fv(uniform, array);
  14698. };
  14699. /**
  14700. * Set the value of an uniform to an array of number (stored as vec2)
  14701. * @param uniform defines the webGL uniform location where to store the value
  14702. * @param array defines the array of number to store
  14703. */
  14704. Engine.prototype.setArray2 = function (uniform, array) {
  14705. if (!uniform || array.length % 2 !== 0)
  14706. return;
  14707. this._gl.uniform2fv(uniform, array);
  14708. };
  14709. /**
  14710. * Set the value of an uniform to an array of number (stored as vec3)
  14711. * @param uniform defines the webGL uniform location where to store the value
  14712. * @param array defines the array of number to store
  14713. */
  14714. Engine.prototype.setArray3 = function (uniform, array) {
  14715. if (!uniform || array.length % 3 !== 0)
  14716. return;
  14717. this._gl.uniform3fv(uniform, array);
  14718. };
  14719. /**
  14720. * Set the value of an uniform to an array of number (stored as vec4)
  14721. * @param uniform defines the webGL uniform location where to store the value
  14722. * @param array defines the array of number to store
  14723. */
  14724. Engine.prototype.setArray4 = function (uniform, array) {
  14725. if (!uniform || array.length % 4 !== 0)
  14726. return;
  14727. this._gl.uniform4fv(uniform, array);
  14728. };
  14729. /**
  14730. * Set the value of an uniform to an array of float32 (stored as matrices)
  14731. * @param uniform defines the webGL uniform location where to store the value
  14732. * @param matrices defines the array of float32 to store
  14733. */
  14734. Engine.prototype.setMatrices = function (uniform, matrices) {
  14735. if (!uniform)
  14736. return;
  14737. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14738. };
  14739. /**
  14740. * Set the value of an uniform to a matrix
  14741. * @param uniform defines the webGL uniform location where to store the value
  14742. * @param matrix defines the matrix to store
  14743. */
  14744. Engine.prototype.setMatrix = function (uniform, matrix) {
  14745. if (!uniform)
  14746. return;
  14747. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14748. };
  14749. /**
  14750. * Set the value of an uniform to a matrix (3x3)
  14751. * @param uniform defines the webGL uniform location where to store the value
  14752. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14753. */
  14754. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14755. if (!uniform)
  14756. return;
  14757. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14758. };
  14759. /**
  14760. * Set the value of an uniform to a matrix (2x2)
  14761. * @param uniform defines the webGL uniform location where to store the value
  14762. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14763. */
  14764. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14765. if (!uniform)
  14766. return;
  14767. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14768. };
  14769. /**
  14770. * Set the value of an uniform to a number (int)
  14771. * @param uniform defines the webGL uniform location where to store the value
  14772. * @param value defines the int number to store
  14773. */
  14774. Engine.prototype.setInt = function (uniform, value) {
  14775. if (!uniform)
  14776. return;
  14777. this._gl.uniform1i(uniform, value);
  14778. };
  14779. /**
  14780. * Set the value of an uniform to a number (float)
  14781. * @param uniform defines the webGL uniform location where to store the value
  14782. * @param value defines the float number to store
  14783. */
  14784. Engine.prototype.setFloat = function (uniform, value) {
  14785. if (!uniform)
  14786. return;
  14787. this._gl.uniform1f(uniform, value);
  14788. };
  14789. /**
  14790. * Set the value of an uniform to a vec2
  14791. * @param uniform defines the webGL uniform location where to store the value
  14792. * @param x defines the 1st component of the value
  14793. * @param y defines the 2nd component of the value
  14794. */
  14795. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14796. if (!uniform)
  14797. return;
  14798. this._gl.uniform2f(uniform, x, y);
  14799. };
  14800. /**
  14801. * Set the value of an uniform to a vec3
  14802. * @param uniform defines the webGL uniform location where to store the value
  14803. * @param x defines the 1st component of the value
  14804. * @param y defines the 2nd component of the value
  14805. * @param z defines the 3rd component of the value
  14806. */
  14807. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14808. if (!uniform)
  14809. return;
  14810. this._gl.uniform3f(uniform, x, y, z);
  14811. };
  14812. /**
  14813. * Set the value of an uniform to a boolean
  14814. * @param uniform defines the webGL uniform location where to store the value
  14815. * @param bool defines the boolean to store
  14816. */
  14817. Engine.prototype.setBool = function (uniform, bool) {
  14818. if (!uniform)
  14819. return;
  14820. this._gl.uniform1i(uniform, bool);
  14821. };
  14822. /**
  14823. * Set the value of an uniform to a vec4
  14824. * @param uniform defines the webGL uniform location where to store the value
  14825. * @param x defines the 1st component of the value
  14826. * @param y defines the 2nd component of the value
  14827. * @param z defines the 3rd component of the value
  14828. * @param w defines the 4th component of the value
  14829. */
  14830. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14831. if (!uniform)
  14832. return;
  14833. this._gl.uniform4f(uniform, x, y, z, w);
  14834. };
  14835. /**
  14836. * Set the value of an uniform to a Color3
  14837. * @param uniform defines the webGL uniform location where to store the value
  14838. * @param color3 defines the color to store
  14839. */
  14840. Engine.prototype.setColor3 = function (uniform, color3) {
  14841. if (!uniform)
  14842. return;
  14843. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14844. };
  14845. /**
  14846. * Set the value of an uniform to a Color3 and an alpha value
  14847. * @param uniform defines the webGL uniform location where to store the value
  14848. * @param color3 defines the color to store
  14849. * @param alpha defines the alpha component to store
  14850. */
  14851. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14852. if (!uniform)
  14853. return;
  14854. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14855. };
  14856. /**
  14857. * Sets a Color4 on a uniform variable
  14858. * @param uniform defines the uniform location
  14859. * @param color4 defines the value to be set
  14860. */
  14861. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14862. if (!uniform)
  14863. return;
  14864. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14865. };
  14866. // States
  14867. /**
  14868. * Set various states to the webGL context
  14869. * @param culling defines backface culling state
  14870. * @param zOffset defines the value to apply to zOffset (0 by default)
  14871. * @param force defines if states must be applied even if cache is up to date
  14872. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14873. */
  14874. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14875. if (zOffset === void 0) { zOffset = 0; }
  14876. if (reverseSide === void 0) { reverseSide = false; }
  14877. // Culling
  14878. if (this._depthCullingState.cull !== culling || force) {
  14879. this._depthCullingState.cull = culling;
  14880. }
  14881. // Cull face
  14882. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14883. if (this._depthCullingState.cullFace !== cullFace || force) {
  14884. this._depthCullingState.cullFace = cullFace;
  14885. }
  14886. // Z offset
  14887. this.setZOffset(zOffset);
  14888. // Front face
  14889. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14890. if (this._depthCullingState.frontFace !== frontFace || force) {
  14891. this._depthCullingState.frontFace = frontFace;
  14892. }
  14893. };
  14894. /**
  14895. * Set the z offset to apply to current rendering
  14896. * @param value defines the offset to apply
  14897. */
  14898. Engine.prototype.setZOffset = function (value) {
  14899. this._depthCullingState.zOffset = value;
  14900. };
  14901. /**
  14902. * Gets the current value of the zOffset
  14903. * @returns the current zOffset state
  14904. */
  14905. Engine.prototype.getZOffset = function () {
  14906. return this._depthCullingState.zOffset;
  14907. };
  14908. /**
  14909. * Enable or disable depth buffering
  14910. * @param enable defines the state to set
  14911. */
  14912. Engine.prototype.setDepthBuffer = function (enable) {
  14913. this._depthCullingState.depthTest = enable;
  14914. };
  14915. /**
  14916. * Gets a boolean indicating if depth writing is enabled
  14917. * @returns the current depth writing state
  14918. */
  14919. Engine.prototype.getDepthWrite = function () {
  14920. return this._depthCullingState.depthMask;
  14921. };
  14922. /**
  14923. * Enable or disable depth writing
  14924. * @param enable defines the state to set
  14925. */
  14926. Engine.prototype.setDepthWrite = function (enable) {
  14927. this._depthCullingState.depthMask = enable;
  14928. };
  14929. /**
  14930. * Enable or disable color writing
  14931. * @param enable defines the state to set
  14932. */
  14933. Engine.prototype.setColorWrite = function (enable) {
  14934. this._gl.colorMask(enable, enable, enable, enable);
  14935. this._colorWrite = enable;
  14936. };
  14937. /**
  14938. * Gets a boolean indicating if color writing is enabled
  14939. * @returns the current color writing state
  14940. */
  14941. Engine.prototype.getColorWrite = function () {
  14942. return this._colorWrite;
  14943. };
  14944. /**
  14945. * Sets alpha constants used by some alpha blending modes
  14946. * @param r defines the red component
  14947. * @param g defines the green component
  14948. * @param b defines the blue component
  14949. * @param a defines the alpha component
  14950. */
  14951. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14952. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14953. };
  14954. /**
  14955. * Sets the current alpha mode
  14956. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14957. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14958. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14959. */
  14960. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14961. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14962. if (this._alphaMode === mode) {
  14963. return;
  14964. }
  14965. switch (mode) {
  14966. case Engine.ALPHA_DISABLE:
  14967. this._alphaState.alphaBlend = false;
  14968. break;
  14969. case Engine.ALPHA_PREMULTIPLIED:
  14970. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14971. this._alphaState.alphaBlend = true;
  14972. break;
  14973. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14974. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14975. this._alphaState.alphaBlend = true;
  14976. break;
  14977. case Engine.ALPHA_COMBINE:
  14978. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14979. this._alphaState.alphaBlend = true;
  14980. break;
  14981. case Engine.ALPHA_ONEONE:
  14982. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14983. this._alphaState.alphaBlend = true;
  14984. break;
  14985. case Engine.ALPHA_ADD:
  14986. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14987. this._alphaState.alphaBlend = true;
  14988. break;
  14989. case Engine.ALPHA_SUBTRACT:
  14990. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14991. this._alphaState.alphaBlend = true;
  14992. break;
  14993. case Engine.ALPHA_MULTIPLY:
  14994. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14995. this._alphaState.alphaBlend = true;
  14996. break;
  14997. case Engine.ALPHA_MAXIMIZED:
  14998. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14999. this._alphaState.alphaBlend = true;
  15000. break;
  15001. case Engine.ALPHA_INTERPOLATE:
  15002. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  15003. this._alphaState.alphaBlend = true;
  15004. break;
  15005. case Engine.ALPHA_SCREENMODE:
  15006. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  15007. this._alphaState.alphaBlend = true;
  15008. break;
  15009. }
  15010. if (!noDepthWriteChange) {
  15011. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  15012. }
  15013. this._alphaMode = mode;
  15014. };
  15015. /**
  15016. * Gets the current alpha mode
  15017. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  15018. * @returns the current alpha mode
  15019. */
  15020. Engine.prototype.getAlphaMode = function () {
  15021. return this._alphaMode;
  15022. };
  15023. // Textures
  15024. /**
  15025. * Clears the list of texture accessible through engine.
  15026. * This can help preventing texture load conflict due to name collision.
  15027. */
  15028. Engine.prototype.clearInternalTexturesCache = function () {
  15029. this._internalTexturesCache = [];
  15030. };
  15031. /**
  15032. * Force the entire cache to be cleared
  15033. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  15034. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  15035. */
  15036. Engine.prototype.wipeCaches = function (bruteForce) {
  15037. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  15038. return;
  15039. }
  15040. this._currentEffect = null;
  15041. this._viewportCached.x = 0;
  15042. this._viewportCached.y = 0;
  15043. this._viewportCached.z = 0;
  15044. this._viewportCached.w = 0;
  15045. if (bruteForce) {
  15046. this.resetTextureCache();
  15047. this._currentProgram = null;
  15048. this._stencilState.reset();
  15049. this._depthCullingState.reset();
  15050. this.setDepthFunctionToLessOrEqual();
  15051. this._alphaState.reset();
  15052. this._unpackFlipYCached = null;
  15053. }
  15054. this._resetVertexBufferBinding();
  15055. this._cachedIndexBuffer = null;
  15056. this._cachedEffectForVertexBuffers = null;
  15057. this._unbindVertexArrayObject();
  15058. this.bindIndexBuffer(null);
  15059. };
  15060. /**
  15061. * Set the compressed texture format to use, based on the formats you have, and the formats
  15062. * supported by the hardware / browser.
  15063. *
  15064. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  15065. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  15066. * to API arguments needed to compressed textures. This puts the burden on the container
  15067. * generator to house the arcane code for determining these for current & future formats.
  15068. *
  15069. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  15070. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  15071. *
  15072. * Note: The result of this call is not taken into account when a texture is base64.
  15073. *
  15074. * @param formatsAvailable defines the list of those format families you have created
  15075. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  15076. *
  15077. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  15078. * @returns The extension selected.
  15079. */
  15080. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  15081. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  15082. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  15083. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  15084. return this._textureFormatInUse = this._texturesSupported[i];
  15085. }
  15086. }
  15087. }
  15088. // actively set format to nothing, to allow this to be called more than once
  15089. // and possibly fail the 2nd time
  15090. this._textureFormatInUse = null;
  15091. return null;
  15092. };
  15093. Engine.prototype._getSamplingParameters = function (samplingMode, generateMipMaps) {
  15094. var gl = this._gl;
  15095. var magFilter = gl.NEAREST;
  15096. var minFilter = gl.NEAREST;
  15097. switch (samplingMode) {
  15098. case Engine.TEXTURE_BILINEAR_SAMPLINGMODE:
  15099. magFilter = gl.LINEAR;
  15100. if (generateMipMaps) {
  15101. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  15102. }
  15103. else {
  15104. minFilter = gl.LINEAR;
  15105. }
  15106. break;
  15107. case Engine.TEXTURE_TRILINEAR_SAMPLINGMODE:
  15108. magFilter = gl.LINEAR;
  15109. if (generateMipMaps) {
  15110. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  15111. }
  15112. else {
  15113. minFilter = gl.LINEAR;
  15114. }
  15115. break;
  15116. case Engine.TEXTURE_NEAREST_SAMPLINGMODE:
  15117. magFilter = gl.NEAREST;
  15118. if (generateMipMaps) {
  15119. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  15120. }
  15121. else {
  15122. minFilter = gl.NEAREST;
  15123. }
  15124. break;
  15125. case Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST:
  15126. magFilter = gl.NEAREST;
  15127. if (generateMipMaps) {
  15128. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  15129. }
  15130. else {
  15131. minFilter = gl.NEAREST;
  15132. }
  15133. break;
  15134. case Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST:
  15135. magFilter = gl.NEAREST;
  15136. if (generateMipMaps) {
  15137. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  15138. }
  15139. else {
  15140. minFilter = gl.LINEAR;
  15141. }
  15142. break;
  15143. case Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR:
  15144. magFilter = gl.NEAREST;
  15145. if (generateMipMaps) {
  15146. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  15147. }
  15148. else {
  15149. minFilter = gl.LINEAR;
  15150. }
  15151. break;
  15152. case Engine.TEXTURE_NEAREST_LINEAR:
  15153. magFilter = gl.NEAREST;
  15154. minFilter = gl.LINEAR;
  15155. break;
  15156. case Engine.TEXTURE_NEAREST_NEAREST:
  15157. magFilter = gl.NEAREST;
  15158. minFilter = gl.NEAREST;
  15159. break;
  15160. case Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST:
  15161. magFilter = gl.LINEAR;
  15162. if (generateMipMaps) {
  15163. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  15164. }
  15165. else {
  15166. minFilter = gl.NEAREST;
  15167. }
  15168. break;
  15169. case Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR:
  15170. magFilter = gl.LINEAR;
  15171. if (generateMipMaps) {
  15172. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  15173. }
  15174. else {
  15175. minFilter = gl.NEAREST;
  15176. }
  15177. break;
  15178. case Engine.TEXTURE_LINEAR_LINEAR:
  15179. magFilter = gl.LINEAR;
  15180. minFilter = gl.LINEAR;
  15181. break;
  15182. case Engine.TEXTURE_LINEAR_NEAREST:
  15183. magFilter = gl.LINEAR;
  15184. minFilter = gl.NEAREST;
  15185. break;
  15186. }
  15187. return {
  15188. min: minFilter,
  15189. mag: magFilter
  15190. };
  15191. };
  15192. Engine.prototype._partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  15193. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  15194. var img;
  15195. var onload = function () {
  15196. loadedImages[index] = img;
  15197. loadedImages._internalCount++;
  15198. if (scene) {
  15199. scene._removePendingData(img);
  15200. }
  15201. if (loadedImages._internalCount === 6) {
  15202. onfinish(loadedImages);
  15203. }
  15204. };
  15205. var onerror = function (message, exception) {
  15206. if (scene) {
  15207. scene._removePendingData(img);
  15208. }
  15209. if (onErrorCallBack) {
  15210. onErrorCallBack(message, exception);
  15211. }
  15212. };
  15213. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  15214. if (scene) {
  15215. scene._addPendingData(img);
  15216. }
  15217. };
  15218. Engine.prototype._cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  15219. if (onError === void 0) { onError = null; }
  15220. var loadedImages = [];
  15221. loadedImages._internalCount = 0;
  15222. for (var index = 0; index < 6; index++) {
  15223. this._partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  15224. }
  15225. };
  15226. ;
  15227. /** @hidden */
  15228. Engine.prototype._createTexture = function () {
  15229. var texture = this._gl.createTexture();
  15230. if (!texture) {
  15231. throw new Error("Unable to create texture");
  15232. }
  15233. return texture;
  15234. };
  15235. /**
  15236. * Usually called from BABYLON.Texture.ts.
  15237. * Passed information to create a WebGLTexture
  15238. * @param urlArg defines a value which contains one of the following:
  15239. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  15240. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  15241. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  15242. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  15243. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  15244. * @param scene needed for loading to the correct scene
  15245. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  15246. * @param onLoad optional callback to be called upon successful completion
  15247. * @param onError optional callback to be called upon failure
  15248. * @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
  15249. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  15250. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  15251. * @param forcedExtension defines the extension to use to pick the right loader
  15252. * @returns a InternalTexture for assignment back into BABYLON.Texture
  15253. */
  15254. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format, forcedExtension) {
  15255. var _this = this;
  15256. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  15257. if (onLoad === void 0) { onLoad = null; }
  15258. if (onError === void 0) { onError = null; }
  15259. if (buffer === void 0) { buffer = null; }
  15260. if (fallback === void 0) { fallback = null; }
  15261. if (format === void 0) { format = null; }
  15262. if (forcedExtension === void 0) { forcedExtension = null; }
  15263. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  15264. var fromData = url.substr(0, 5) === "data:";
  15265. var fromBlob = url.substr(0, 5) === "blob:";
  15266. var isBase64 = fromData && url.indexOf(";base64,") !== -1;
  15267. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  15268. // establish the file extension, if possible
  15269. var lastDot = url.lastIndexOf('.');
  15270. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? url.substring(lastDot).toLowerCase() : "");
  15271. var loader = null;
  15272. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  15273. var availableLoader = _a[_i];
  15274. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, isBase64, buffer ? true : false)) {
  15275. loader = availableLoader;
  15276. break;
  15277. }
  15278. }
  15279. if (loader) {
  15280. url = loader.transformUrl(url, this._textureFormatInUse);
  15281. }
  15282. if (scene) {
  15283. scene._addPendingData(texture);
  15284. }
  15285. texture.url = url;
  15286. texture.generateMipMaps = !noMipmap;
  15287. texture.samplingMode = samplingMode;
  15288. texture.invertY = invertY;
  15289. if (!this._doNotHandleContextLost) {
  15290. // Keep a link to the buffer only if we plan to handle context lost
  15291. texture._buffer = buffer;
  15292. }
  15293. var onLoadObserver = null;
  15294. if (onLoad && !fallback) {
  15295. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  15296. }
  15297. if (!fallback)
  15298. this._internalTexturesCache.push(texture);
  15299. var onInternalError = function (message, exception) {
  15300. if (scene) {
  15301. scene._removePendingData(texture);
  15302. }
  15303. var customFallback = false;
  15304. if (loader) {
  15305. var fallbackUrl = loader.getFallbackTextureUrl(url, _this._textureFormatInUse);
  15306. if (fallbackUrl) {
  15307. // Add Back
  15308. customFallback = true;
  15309. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  15310. }
  15311. }
  15312. if (!customFallback) {
  15313. if (onLoadObserver) {
  15314. texture.onLoadedObservable.remove(onLoadObserver);
  15315. }
  15316. if (BABYLON.Tools.UseFallbackTexture) {
  15317. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  15318. }
  15319. }
  15320. if (onError) {
  15321. onError(message || "Unknown error", exception);
  15322. }
  15323. };
  15324. // processing for non-image formats
  15325. if (loader) {
  15326. var callback = function (data) {
  15327. loader.loadData(data, texture, function (width, height, loadMipmap, isCompressed, done) {
  15328. _this._prepareWebGLTexture(texture, scene, width, height, invertY, !loadMipmap, isCompressed, function () {
  15329. done();
  15330. return false;
  15331. }, samplingMode);
  15332. });
  15333. };
  15334. if (!buffer) {
  15335. this._loadFile(url, callback, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  15336. onInternalError("Unable to load " + (request ? request.responseURL : url, exception));
  15337. });
  15338. }
  15339. else {
  15340. callback(buffer);
  15341. }
  15342. }
  15343. else {
  15344. var onload = function (img) {
  15345. if (fromBlob && !_this._doNotHandleContextLost) {
  15346. // We need to store the image if we need to rebuild the texture
  15347. // in case of a webgl context lost
  15348. texture._buffer = img;
  15349. }
  15350. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  15351. var gl = _this._gl;
  15352. var isPot = (img.width === potWidth && img.height === potHeight);
  15353. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  15354. if (isPot) {
  15355. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  15356. return false;
  15357. }
  15358. var maxTextureSize = _this._caps.maxTextureSize;
  15359. if (img.width > maxTextureSize || img.height > maxTextureSize) {
  15360. _this._prepareWorkingCanvas();
  15361. if (!_this._workingCanvas || !_this._workingContext) {
  15362. return false;
  15363. }
  15364. _this._workingCanvas.width = potWidth;
  15365. _this._workingCanvas.height = potHeight;
  15366. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  15367. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15368. texture.width = potWidth;
  15369. texture.height = potHeight;
  15370. return false;
  15371. }
  15372. else {
  15373. // Using shaders when possible to rescale because canvas.drawImage is lossy
  15374. var source_1 = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15375. _this._bindTextureDirectly(gl.TEXTURE_2D, source_1, true);
  15376. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  15377. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15378. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15379. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15380. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15381. _this._rescaleTexture(source_1, texture, scene, internalFormat, function () {
  15382. _this._releaseTexture(source_1);
  15383. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15384. continuationCallback();
  15385. });
  15386. }
  15387. return true;
  15388. }, samplingMode);
  15389. };
  15390. if (!fromData || isBase64) {
  15391. if (buffer instanceof HTMLImageElement) {
  15392. onload(buffer);
  15393. }
  15394. else {
  15395. BABYLON.Tools.LoadImage(url, onload, onInternalError, scene ? scene.database : null);
  15396. }
  15397. }
  15398. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  15399. BABYLON.Tools.LoadImage(buffer, onload, onInternalError, scene ? scene.database : null);
  15400. }
  15401. else {
  15402. onload(buffer);
  15403. }
  15404. }
  15405. return texture;
  15406. };
  15407. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  15408. var _this = this;
  15409. var rtt = this.createRenderTargetTexture({
  15410. width: destination.width,
  15411. height: destination.height,
  15412. }, {
  15413. generateMipMaps: false,
  15414. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  15415. samplingMode: Engine.TEXTURE_BILINEAR_SAMPLINGMODE,
  15416. generateDepthBuffer: false,
  15417. generateStencilBuffer: false
  15418. });
  15419. if (!this._rescalePostProcess) {
  15420. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, Engine.TEXTURE_BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  15421. }
  15422. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  15423. _this._rescalePostProcess.onApply = function (effect) {
  15424. effect._bindTexture("textureSampler", source);
  15425. };
  15426. var hostingScene = scene;
  15427. if (!hostingScene) {
  15428. hostingScene = _this.scenes[_this.scenes.length - 1];
  15429. }
  15430. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  15431. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  15432. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  15433. _this.unBindFramebuffer(rtt);
  15434. _this._releaseTexture(rtt);
  15435. if (onComplete) {
  15436. onComplete();
  15437. }
  15438. });
  15439. };
  15440. /**
  15441. * Update a raw texture
  15442. * @param texture defines the texture to update
  15443. * @param data defines the data to store in the texture
  15444. * @param format defines the format of the data
  15445. * @param invertY defines if data must be stored with Y axis inverted
  15446. * @param compression defines the compression used (null by default)
  15447. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15448. */
  15449. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  15450. if (compression === void 0) { compression = null; }
  15451. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15452. if (!texture) {
  15453. return;
  15454. }
  15455. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  15456. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  15457. // babylon's internalFormat but gl's texImage2D format
  15458. var internalFormat = this._getInternalFormat(format);
  15459. var textureType = this._getWebGLTextureType(type);
  15460. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15461. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15462. if (!this._doNotHandleContextLost) {
  15463. texture._bufferView = data;
  15464. texture.format = format;
  15465. texture.type = type;
  15466. texture.invertY = invertY;
  15467. texture._compression = compression;
  15468. }
  15469. if (texture.width % 4 !== 0) {
  15470. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  15471. }
  15472. if (compression && data) {
  15473. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  15474. }
  15475. else {
  15476. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  15477. }
  15478. if (texture.generateMipMaps) {
  15479. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15480. }
  15481. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15482. // this.resetTextureCache();
  15483. texture.isReady = true;
  15484. };
  15485. /**
  15486. * Creates a raw texture
  15487. * @param data defines the data to store in the texture
  15488. * @param width defines the width of the texture
  15489. * @param height defines the height of the texture
  15490. * @param format defines the format of the data
  15491. * @param generateMipMaps defines if the engine should generate the mip levels
  15492. * @param invertY defines if data must be stored with Y axis inverted
  15493. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  15494. * @param compression defines the compression used (null by default)
  15495. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15496. * @returns the raw texture inside an InternalTexture
  15497. */
  15498. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  15499. if (compression === void 0) { compression = null; }
  15500. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15501. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  15502. texture.baseWidth = width;
  15503. texture.baseHeight = height;
  15504. texture.width = width;
  15505. texture.height = height;
  15506. texture.format = format;
  15507. texture.generateMipMaps = generateMipMaps;
  15508. texture.samplingMode = samplingMode;
  15509. texture.invertY = invertY;
  15510. texture._compression = compression;
  15511. texture.type = type;
  15512. if (!this._doNotHandleContextLost) {
  15513. texture._bufferView = data;
  15514. }
  15515. this.updateRawTexture(texture, data, format, invertY, compression, type);
  15516. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15517. // Filters
  15518. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15519. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  15520. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15521. if (generateMipMaps) {
  15522. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15523. }
  15524. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15525. this._internalTexturesCache.push(texture);
  15526. return texture;
  15527. };
  15528. /** @hidden */
  15529. Engine.prototype._unpackFlipY = function (value) {
  15530. if (this._unpackFlipYCached !== value) {
  15531. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
  15532. if (this.enableUnpackFlipYCached) {
  15533. this._unpackFlipYCached = value;
  15534. }
  15535. }
  15536. };
  15537. /** @hidden */
  15538. Engine.prototype._getUnpackAlignement = function () {
  15539. return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT);
  15540. };
  15541. /**
  15542. * Creates a dynamic texture
  15543. * @param width defines the width of the texture
  15544. * @param height defines the height of the texture
  15545. * @param generateMipMaps defines if the engine should generate the mip levels
  15546. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  15547. * @returns the dynamic texture inside an InternalTexture
  15548. */
  15549. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  15550. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  15551. texture.baseWidth = width;
  15552. texture.baseHeight = height;
  15553. if (generateMipMaps) {
  15554. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  15555. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  15556. }
  15557. // this.resetTextureCache();
  15558. texture.width = width;
  15559. texture.height = height;
  15560. texture.isReady = false;
  15561. texture.generateMipMaps = generateMipMaps;
  15562. texture.samplingMode = samplingMode;
  15563. this.updateTextureSamplingMode(samplingMode, texture);
  15564. this._internalTexturesCache.push(texture);
  15565. return texture;
  15566. };
  15567. /**
  15568. * Update the sampling mode of a given texture
  15569. * @param samplingMode defines the required sampling mode
  15570. * @param texture defines the texture to update
  15571. */
  15572. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  15573. var filters = this._getSamplingParameters(samplingMode, texture.generateMipMaps);
  15574. if (texture.isCube) {
  15575. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15576. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15577. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15578. }
  15579. else if (texture.is3D) {
  15580. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15581. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15582. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15583. }
  15584. else {
  15585. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15586. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15587. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15588. }
  15589. texture.samplingMode = samplingMode;
  15590. };
  15591. /**
  15592. * Update the content of a dynamic texture
  15593. * @param texture defines the texture to update
  15594. * @param canvas defines the canvas containing the source
  15595. * @param invertY defines if data must be stored with Y axis inverted
  15596. * @param premulAlpha defines if alpha is stored as premultiplied
  15597. * @param format defines the format of the data
  15598. */
  15599. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  15600. if (premulAlpha === void 0) { premulAlpha = false; }
  15601. if (!texture) {
  15602. return;
  15603. }
  15604. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15605. this._unpackFlipY(invertY);
  15606. if (premulAlpha) {
  15607. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  15608. }
  15609. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  15610. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  15611. if (texture.generateMipMaps) {
  15612. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15613. }
  15614. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15615. if (premulAlpha) {
  15616. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  15617. }
  15618. texture.isReady = true;
  15619. };
  15620. /**
  15621. * Update a video texture
  15622. * @param texture defines the texture to update
  15623. * @param video defines the video element to use
  15624. * @param invertY defines if data must be stored with Y axis inverted
  15625. */
  15626. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  15627. if (!texture || texture._isDisabled) {
  15628. return;
  15629. }
  15630. var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15631. this._unpackFlipY(!invertY); // Video are upside down by default
  15632. try {
  15633. // Testing video texture support
  15634. if (this._videoTextureSupported === undefined) {
  15635. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  15636. if (this._gl.getError() !== 0) {
  15637. this._videoTextureSupported = false;
  15638. }
  15639. else {
  15640. this._videoTextureSupported = true;
  15641. }
  15642. }
  15643. // Copy video through the current working canvas if video texture is not supported
  15644. if (!this._videoTextureSupported) {
  15645. if (!texture._workingCanvas) {
  15646. texture._workingCanvas = document.createElement("canvas");
  15647. var context = texture._workingCanvas.getContext("2d");
  15648. if (!context) {
  15649. throw new Error("Unable to get 2d context");
  15650. }
  15651. texture._workingContext = context;
  15652. texture._workingCanvas.width = texture.width;
  15653. texture._workingCanvas.height = texture.height;
  15654. }
  15655. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  15656. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  15657. }
  15658. else {
  15659. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  15660. }
  15661. if (texture.generateMipMaps) {
  15662. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15663. }
  15664. if (!wasPreviouslyBound) {
  15665. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15666. }
  15667. // this.resetTextureCache();
  15668. texture.isReady = true;
  15669. }
  15670. catch (ex) {
  15671. // Something unexpected
  15672. // Let's disable the texture
  15673. texture._isDisabled = true;
  15674. }
  15675. };
  15676. /**
  15677. * Updates a depth texture Comparison Mode and Function.
  15678. * If the comparison Function is equal to 0, the mode will be set to none.
  15679. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  15680. * @param texture The texture to set the comparison function for
  15681. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  15682. */
  15683. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  15684. if (this.webGLVersion === 1) {
  15685. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  15686. return;
  15687. }
  15688. var gl = this._gl;
  15689. if (texture.isCube) {
  15690. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15691. if (comparisonFunction === 0) {
  15692. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15693. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15694. }
  15695. else {
  15696. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15697. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15698. }
  15699. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15700. }
  15701. else {
  15702. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15703. if (comparisonFunction === 0) {
  15704. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15705. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15706. }
  15707. else {
  15708. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15709. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15710. }
  15711. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15712. }
  15713. texture._comparisonFunction = comparisonFunction;
  15714. };
  15715. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  15716. var width = size.width || size;
  15717. var height = size.height || size;
  15718. internalTexture.baseWidth = width;
  15719. internalTexture.baseHeight = height;
  15720. internalTexture.width = width;
  15721. internalTexture.height = height;
  15722. internalTexture.isReady = true;
  15723. internalTexture.samples = 1;
  15724. internalTexture.generateMipMaps = false;
  15725. internalTexture._generateDepthBuffer = true;
  15726. internalTexture._generateStencilBuffer = generateStencil;
  15727. internalTexture.samplingMode = bilinearFiltering ? Engine.TEXTURE_BILINEAR_SAMPLINGMODE : Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15728. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15729. internalTexture._comparisonFunction = comparisonFunction;
  15730. var gl = this._gl;
  15731. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15732. var samplingParameters = this._getSamplingParameters(internalTexture.samplingMode, false);
  15733. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  15734. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  15735. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15736. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15737. if (comparisonFunction === 0) {
  15738. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15739. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15740. }
  15741. else {
  15742. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15743. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15744. }
  15745. };
  15746. /**
  15747. * Creates a depth stencil texture.
  15748. * This is only available in WebGL 2 or with the depth texture extension available.
  15749. * @param size The size of face edge in the texture.
  15750. * @param options The options defining the texture.
  15751. * @returns The texture
  15752. */
  15753. Engine.prototype.createDepthStencilTexture = function (size, options) {
  15754. if (options.isCube) {
  15755. var width = size.width || size;
  15756. return this._createDepthStencilCubeTexture(width, options);
  15757. }
  15758. else {
  15759. return this._createDepthStencilTexture(size, options);
  15760. }
  15761. };
  15762. /**
  15763. * Creates a depth stencil texture.
  15764. * This is only available in WebGL 2 or with the depth texture extension available.
  15765. * @param size The size of face edge in the texture.
  15766. * @param options The options defining the texture.
  15767. * @returns The texture
  15768. */
  15769. Engine.prototype._createDepthStencilTexture = function (size, options) {
  15770. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  15771. if (!this._caps.depthTextureExtension) {
  15772. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  15773. return internalTexture;
  15774. }
  15775. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15776. var gl = this._gl;
  15777. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  15778. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15779. if (this.webGLVersion > 1) {
  15780. if (internalOptions.generateStencil) {
  15781. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15782. }
  15783. else {
  15784. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15785. }
  15786. }
  15787. else {
  15788. if (internalOptions.generateStencil) {
  15789. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15790. }
  15791. else {
  15792. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15793. }
  15794. }
  15795. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15796. return internalTexture;
  15797. };
  15798. /**
  15799. * Creates a depth stencil cube texture.
  15800. * This is only available in WebGL 2.
  15801. * @param size The size of face edge in the cube texture.
  15802. * @param options The options defining the cube texture.
  15803. * @returns The cube texture
  15804. */
  15805. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  15806. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  15807. internalTexture.isCube = true;
  15808. if (this.webGLVersion === 1) {
  15809. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  15810. return internalTexture;
  15811. }
  15812. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15813. var gl = this._gl;
  15814. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  15815. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15816. // Create the depth/stencil buffer
  15817. for (var face = 0; face < 6; face++) {
  15818. if (internalOptions.generateStencil) {
  15819. 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);
  15820. }
  15821. else {
  15822. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15823. }
  15824. }
  15825. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15826. return internalTexture;
  15827. };
  15828. /**
  15829. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15830. * @param renderTarget The render target to set the frame buffer for
  15831. */
  15832. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15833. // Create the framebuffer
  15834. var internalTexture = renderTarget.getInternalTexture();
  15835. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15836. return;
  15837. }
  15838. var gl = this._gl;
  15839. var depthStencilTexture = renderTarget.depthStencilTexture;
  15840. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15841. if (depthStencilTexture.isCube) {
  15842. if (depthStencilTexture._generateStencilBuffer) {
  15843. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15844. }
  15845. else {
  15846. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15847. }
  15848. }
  15849. else {
  15850. if (depthStencilTexture._generateStencilBuffer) {
  15851. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15852. }
  15853. else {
  15854. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15855. }
  15856. }
  15857. this.bindUnboundFramebuffer(null);
  15858. };
  15859. /**
  15860. * Creates a new render target texture
  15861. * @param size defines the size of the texture
  15862. * @param options defines the options used to create the texture
  15863. * @returns a new render target texture stored in an InternalTexture
  15864. */
  15865. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15866. var fullOptions = new RenderTargetCreationOptions();
  15867. if (options !== undefined && typeof options === "object") {
  15868. fullOptions.generateMipMaps = options.generateMipMaps;
  15869. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15870. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15871. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15872. fullOptions.samplingMode = options.samplingMode === undefined ? Engine.TEXTURE_TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15873. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15874. }
  15875. else {
  15876. fullOptions.generateMipMaps = options;
  15877. fullOptions.generateDepthBuffer = true;
  15878. fullOptions.generateStencilBuffer = false;
  15879. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15880. fullOptions.samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15881. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15882. }
  15883. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15884. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15885. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15886. }
  15887. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15888. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15889. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15890. }
  15891. var gl = this._gl;
  15892. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15893. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15894. var width = size.width || size;
  15895. var height = size.height || size;
  15896. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false);
  15897. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15898. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15899. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15900. }
  15901. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15902. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15903. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15904. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15905. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15906. // Create the framebuffer
  15907. var currentFrameBuffer = this._currentFramebuffer;
  15908. var framebuffer = gl.createFramebuffer();
  15909. this.bindUnboundFramebuffer(framebuffer);
  15910. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15911. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15912. if (fullOptions.generateMipMaps) {
  15913. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15914. }
  15915. // Unbind
  15916. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15917. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15918. this.bindUnboundFramebuffer(currentFrameBuffer);
  15919. texture._framebuffer = framebuffer;
  15920. texture.baseWidth = width;
  15921. texture.baseHeight = height;
  15922. texture.width = width;
  15923. texture.height = height;
  15924. texture.isReady = true;
  15925. texture.samples = 1;
  15926. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15927. texture.samplingMode = fullOptions.samplingMode;
  15928. texture.type = fullOptions.type;
  15929. texture.format = fullOptions.format;
  15930. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15931. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15932. // this.resetTextureCache();
  15933. this._internalTexturesCache.push(texture);
  15934. return texture;
  15935. };
  15936. /**
  15937. * Create a multi render target texture
  15938. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15939. * @param size defines the size of the texture
  15940. * @param options defines the creation options
  15941. * @returns the cube texture as an InternalTexture
  15942. */
  15943. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15944. var generateMipMaps = false;
  15945. var generateDepthBuffer = true;
  15946. var generateStencilBuffer = false;
  15947. var generateDepthTexture = false;
  15948. var textureCount = 1;
  15949. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15950. var defaultSamplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15951. var types = new Array();
  15952. var samplingModes = new Array();
  15953. if (options !== undefined) {
  15954. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15955. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15956. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15957. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15958. textureCount = options.textureCount || 1;
  15959. if (options.types) {
  15960. types = options.types;
  15961. }
  15962. if (options.samplingModes) {
  15963. samplingModes = options.samplingModes;
  15964. }
  15965. }
  15966. var gl = this._gl;
  15967. // Create the framebuffer
  15968. var framebuffer = gl.createFramebuffer();
  15969. this.bindUnboundFramebuffer(framebuffer);
  15970. var width = size.width || size;
  15971. var height = size.height || size;
  15972. var textures = [];
  15973. var attachments = [];
  15974. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15975. for (var i = 0; i < textureCount; i++) {
  15976. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15977. var type = types[i] || defaultType;
  15978. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15979. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15980. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15981. }
  15982. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15983. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15984. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15985. }
  15986. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15987. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15988. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15989. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15990. }
  15991. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15992. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15993. textures.push(texture);
  15994. attachments.push(attachment);
  15995. gl.activeTexture(gl["TEXTURE" + i]);
  15996. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15997. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15998. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15999. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16000. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16001. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  16002. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  16003. if (generateMipMaps) {
  16004. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  16005. }
  16006. // Unbind
  16007. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16008. texture._framebuffer = framebuffer;
  16009. texture._depthStencilBuffer = depthStencilBuffer;
  16010. texture.baseWidth = width;
  16011. texture.baseHeight = height;
  16012. texture.width = width;
  16013. texture.height = height;
  16014. texture.isReady = true;
  16015. texture.samples = 1;
  16016. texture.generateMipMaps = generateMipMaps;
  16017. texture.samplingMode = samplingMode;
  16018. texture.type = type;
  16019. texture._generateDepthBuffer = generateDepthBuffer;
  16020. texture._generateStencilBuffer = generateStencilBuffer;
  16021. texture._attachments = attachments;
  16022. this._internalTexturesCache.push(texture);
  16023. }
  16024. if (generateDepthTexture && this._caps.depthTextureExtension) {
  16025. // Depth texture
  16026. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  16027. gl.activeTexture(gl.TEXTURE0);
  16028. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  16029. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16030. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16031. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16032. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16033. 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);
  16034. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  16035. depthTexture._framebuffer = framebuffer;
  16036. depthTexture.baseWidth = width;
  16037. depthTexture.baseHeight = height;
  16038. depthTexture.width = width;
  16039. depthTexture.height = height;
  16040. depthTexture.isReady = true;
  16041. depthTexture.samples = 1;
  16042. depthTexture.generateMipMaps = generateMipMaps;
  16043. depthTexture.samplingMode = gl.NEAREST;
  16044. depthTexture._generateDepthBuffer = generateDepthBuffer;
  16045. depthTexture._generateStencilBuffer = generateStencilBuffer;
  16046. textures.push(depthTexture);
  16047. this._internalTexturesCache.push(depthTexture);
  16048. }
  16049. gl.drawBuffers(attachments);
  16050. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  16051. this.bindUnboundFramebuffer(null);
  16052. this.resetTextureCache();
  16053. return textures;
  16054. };
  16055. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  16056. if (samples === void 0) { samples = 1; }
  16057. var depthStencilBuffer = null;
  16058. var gl = this._gl;
  16059. // Create the depth/stencil buffer
  16060. if (generateStencilBuffer) {
  16061. depthStencilBuffer = gl.createRenderbuffer();
  16062. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  16063. if (samples > 1) {
  16064. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  16065. }
  16066. else {
  16067. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  16068. }
  16069. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  16070. }
  16071. else if (generateDepthBuffer) {
  16072. depthStencilBuffer = gl.createRenderbuffer();
  16073. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  16074. if (samples > 1) {
  16075. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  16076. }
  16077. else {
  16078. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  16079. }
  16080. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  16081. }
  16082. return depthStencilBuffer;
  16083. };
  16084. /**
  16085. * Updates the sample count of a render target texture
  16086. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  16087. * @param texture defines the texture to update
  16088. * @param samples defines the sample count to set
  16089. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  16090. */
  16091. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  16092. if (this.webGLVersion < 2 || !texture) {
  16093. return 1;
  16094. }
  16095. if (texture.samples === samples) {
  16096. return samples;
  16097. }
  16098. var gl = this._gl;
  16099. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  16100. // Dispose previous render buffers
  16101. if (texture._depthStencilBuffer) {
  16102. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16103. texture._depthStencilBuffer = null;
  16104. }
  16105. if (texture._MSAAFramebuffer) {
  16106. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16107. texture._MSAAFramebuffer = null;
  16108. }
  16109. if (texture._MSAARenderBuffer) {
  16110. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16111. texture._MSAARenderBuffer = null;
  16112. }
  16113. if (samples > 1) {
  16114. var framebuffer = gl.createFramebuffer();
  16115. if (!framebuffer) {
  16116. throw new Error("Unable to create multi sampled framebuffer");
  16117. }
  16118. texture._MSAAFramebuffer = framebuffer;
  16119. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  16120. var colorRenderbuffer = gl.createRenderbuffer();
  16121. if (!colorRenderbuffer) {
  16122. throw new Error("Unable to create multi sampled framebuffer");
  16123. }
  16124. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  16125. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  16126. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  16127. texture._MSAARenderBuffer = colorRenderbuffer;
  16128. }
  16129. else {
  16130. this.bindUnboundFramebuffer(texture._framebuffer);
  16131. }
  16132. texture.samples = samples;
  16133. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  16134. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  16135. this.bindUnboundFramebuffer(null);
  16136. return samples;
  16137. };
  16138. /**
  16139. * Update the sample count for a given multiple render target texture
  16140. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  16141. * @param textures defines the textures to update
  16142. * @param samples defines the sample count to set
  16143. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  16144. */
  16145. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  16146. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  16147. return 1;
  16148. }
  16149. if (textures[0].samples === samples) {
  16150. return samples;
  16151. }
  16152. var gl = this._gl;
  16153. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  16154. // Dispose previous render buffers
  16155. if (textures[0]._depthStencilBuffer) {
  16156. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  16157. textures[0]._depthStencilBuffer = null;
  16158. }
  16159. if (textures[0]._MSAAFramebuffer) {
  16160. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  16161. textures[0]._MSAAFramebuffer = null;
  16162. }
  16163. for (var i = 0; i < textures.length; i++) {
  16164. if (textures[i]._MSAARenderBuffer) {
  16165. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  16166. textures[i]._MSAARenderBuffer = null;
  16167. }
  16168. }
  16169. if (samples > 1) {
  16170. var framebuffer = gl.createFramebuffer();
  16171. if (!framebuffer) {
  16172. throw new Error("Unable to create multi sampled framebuffer");
  16173. }
  16174. this.bindUnboundFramebuffer(framebuffer);
  16175. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  16176. var attachments = [];
  16177. for (var i = 0; i < textures.length; i++) {
  16178. var texture = textures[i];
  16179. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  16180. var colorRenderbuffer = gl.createRenderbuffer();
  16181. if (!colorRenderbuffer) {
  16182. throw new Error("Unable to create multi sampled framebuffer");
  16183. }
  16184. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  16185. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  16186. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  16187. texture._MSAAFramebuffer = framebuffer;
  16188. texture._MSAARenderBuffer = colorRenderbuffer;
  16189. texture.samples = samples;
  16190. texture._depthStencilBuffer = depthStencilBuffer;
  16191. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  16192. attachments.push(attachment);
  16193. }
  16194. gl.drawBuffers(attachments);
  16195. }
  16196. else {
  16197. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  16198. }
  16199. this.bindUnboundFramebuffer(null);
  16200. return samples;
  16201. };
  16202. /** @hidden */
  16203. Engine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  16204. if (faceIndex === void 0) { faceIndex = 0; }
  16205. if (lod === void 0) { lod = 0; }
  16206. var gl = this._gl;
  16207. var target = gl.TEXTURE_2D;
  16208. if (texture.isCube) {
  16209. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  16210. }
  16211. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  16212. };
  16213. /** @hidden */
  16214. Engine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  16215. if (faceIndex === void 0) { faceIndex = 0; }
  16216. if (lod === void 0) { lod = 0; }
  16217. var gl = this._gl;
  16218. var textureType = this._getWebGLTextureType(texture.type);
  16219. var format = this._getInternalFormat(texture.format);
  16220. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  16221. this._unpackFlipY(texture.invertY);
  16222. var target = gl.TEXTURE_2D;
  16223. if (texture.isCube) {
  16224. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  16225. }
  16226. var lodMaxWidth = Math.round(BABYLON.Scalar.Log2(texture.width));
  16227. var lodMaxHeight = Math.round(BABYLON.Scalar.Log2(texture.height));
  16228. var width = Math.pow(2, Math.max(lodMaxWidth - lod, 0));
  16229. var height = Math.pow(2, Math.max(lodMaxHeight - lod, 0));
  16230. gl.texImage2D(target, lod, internalFormat, width, height, 0, format, textureType, imageData);
  16231. };
  16232. /** @hidden */
  16233. Engine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  16234. if (faceIndex === void 0) { faceIndex = 0; }
  16235. if (lod === void 0) { lod = 0; }
  16236. var gl = this._gl;
  16237. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  16238. this._bindTextureDirectly(bindTarget, texture, true);
  16239. this._uploadDataToTextureDirectly(texture, imageData, faceIndex, lod);
  16240. this._bindTextureDirectly(bindTarget, null, true);
  16241. };
  16242. /** @hidden */
  16243. Engine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  16244. if (faceIndex === void 0) { faceIndex = 0; }
  16245. if (lod === void 0) { lod = 0; }
  16246. var gl = this._gl;
  16247. var textureType = this._getWebGLTextureType(texture.type);
  16248. var format = this._getInternalFormat(texture.format);
  16249. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  16250. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  16251. this._bindTextureDirectly(bindTarget, texture, true);
  16252. this._unpackFlipY(texture.invertY);
  16253. var target = gl.TEXTURE_2D;
  16254. if (texture.isCube) {
  16255. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  16256. }
  16257. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  16258. this._bindTextureDirectly(bindTarget, null, true);
  16259. };
  16260. /**
  16261. * Creates a new render target cube texture
  16262. * @param size defines the size of the texture
  16263. * @param options defines the options used to create the texture
  16264. * @returns a new render target cube texture stored in an InternalTexture
  16265. */
  16266. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  16267. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: Engine.TEXTURE_TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  16268. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  16269. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  16270. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  16271. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16272. }
  16273. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  16274. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  16275. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16276. }
  16277. var gl = this._gl;
  16278. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  16279. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16280. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps);
  16281. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  16282. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  16283. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  16284. }
  16285. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  16286. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  16287. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16288. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16289. for (var face = 0; face < 6; face++) {
  16290. 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);
  16291. }
  16292. // Create the framebuffer
  16293. var framebuffer = gl.createFramebuffer();
  16294. this.bindUnboundFramebuffer(framebuffer);
  16295. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  16296. // MipMaps
  16297. if (fullOptions.generateMipMaps) {
  16298. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  16299. }
  16300. // Unbind
  16301. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16302. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  16303. this.bindUnboundFramebuffer(null);
  16304. texture._framebuffer = framebuffer;
  16305. texture.width = size;
  16306. texture.height = size;
  16307. texture.isReady = true;
  16308. texture.isCube = true;
  16309. texture.samples = 1;
  16310. texture.generateMipMaps = fullOptions.generateMipMaps;
  16311. texture.samplingMode = fullOptions.samplingMode;
  16312. texture.type = fullOptions.type;
  16313. texture.format = fullOptions.format;
  16314. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  16315. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  16316. this._internalTexturesCache.push(texture);
  16317. return texture;
  16318. };
  16319. /**
  16320. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  16321. * @param rootUrl defines the url where the file to load is located
  16322. * @param scene defines the current scene
  16323. * @param lodScale defines scale to apply to the mip map selection
  16324. * @param lodOffset defines offset to apply to the mip map selection
  16325. * @param onLoad defines an optional callback raised when the texture is loaded
  16326. * @param onError defines an optional callback raised if there is an issue to load the texture
  16327. * @param format defines the format of the data
  16328. * @param forcedExtension defines the extension to use to pick the right loader
  16329. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  16330. * @returns the cube texture as an InternalTexture
  16331. */
  16332. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
  16333. var _this = this;
  16334. if (onLoad === void 0) { onLoad = null; }
  16335. if (onError === void 0) { onError = null; }
  16336. if (forcedExtension === void 0) { forcedExtension = null; }
  16337. if (createPolynomials === void 0) { createPolynomials = true; }
  16338. var callback = function (loadData) {
  16339. if (!loadData) {
  16340. if (onLoad) {
  16341. onLoad(null);
  16342. }
  16343. return;
  16344. }
  16345. var texture = loadData.texture;
  16346. if (!createPolynomials) {
  16347. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  16348. }
  16349. else if (loadData.info.sphericalPolynomial) {
  16350. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  16351. }
  16352. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  16353. if (_this._caps.textureLOD) {
  16354. // Do not add extra process if texture lod is supported.
  16355. if (onLoad) {
  16356. onLoad(texture);
  16357. }
  16358. return;
  16359. }
  16360. var mipSlices = 3;
  16361. var gl = _this._gl;
  16362. var width = loadData.width;
  16363. if (!width) {
  16364. return;
  16365. }
  16366. var textures = [];
  16367. for (var i = 0; i < mipSlices; i++) {
  16368. //compute LOD from even spacing in smoothness (matching shader calculation)
  16369. var smoothness = i / (mipSlices - 1);
  16370. var roughness = 1 - smoothness;
  16371. var minLODIndex = lodOffset; // roughness = 0
  16372. var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  16373. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  16374. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  16375. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  16376. glTextureFromLod.type = texture.type;
  16377. glTextureFromLod.format = texture.format;
  16378. glTextureFromLod.width = Math.pow(2, Math.max(BABYLON.Scalar.Log2(width) - mipmapIndex, 0));
  16379. glTextureFromLod.height = glTextureFromLod.width;
  16380. glTextureFromLod.isCube = true;
  16381. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  16382. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  16383. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  16384. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16385. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16386. if (loadData.isDDS) {
  16387. var info = loadData.info;
  16388. var data = loadData.data;
  16389. _this._unpackFlipY(info.isCompressed);
  16390. BABYLON.DDSTools.UploadDDSLevels(_this, glTextureFromLod, data, info, true, 6, mipmapIndex);
  16391. }
  16392. else {
  16393. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  16394. }
  16395. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16396. // Wrap in a base texture for easy binding.
  16397. var lodTexture = new BABYLON.BaseTexture(scene);
  16398. lodTexture.isCube = true;
  16399. lodTexture._texture = glTextureFromLod;
  16400. glTextureFromLod.isReady = true;
  16401. textures.push(lodTexture);
  16402. }
  16403. texture._lodTextureHigh = textures[2];
  16404. texture._lodTextureMid = textures[1];
  16405. texture._lodTextureLow = textures[0];
  16406. if (onLoad) {
  16407. onLoad(texture);
  16408. }
  16409. };
  16410. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  16411. };
  16412. /**
  16413. * Creates a cube texture
  16414. * @param rootUrl defines the url where the files to load is located
  16415. * @param scene defines the current scene
  16416. * @param files defines the list of files to load (1 per face)
  16417. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  16418. * @param onLoad defines an optional callback raised when the texture is loaded
  16419. * @param onError defines an optional callback raised if there is an issue to load the texture
  16420. * @param format defines the format of the data
  16421. * @param forcedExtension defines the extension to use to pick the right loader
  16422. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  16423. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  16424. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  16425. * @param fallback defines texture to use while falling back when (compressed) texture file not found.
  16426. * @returns the cube texture as an InternalTexture
  16427. */
  16428. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback) {
  16429. var _this = this;
  16430. if (onLoad === void 0) { onLoad = null; }
  16431. if (onError === void 0) { onError = null; }
  16432. if (forcedExtension === void 0) { forcedExtension = null; }
  16433. if (createPolynomials === void 0) { createPolynomials = false; }
  16434. if (lodScale === void 0) { lodScale = 0; }
  16435. if (lodOffset === void 0) { lodOffset = 0; }
  16436. if (fallback === void 0) { fallback = null; }
  16437. var gl = this._gl;
  16438. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  16439. texture.isCube = true;
  16440. texture.url = rootUrl;
  16441. texture.generateMipMaps = !noMipmap;
  16442. texture._lodGenerationScale = lodScale;
  16443. texture._lodGenerationOffset = lodOffset;
  16444. if (!this._doNotHandleContextLost) {
  16445. texture._extension = forcedExtension;
  16446. texture._files = files;
  16447. }
  16448. var lastDot = rootUrl.lastIndexOf('.');
  16449. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  16450. var loader = null;
  16451. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  16452. var availableLoader = _a[_i];
  16453. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, false, false)) {
  16454. loader = availableLoader;
  16455. break;
  16456. }
  16457. }
  16458. var onInternalError = function (request, exception) {
  16459. if (loader) {
  16460. var fallbackUrl = loader.getFallbackTextureUrl(rootUrl, _this._textureFormatInUse);
  16461. if (fallbackUrl) {
  16462. _this.createCubeTexture(fallbackUrl, scene, files, noMipmap, onLoad, onError, format, extension, createPolynomials, lodScale, lodOffset, texture);
  16463. }
  16464. }
  16465. if (onError && request) {
  16466. onError(request.status + " " + request.statusText, exception);
  16467. }
  16468. };
  16469. if (loader) {
  16470. rootUrl = loader.transformUrl(rootUrl, this._textureFormatInUse);
  16471. var onloaddata = function (data) {
  16472. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16473. loader.loadCubeData(data, texture, createPolynomials, onLoad, onError);
  16474. };
  16475. if (files && files.length === 6) {
  16476. if (loader.supportCascades) {
  16477. this._cascadeLoadFiles(scene, onloaddata, files, onError);
  16478. }
  16479. else if (onError) {
  16480. onError("Textures type does not support cascades.");
  16481. }
  16482. }
  16483. else {
  16484. this._loadFile(rootUrl, onloaddata, undefined, undefined, true, onInternalError);
  16485. }
  16486. }
  16487. else {
  16488. if (!files) {
  16489. throw new Error("Cannot load cubemap because files were not defined");
  16490. }
  16491. this._cascadeLoadImgs(rootUrl, scene, function (imgs) {
  16492. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  16493. var height = width;
  16494. _this._prepareWorkingCanvas();
  16495. if (!_this._workingCanvas || !_this._workingContext) {
  16496. return;
  16497. }
  16498. _this._workingCanvas.width = width;
  16499. _this._workingCanvas.height = height;
  16500. var faces = [
  16501. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  16502. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  16503. ];
  16504. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16505. _this._unpackFlipY(false);
  16506. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  16507. for (var index = 0; index < faces.length; index++) {
  16508. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  16509. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  16510. }
  16511. if (!noMipmap) {
  16512. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  16513. }
  16514. _this._setCubeMapTextureParams(!noMipmap);
  16515. texture.width = width;
  16516. texture.height = height;
  16517. texture.isReady = true;
  16518. if (format) {
  16519. texture.format = format;
  16520. }
  16521. texture.onLoadedObservable.notifyObservers(texture);
  16522. texture.onLoadedObservable.clear();
  16523. if (onLoad) {
  16524. onLoad();
  16525. }
  16526. }, files, onError);
  16527. }
  16528. this._internalTexturesCache.push(texture);
  16529. return texture;
  16530. };
  16531. /**
  16532. * @hidden
  16533. */
  16534. Engine.prototype._setCubeMapTextureParams = function (loadMipmap) {
  16535. var gl = this._gl;
  16536. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  16537. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  16538. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16539. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16540. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16541. // this.resetTextureCache();
  16542. };
  16543. /**
  16544. * Update a raw cube texture
  16545. * @param texture defines the texture to udpdate
  16546. * @param data defines the data to store
  16547. * @param format defines the data format
  16548. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  16549. * @param invertY defines if data must be stored with Y axis inverted
  16550. * @param compression defines the compression used (null by default)
  16551. * @param level defines which level of the texture to update
  16552. */
  16553. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  16554. if (compression === void 0) { compression = null; }
  16555. if (level === void 0) { level = 0; }
  16556. texture._bufferViewArray = data;
  16557. texture.format = format;
  16558. texture.type = type;
  16559. texture.invertY = invertY;
  16560. texture._compression = compression;
  16561. var gl = this._gl;
  16562. var textureType = this._getWebGLTextureType(type);
  16563. var internalFormat = this._getInternalFormat(format);
  16564. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  16565. var needConversion = false;
  16566. if (internalFormat === gl.RGB) {
  16567. internalFormat = gl.RGBA;
  16568. needConversion = true;
  16569. }
  16570. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16571. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16572. if (texture.width % 4 !== 0) {
  16573. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  16574. }
  16575. // Data are known to be in +X +Y +Z -X -Y -Z
  16576. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16577. var faceData = data[faceIndex];
  16578. if (compression) {
  16579. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  16580. }
  16581. else {
  16582. if (needConversion) {
  16583. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  16584. }
  16585. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  16586. }
  16587. }
  16588. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  16589. if (isPot && texture.generateMipMaps && level === 0) {
  16590. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  16591. }
  16592. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16593. // this.resetTextureCache();
  16594. texture.isReady = true;
  16595. };
  16596. /**
  16597. * Creates a new raw cube texture
  16598. * @param data defines the array of data to use to create each face
  16599. * @param size defines the size of the textures
  16600. * @param format defines the format of the data
  16601. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  16602. * @param generateMipMaps defines if the engine should generate the mip levels
  16603. * @param invertY defines if data must be stored with Y axis inverted
  16604. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16605. * @param compression defines the compression used (null by default)
  16606. * @returns the cube texture as an InternalTexture
  16607. */
  16608. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  16609. if (compression === void 0) { compression = null; }
  16610. var gl = this._gl;
  16611. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  16612. texture.isCube = true;
  16613. texture.format = format;
  16614. texture.type = type;
  16615. if (!this._doNotHandleContextLost) {
  16616. texture._bufferViewArray = data;
  16617. }
  16618. var textureType = this._getWebGLTextureType(type);
  16619. var internalFormat = this._getInternalFormat(format);
  16620. if (internalFormat === gl.RGB) {
  16621. internalFormat = gl.RGBA;
  16622. }
  16623. // Mipmap generation needs a sized internal format that is both color-renderable and texture-filterable
  16624. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  16625. generateMipMaps = false;
  16626. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16627. BABYLON.Tools.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  16628. }
  16629. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  16630. generateMipMaps = false;
  16631. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16632. BABYLON.Tools.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  16633. }
  16634. else if (textureType === gl.FLOAT && !this._caps.textureFloatRender) {
  16635. generateMipMaps = false;
  16636. BABYLON.Tools.Warn("Render to float textures is not supported. Mipmap generation forced to false.");
  16637. }
  16638. else if (textureType === gl.HALF_FLOAT && !this._caps.colorBufferFloat) {
  16639. generateMipMaps = false;
  16640. BABYLON.Tools.Warn("Render to half float textures is not supported. Mipmap generation forced to false.");
  16641. }
  16642. var width = size;
  16643. var height = width;
  16644. texture.width = width;
  16645. texture.height = height;
  16646. // Double check on POT to generate Mips.
  16647. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  16648. if (!isPot) {
  16649. generateMipMaps = false;
  16650. }
  16651. // Upload data if needed. The texture won't be ready until then.
  16652. if (data) {
  16653. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  16654. }
  16655. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  16656. // Filters
  16657. if (data && generateMipMaps) {
  16658. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  16659. }
  16660. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  16661. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  16662. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  16663. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16664. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16665. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16666. texture.generateMipMaps = generateMipMaps;
  16667. return texture;
  16668. };
  16669. /**
  16670. * Creates a new raw cube texture from a specified url
  16671. * @param url defines the url where the data is located
  16672. * @param scene defines the current scene
  16673. * @param size defines the size of the textures
  16674. * @param format defines the format of the data
  16675. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  16676. * @param noMipmap defines if the engine should avoid generating the mip levels
  16677. * @param callback defines a callback used to extract texture data from loaded data
  16678. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  16679. * @param onLoad defines a callback called when texture is loaded
  16680. * @param onError defines a callback called if there is an error
  16681. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16682. * @param invertY defines if data must be stored with Y axis inverted
  16683. * @returns the cube texture as an InternalTexture
  16684. */
  16685. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  16686. var _this = this;
  16687. if (onLoad === void 0) { onLoad = null; }
  16688. if (onError === void 0) { onError = null; }
  16689. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  16690. if (invertY === void 0) { invertY = false; }
  16691. var gl = this._gl;
  16692. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  16693. scene._addPendingData(texture);
  16694. texture.url = url;
  16695. this._internalTexturesCache.push(texture);
  16696. var onerror = function (request, exception) {
  16697. scene._removePendingData(texture);
  16698. if (onError && request) {
  16699. onError(request.status + " " + request.statusText, exception);
  16700. }
  16701. };
  16702. var internalCallback = function (data) {
  16703. var width = texture.width;
  16704. var faceDataArrays = callback(data);
  16705. if (!faceDataArrays) {
  16706. return;
  16707. }
  16708. if (mipmapGenerator) {
  16709. var textureType = _this._getWebGLTextureType(type);
  16710. var internalFormat = _this._getInternalFormat(format);
  16711. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  16712. var needConversion = false;
  16713. if (internalFormat === gl.RGB) {
  16714. internalFormat = gl.RGBA;
  16715. needConversion = true;
  16716. }
  16717. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16718. _this._unpackFlipY(false);
  16719. var mipData = mipmapGenerator(faceDataArrays);
  16720. for (var level = 0; level < mipData.length; level++) {
  16721. var mipSize = width >> level;
  16722. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16723. var mipFaceData = mipData[level][faceIndex];
  16724. if (needConversion) {
  16725. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  16726. }
  16727. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  16728. }
  16729. }
  16730. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16731. }
  16732. else {
  16733. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  16734. }
  16735. texture.isReady = true;
  16736. // this.resetTextureCache();
  16737. scene._removePendingData(texture);
  16738. if (onLoad) {
  16739. onLoad();
  16740. }
  16741. };
  16742. this._loadFile(url, function (data) {
  16743. internalCallback(data);
  16744. }, undefined, scene.database, true, onerror);
  16745. return texture;
  16746. };
  16747. ;
  16748. /**
  16749. * Update a raw 3D texture
  16750. * @param texture defines the texture to update
  16751. * @param data defines the data to store
  16752. * @param format defines the data format
  16753. * @param invertY defines if data must be stored with Y axis inverted
  16754. * @param compression defines the used compression (can be null)
  16755. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  16756. */
  16757. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  16758. if (compression === void 0) { compression = null; }
  16759. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16760. var internalType = this._getWebGLTextureType(textureType);
  16761. var internalFormat = this._getInternalFormat(format);
  16762. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  16763. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16764. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16765. if (!this._doNotHandleContextLost) {
  16766. texture._bufferView = data;
  16767. texture.format = format;
  16768. texture.invertY = invertY;
  16769. texture._compression = compression;
  16770. }
  16771. if (texture.width % 4 !== 0) {
  16772. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  16773. }
  16774. if (compression && data) {
  16775. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  16776. }
  16777. else {
  16778. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  16779. }
  16780. if (texture.generateMipMaps) {
  16781. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16782. }
  16783. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16784. // this.resetTextureCache();
  16785. texture.isReady = true;
  16786. };
  16787. /**
  16788. * Creates a new raw 3D texture
  16789. * @param data defines the data used to create the texture
  16790. * @param width defines the width of the texture
  16791. * @param height defines the height of the texture
  16792. * @param depth defines the depth of the texture
  16793. * @param format defines the format of the texture
  16794. * @param generateMipMaps defines if the engine must generate mip levels
  16795. * @param invertY defines if data must be stored with Y axis inverted
  16796. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16797. * @param compression defines the compressed used (can be null)
  16798. * @param textureType defines the compressed used (can be null)
  16799. * @returns a new raw 3D texture (stored in an InternalTexture)
  16800. */
  16801. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  16802. if (compression === void 0) { compression = null; }
  16803. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16804. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  16805. texture.baseWidth = width;
  16806. texture.baseHeight = height;
  16807. texture.baseDepth = depth;
  16808. texture.width = width;
  16809. texture.height = height;
  16810. texture.depth = depth;
  16811. texture.format = format;
  16812. texture.type = textureType;
  16813. texture.generateMipMaps = generateMipMaps;
  16814. texture.samplingMode = samplingMode;
  16815. texture.is3D = true;
  16816. if (!this._doNotHandleContextLost) {
  16817. texture._bufferView = data;
  16818. }
  16819. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  16820. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16821. // Filters
  16822. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  16823. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  16824. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  16825. if (generateMipMaps) {
  16826. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16827. }
  16828. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16829. this._internalTexturesCache.push(texture);
  16830. return texture;
  16831. };
  16832. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  16833. var gl = this._gl;
  16834. if (!gl) {
  16835. return;
  16836. }
  16837. var filters = this._getSamplingParameters(samplingMode, !noMipmap);
  16838. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16839. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16840. if (!noMipmap && !isCompressed) {
  16841. gl.generateMipmap(gl.TEXTURE_2D);
  16842. }
  16843. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16844. // this.resetTextureCache();
  16845. if (scene) {
  16846. scene._removePendingData(texture);
  16847. }
  16848. texture.onLoadedObservable.notifyObservers(texture);
  16849. texture.onLoadedObservable.clear();
  16850. };
  16851. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16852. var _this = this;
  16853. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  16854. var maxTextureSize = this.getCaps().maxTextureSize;
  16855. var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, maxTextureSize) : width);
  16856. var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, maxTextureSize) : height);
  16857. var gl = this._gl;
  16858. if (!gl) {
  16859. return;
  16860. }
  16861. if (!texture._webGLTexture) {
  16862. // this.resetTextureCache();
  16863. if (scene) {
  16864. scene._removePendingData(texture);
  16865. }
  16866. return;
  16867. }
  16868. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16869. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16870. texture.baseWidth = width;
  16871. texture.baseHeight = height;
  16872. texture.width = potWidth;
  16873. texture.height = potHeight;
  16874. texture.isReady = true;
  16875. if (processFunction(potWidth, potHeight, function () {
  16876. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16877. })) {
  16878. // Returning as texture needs extra async steps
  16879. return;
  16880. }
  16881. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16882. };
  16883. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16884. // Create new RGBA data container.
  16885. var rgbaData;
  16886. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16887. rgbaData = new Float32Array(width * height * 4);
  16888. }
  16889. else {
  16890. rgbaData = new Uint32Array(width * height * 4);
  16891. }
  16892. // Convert each pixel.
  16893. for (var x = 0; x < width; x++) {
  16894. for (var y = 0; y < height; y++) {
  16895. var index = (y * width + x) * 3;
  16896. var newIndex = (y * width + x) * 4;
  16897. // Map Old Value to new value.
  16898. rgbaData[newIndex + 0] = rgbData[index + 0];
  16899. rgbaData[newIndex + 1] = rgbData[index + 1];
  16900. rgbaData[newIndex + 2] = rgbData[index + 2];
  16901. // Add fully opaque alpha channel.
  16902. rgbaData[newIndex + 3] = 1;
  16903. }
  16904. }
  16905. return rgbaData;
  16906. };
  16907. /** @hidden */
  16908. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16909. var gl = this._gl;
  16910. if (texture._framebuffer) {
  16911. gl.deleteFramebuffer(texture._framebuffer);
  16912. texture._framebuffer = null;
  16913. }
  16914. if (texture._depthStencilBuffer) {
  16915. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16916. texture._depthStencilBuffer = null;
  16917. }
  16918. if (texture._MSAAFramebuffer) {
  16919. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16920. texture._MSAAFramebuffer = null;
  16921. }
  16922. if (texture._MSAARenderBuffer) {
  16923. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16924. texture._MSAARenderBuffer = null;
  16925. }
  16926. };
  16927. /** @hidden */
  16928. Engine.prototype._releaseTexture = function (texture) {
  16929. var gl = this._gl;
  16930. this._releaseFramebufferObjects(texture);
  16931. gl.deleteTexture(texture._webGLTexture);
  16932. // Unbind channels
  16933. this.unbindAllTextures();
  16934. var index = this._internalTexturesCache.indexOf(texture);
  16935. if (index !== -1) {
  16936. this._internalTexturesCache.splice(index, 1);
  16937. }
  16938. // Integrated fixed lod samplers.
  16939. if (texture._lodTextureHigh) {
  16940. texture._lodTextureHigh.dispose();
  16941. }
  16942. if (texture._lodTextureMid) {
  16943. texture._lodTextureMid.dispose();
  16944. }
  16945. if (texture._lodTextureLow) {
  16946. texture._lodTextureLow.dispose();
  16947. }
  16948. // Set output texture of post process to null if the texture has been released/disposed
  16949. this.scenes.forEach(function (scene) {
  16950. scene.postProcesses.forEach(function (postProcess) {
  16951. if (postProcess._outputTexture == texture) {
  16952. postProcess._outputTexture = null;
  16953. }
  16954. });
  16955. scene.cameras.forEach(function (camera) {
  16956. camera._postProcesses.forEach(function (postProcess) {
  16957. if (postProcess) {
  16958. if (postProcess._outputTexture == texture) {
  16959. postProcess._outputTexture = null;
  16960. }
  16961. }
  16962. });
  16963. });
  16964. });
  16965. };
  16966. Engine.prototype.setProgram = function (program) {
  16967. if (this._currentProgram !== program) {
  16968. this._gl.useProgram(program);
  16969. this._currentProgram = program;
  16970. }
  16971. };
  16972. /**
  16973. * Binds an effect to the webGL context
  16974. * @param effect defines the effect to bind
  16975. */
  16976. Engine.prototype.bindSamplers = function (effect) {
  16977. this.setProgram(effect.getProgram());
  16978. var samplers = effect.getSamplers();
  16979. for (var index = 0; index < samplers.length; index++) {
  16980. var uniform = effect.getUniform(samplers[index]);
  16981. if (uniform) {
  16982. this._boundUniforms[index] = uniform;
  16983. }
  16984. }
  16985. this._currentEffect = null;
  16986. };
  16987. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16988. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16989. return;
  16990. }
  16991. // Remove
  16992. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16993. // Bind last to it
  16994. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16995. // Bind to dummy
  16996. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16997. };
  16998. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16999. if (!internalTexture) {
  17000. return -1;
  17001. }
  17002. internalTexture._initialSlot = channel;
  17003. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  17004. if (channel !== internalTexture._designatedSlot) {
  17005. this._textureCollisions.addCount(1, false);
  17006. }
  17007. }
  17008. else {
  17009. if (channel !== internalTexture._designatedSlot) {
  17010. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  17011. return internalTexture._designatedSlot;
  17012. }
  17013. else {
  17014. // No slot for this texture, let's pick a new one (if we find a free slot)
  17015. if (this._nextFreeTextureSlots.length) {
  17016. return this._nextFreeTextureSlots[0];
  17017. }
  17018. // We need to recycle the oldest bound texture, sorry.
  17019. this._textureCollisions.addCount(1, false);
  17020. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  17021. }
  17022. }
  17023. }
  17024. return channel;
  17025. };
  17026. Engine.prototype._linkTrackers = function (previous, next) {
  17027. previous.next = next;
  17028. next.previous = previous;
  17029. };
  17030. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  17031. var currentSlot = internalTexture._designatedSlot;
  17032. if (currentSlot === -1) {
  17033. return -1;
  17034. }
  17035. internalTexture._designatedSlot = -1;
  17036. if (this.disableTextureBindingOptimization) {
  17037. return -1;
  17038. }
  17039. // Remove from bound list
  17040. this._linkTrackers(internalTexture.previous, internalTexture.next);
  17041. // Free the slot
  17042. this._boundTexturesCache[currentSlot] = null;
  17043. this._nextFreeTextureSlots.push(currentSlot);
  17044. return currentSlot;
  17045. };
  17046. Engine.prototype._activateCurrentTexture = function () {
  17047. if (this._currentTextureChannel !== this._activeChannel) {
  17048. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  17049. this._currentTextureChannel = this._activeChannel;
  17050. }
  17051. };
  17052. /** @hidden */
  17053. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  17054. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  17055. if (force === void 0) { force = false; }
  17056. var wasPreviouslyBound = false;
  17057. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  17058. this._activeChannel = texture._designatedSlot;
  17059. }
  17060. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  17061. var isTextureForRendering = texture && texture._initialSlot > -1;
  17062. if (currentTextureBound !== texture || force) {
  17063. if (currentTextureBound) {
  17064. this._removeDesignatedSlot(currentTextureBound);
  17065. }
  17066. this._activateCurrentTexture();
  17067. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  17068. this._boundTexturesCache[this._activeChannel] = texture;
  17069. if (texture) {
  17070. if (!this.disableTextureBindingOptimization) {
  17071. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  17072. if (slotIndex > -1) {
  17073. this._nextFreeTextureSlots.splice(slotIndex, 1);
  17074. }
  17075. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  17076. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  17077. }
  17078. texture._designatedSlot = this._activeChannel;
  17079. }
  17080. }
  17081. else if (forTextureDataUpdate) {
  17082. wasPreviouslyBound = true;
  17083. this._activateCurrentTexture();
  17084. }
  17085. if (isTextureForRendering && !forTextureDataUpdate) {
  17086. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  17087. }
  17088. return wasPreviouslyBound;
  17089. };
  17090. /** @hidden */
  17091. Engine.prototype._bindTexture = function (channel, texture) {
  17092. if (channel < 0) {
  17093. return;
  17094. }
  17095. if (texture) {
  17096. channel = this._getCorrectTextureChannel(channel, texture);
  17097. }
  17098. this._activeChannel = channel;
  17099. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  17100. };
  17101. /**
  17102. * Sets a texture to the webGL context from a postprocess
  17103. * @param channel defines the channel to use
  17104. * @param postProcess defines the source postprocess
  17105. */
  17106. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  17107. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  17108. };
  17109. /**
  17110. * Binds the output of the passed in post process to the texture channel specified
  17111. * @param channel The channel the texture should be bound to
  17112. * @param postProcess The post process which's output should be bound
  17113. */
  17114. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  17115. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  17116. };
  17117. /**
  17118. * Unbind all textures from the webGL context
  17119. */
  17120. Engine.prototype.unbindAllTextures = function () {
  17121. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  17122. this._activeChannel = channel;
  17123. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  17124. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  17125. if (this.webGLVersion > 1) {
  17126. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  17127. }
  17128. }
  17129. };
  17130. /**
  17131. * Sets a texture to the according uniform.
  17132. * @param channel The texture channel
  17133. * @param uniform The uniform to set
  17134. * @param texture The texture to apply
  17135. */
  17136. Engine.prototype.setTexture = function (channel, uniform, texture) {
  17137. if (channel < 0) {
  17138. return;
  17139. }
  17140. if (uniform) {
  17141. this._boundUniforms[channel] = uniform;
  17142. }
  17143. this._setTexture(channel, texture);
  17144. };
  17145. /**
  17146. * Sets a depth stencil texture from a render target to the according uniform.
  17147. * @param channel The texture channel
  17148. * @param uniform The uniform to set
  17149. * @param texture The render target texture containing the depth stencil texture to apply
  17150. */
  17151. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  17152. if (channel < 0) {
  17153. return;
  17154. }
  17155. if (uniform) {
  17156. this._boundUniforms[channel] = uniform;
  17157. }
  17158. if (!texture || !texture.depthStencilTexture) {
  17159. this._setTexture(channel, null);
  17160. }
  17161. else {
  17162. this._setTexture(channel, texture, false, true);
  17163. }
  17164. };
  17165. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  17166. var uniform = this._boundUniforms[sourceSlot];
  17167. if (uniform._currentState === destination) {
  17168. return;
  17169. }
  17170. this._gl.uniform1i(uniform, destination);
  17171. uniform._currentState = destination;
  17172. };
  17173. Engine.prototype._getTextureWrapMode = function (mode) {
  17174. switch (mode) {
  17175. case Engine.TEXTURE_WRAP_ADDRESSMODE:
  17176. return this._gl.REPEAT;
  17177. case Engine.TEXTURE_CLAMP_ADDRESSMODE:
  17178. return this._gl.CLAMP_TO_EDGE;
  17179. case Engine.TEXTURE_MIRROR_ADDRESSMODE:
  17180. return this._gl.MIRRORED_REPEAT;
  17181. }
  17182. return this._gl.REPEAT;
  17183. };
  17184. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  17185. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  17186. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  17187. // Not ready?
  17188. if (!texture) {
  17189. if (this._boundTexturesCache[channel] != null) {
  17190. this._activeChannel = channel;
  17191. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  17192. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  17193. if (this.webGLVersion > 1) {
  17194. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  17195. }
  17196. }
  17197. return false;
  17198. }
  17199. // Video
  17200. if (texture.video) {
  17201. this._activeChannel = channel;
  17202. texture.update();
  17203. }
  17204. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  17205. texture.delayLoad();
  17206. return false;
  17207. }
  17208. var internalTexture;
  17209. if (depthStencilTexture) {
  17210. internalTexture = texture.depthStencilTexture;
  17211. }
  17212. else if (texture.isReady()) {
  17213. internalTexture = texture.getInternalTexture();
  17214. }
  17215. else if (texture.isCube) {
  17216. internalTexture = this.emptyCubeTexture;
  17217. }
  17218. else if (texture.is3D) {
  17219. internalTexture = this.emptyTexture3D;
  17220. }
  17221. else {
  17222. internalTexture = this.emptyTexture;
  17223. }
  17224. if (!isPartOfTextureArray) {
  17225. channel = this._getCorrectTextureChannel(channel, internalTexture);
  17226. }
  17227. var needToBind = true;
  17228. if (this._boundTexturesCache[channel] === internalTexture) {
  17229. this._moveBoundTextureOnTop(internalTexture);
  17230. if (!isPartOfTextureArray) {
  17231. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  17232. }
  17233. needToBind = false;
  17234. }
  17235. this._activeChannel = channel;
  17236. if (internalTexture && internalTexture.is3D) {
  17237. if (needToBind) {
  17238. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  17239. }
  17240. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  17241. internalTexture._cachedWrapU = texture.wrapU;
  17242. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  17243. }
  17244. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  17245. internalTexture._cachedWrapV = texture.wrapV;
  17246. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  17247. }
  17248. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  17249. internalTexture._cachedWrapR = texture.wrapR;
  17250. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  17251. }
  17252. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  17253. }
  17254. else if (internalTexture && internalTexture.isCube) {
  17255. if (needToBind) {
  17256. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  17257. }
  17258. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  17259. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  17260. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  17261. var textureWrapMode = (texture.coordinatesMode !== Engine.TEXTURE_CUBIC_MODE && texture.coordinatesMode !== Engine.TEXTURE_SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  17262. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  17263. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  17264. }
  17265. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  17266. }
  17267. else {
  17268. if (needToBind) {
  17269. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  17270. }
  17271. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  17272. internalTexture._cachedWrapU = texture.wrapU;
  17273. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  17274. }
  17275. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  17276. internalTexture._cachedWrapV = texture.wrapV;
  17277. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  17278. }
  17279. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  17280. }
  17281. return true;
  17282. };
  17283. /**
  17284. * Sets an array of texture to the webGL context
  17285. * @param channel defines the channel where the texture array must be set
  17286. * @param uniform defines the associated uniform location
  17287. * @param textures defines the array of textures to bind
  17288. */
  17289. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  17290. if (channel < 0 || !uniform) {
  17291. return;
  17292. }
  17293. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  17294. this._textureUnits = new Int32Array(textures.length);
  17295. }
  17296. for (var i = 0; i < textures.length; i++) {
  17297. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  17298. }
  17299. this._gl.uniform1iv(uniform, this._textureUnits);
  17300. for (var index = 0; index < textures.length; index++) {
  17301. this._setTexture(this._textureUnits[index], textures[index], true);
  17302. }
  17303. };
  17304. /** @hidden */
  17305. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  17306. var internalTexture = texture.getInternalTexture();
  17307. if (!internalTexture) {
  17308. return;
  17309. }
  17310. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  17311. var value = texture.anisotropicFilteringLevel;
  17312. if (internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST
  17313. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR
  17314. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR) {
  17315. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  17316. }
  17317. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  17318. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  17319. internalTexture._cachedAnisotropicFilteringLevel = value;
  17320. }
  17321. };
  17322. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  17323. this._bindTextureDirectly(target, texture, true, true);
  17324. this._gl.texParameterf(target, parameter, value);
  17325. };
  17326. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  17327. if (texture) {
  17328. this._bindTextureDirectly(target, texture, true, true);
  17329. }
  17330. this._gl.texParameteri(target, parameter, value);
  17331. };
  17332. /**
  17333. * Reads pixels from the current frame buffer. Please note that this function can be slow
  17334. * @param x defines the x coordinate of the rectangle where pixels must be read
  17335. * @param y defines the y coordinate of the rectangle where pixels must be read
  17336. * @param width defines the width of the rectangle where pixels must be read
  17337. * @param height defines the height of the rectangle where pixels must be read
  17338. * @returns a Uint8Array containing RGBA colors
  17339. */
  17340. Engine.prototype.readPixels = function (x, y, width, height) {
  17341. var data = new Uint8Array(height * width * 4);
  17342. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  17343. return data;
  17344. };
  17345. /**
  17346. * Add an externaly attached data from its key.
  17347. * This method call will fail and return false, if such key already exists.
  17348. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  17349. * @param key the unique key that identifies the data
  17350. * @param data the data object to associate to the key for this Engine instance
  17351. * @return true if no such key were already present and the data was added successfully, false otherwise
  17352. */
  17353. Engine.prototype.addExternalData = function (key, data) {
  17354. if (!this._externalData) {
  17355. this._externalData = new BABYLON.StringDictionary();
  17356. }
  17357. return this._externalData.add(key, data);
  17358. };
  17359. /**
  17360. * Get an externaly attached data from its key
  17361. * @param key the unique key that identifies the data
  17362. * @return the associated data, if present (can be null), or undefined if not present
  17363. */
  17364. Engine.prototype.getExternalData = function (key) {
  17365. if (!this._externalData) {
  17366. this._externalData = new BABYLON.StringDictionary();
  17367. }
  17368. return this._externalData.get(key);
  17369. };
  17370. /**
  17371. * Get an externaly attached data from its key, create it using a factory if it's not already present
  17372. * @param key the unique key that identifies the data
  17373. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  17374. * @return the associated data, can be null if the factory returned null.
  17375. */
  17376. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  17377. if (!this._externalData) {
  17378. this._externalData = new BABYLON.StringDictionary();
  17379. }
  17380. return this._externalData.getOrAddWithFactory(key, factory);
  17381. };
  17382. /**
  17383. * Remove an externaly attached data from the Engine instance
  17384. * @param key the unique key that identifies the data
  17385. * @return true if the data was successfully removed, false if it doesn't exist
  17386. */
  17387. Engine.prototype.removeExternalData = function (key) {
  17388. if (!this._externalData) {
  17389. this._externalData = new BABYLON.StringDictionary();
  17390. }
  17391. return this._externalData.remove(key);
  17392. };
  17393. /**
  17394. * Unbind all vertex attributes from the webGL context
  17395. */
  17396. Engine.prototype.unbindAllAttributes = function () {
  17397. if (this._mustWipeVertexAttributes) {
  17398. this._mustWipeVertexAttributes = false;
  17399. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  17400. this._gl.disableVertexAttribArray(i);
  17401. this._vertexAttribArraysEnabled[i] = false;
  17402. this._currentBufferPointers[i].active = false;
  17403. }
  17404. return;
  17405. }
  17406. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  17407. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  17408. continue;
  17409. }
  17410. this._gl.disableVertexAttribArray(i);
  17411. this._vertexAttribArraysEnabled[i] = false;
  17412. this._currentBufferPointers[i].active = false;
  17413. }
  17414. };
  17415. /**
  17416. * 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
  17417. */
  17418. Engine.prototype.releaseEffects = function () {
  17419. for (var name in this._compiledEffects) {
  17420. this._deleteProgram(this._compiledEffects[name]._program);
  17421. }
  17422. this._compiledEffects = {};
  17423. };
  17424. /**
  17425. * Dispose and release all associated resources
  17426. */
  17427. Engine.prototype.dispose = function () {
  17428. this.hideLoadingUI();
  17429. this.stopRenderLoop();
  17430. // Release postProcesses
  17431. while (this.postProcesses.length) {
  17432. this.postProcesses[0].dispose();
  17433. }
  17434. // Empty texture
  17435. if (this._emptyTexture) {
  17436. this._releaseTexture(this._emptyTexture);
  17437. this._emptyTexture = null;
  17438. }
  17439. if (this._emptyCubeTexture) {
  17440. this._releaseTexture(this._emptyCubeTexture);
  17441. this._emptyCubeTexture = null;
  17442. }
  17443. // Rescale PP
  17444. if (this._rescalePostProcess) {
  17445. this._rescalePostProcess.dispose();
  17446. }
  17447. // Release scenes
  17448. while (this.scenes.length) {
  17449. this.scenes[0].dispose();
  17450. }
  17451. // Release audio engine
  17452. if (Engine.Instances.length === 1 && Engine.audioEngine) {
  17453. Engine.audioEngine.dispose();
  17454. }
  17455. // Release effects
  17456. this.releaseEffects();
  17457. // Unbind
  17458. this.unbindAllAttributes();
  17459. this._boundUniforms = [];
  17460. if (this._dummyFramebuffer) {
  17461. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  17462. }
  17463. //WebVR
  17464. this.disableVR();
  17465. // Events
  17466. if (BABYLON.Tools.IsWindowObjectExist()) {
  17467. window.removeEventListener("blur", this._onBlur);
  17468. window.removeEventListener("focus", this._onFocus);
  17469. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  17470. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  17471. if (this._renderingCanvas) {
  17472. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  17473. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  17474. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  17475. if (!this._doNotHandleContextLost) {
  17476. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  17477. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  17478. }
  17479. }
  17480. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  17481. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  17482. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  17483. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  17484. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  17485. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  17486. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  17487. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  17488. if (this._onVrDisplayConnect) {
  17489. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  17490. if (this._onVrDisplayDisconnect) {
  17491. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  17492. }
  17493. if (this._onVrDisplayPresentChange) {
  17494. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  17495. }
  17496. this._onVrDisplayConnect = null;
  17497. this._onVrDisplayDisconnect = null;
  17498. }
  17499. }
  17500. // Remove from Instances
  17501. var index = Engine.Instances.indexOf(this);
  17502. if (index >= 0) {
  17503. Engine.Instances.splice(index, 1);
  17504. }
  17505. this._workingCanvas = null;
  17506. this._workingContext = null;
  17507. this._currentBufferPointers = [];
  17508. this._renderingCanvas = null;
  17509. this._currentProgram = null;
  17510. this._bindedRenderFunction = null;
  17511. this.onResizeObservable.clear();
  17512. this.onCanvasBlurObservable.clear();
  17513. this.onCanvasFocusObservable.clear();
  17514. this.onCanvasPointerOutObservable.clear();
  17515. this.onBeginFrameObservable.clear();
  17516. this.onEndFrameObservable.clear();
  17517. BABYLON.Effect.ResetCache();
  17518. // Abort active requests
  17519. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  17520. var request = _a[_i];
  17521. request.abort();
  17522. }
  17523. };
  17524. // Loading screen
  17525. /**
  17526. * Display the loading screen
  17527. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17528. */
  17529. Engine.prototype.displayLoadingUI = function () {
  17530. if (!BABYLON.Tools.IsWindowObjectExist()) {
  17531. return;
  17532. }
  17533. var loadingScreen = this.loadingScreen;
  17534. if (loadingScreen) {
  17535. loadingScreen.displayLoadingUI();
  17536. }
  17537. };
  17538. /**
  17539. * Hide the loading screen
  17540. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17541. */
  17542. Engine.prototype.hideLoadingUI = function () {
  17543. if (!BABYLON.Tools.IsWindowObjectExist()) {
  17544. return;
  17545. }
  17546. var loadingScreen = this.loadingScreen;
  17547. if (loadingScreen) {
  17548. loadingScreen.hideLoadingUI();
  17549. }
  17550. };
  17551. Object.defineProperty(Engine.prototype, "loadingScreen", {
  17552. /**
  17553. * Gets the current loading screen object
  17554. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17555. */
  17556. get: function () {
  17557. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  17558. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  17559. return this._loadingScreen;
  17560. },
  17561. /**
  17562. * Sets the current loading screen object
  17563. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17564. */
  17565. set: function (loadingScreen) {
  17566. this._loadingScreen = loadingScreen;
  17567. },
  17568. enumerable: true,
  17569. configurable: true
  17570. });
  17571. Object.defineProperty(Engine.prototype, "loadingUIText", {
  17572. /**
  17573. * Sets the current loading screen text
  17574. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17575. */
  17576. set: function (text) {
  17577. this.loadingScreen.loadingUIText = text;
  17578. },
  17579. enumerable: true,
  17580. configurable: true
  17581. });
  17582. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  17583. /**
  17584. * Sets the current loading screen background color
  17585. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17586. */
  17587. set: function (color) {
  17588. this.loadingScreen.loadingUIBackgroundColor = color;
  17589. },
  17590. enumerable: true,
  17591. configurable: true
  17592. });
  17593. /**
  17594. * Attach a new callback raised when context lost event is fired
  17595. * @param callback defines the callback to call
  17596. */
  17597. Engine.prototype.attachContextLostEvent = function (callback) {
  17598. if (this._renderingCanvas) {
  17599. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  17600. }
  17601. };
  17602. /**
  17603. * Attach a new callback raised when context restored event is fired
  17604. * @param callback defines the callback to call
  17605. */
  17606. Engine.prototype.attachContextRestoredEvent = function (callback) {
  17607. if (this._renderingCanvas) {
  17608. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  17609. }
  17610. };
  17611. /**
  17612. * Gets the source code of the vertex shader associated with a specific webGL program
  17613. * @param program defines the program to use
  17614. * @returns a string containing the source code of the vertex shader associated with the program
  17615. */
  17616. Engine.prototype.getVertexShaderSource = function (program) {
  17617. var shaders = this._gl.getAttachedShaders(program);
  17618. if (!shaders) {
  17619. return null;
  17620. }
  17621. return this._gl.getShaderSource(shaders[0]);
  17622. };
  17623. /**
  17624. * Gets the source code of the fragment shader associated with a specific webGL program
  17625. * @param program defines the program to use
  17626. * @returns a string containing the source code of the fragment shader associated with the program
  17627. */
  17628. Engine.prototype.getFragmentShaderSource = function (program) {
  17629. var shaders = this._gl.getAttachedShaders(program);
  17630. if (!shaders) {
  17631. return null;
  17632. }
  17633. return this._gl.getShaderSource(shaders[1]);
  17634. };
  17635. /**
  17636. * Get the current error code of the webGL context
  17637. * @returns the error code
  17638. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  17639. */
  17640. Engine.prototype.getError = function () {
  17641. return this._gl.getError();
  17642. };
  17643. // FPS
  17644. /**
  17645. * Gets the current framerate
  17646. * @returns a number representing the framerate
  17647. */
  17648. Engine.prototype.getFps = function () {
  17649. return this._fps;
  17650. };
  17651. /**
  17652. * Gets the time spent between current and previous frame
  17653. * @returns a number representing the delta time in ms
  17654. */
  17655. Engine.prototype.getDeltaTime = function () {
  17656. return this._deltaTime;
  17657. };
  17658. Engine.prototype._measureFps = function () {
  17659. this._performanceMonitor.sampleFrame();
  17660. this._fps = this._performanceMonitor.averageFPS;
  17661. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  17662. };
  17663. /** @hidden */
  17664. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level, buffer) {
  17665. if (faceIndex === void 0) { faceIndex = -1; }
  17666. if (level === void 0) { level = 0; }
  17667. if (buffer === void 0) { buffer = null; }
  17668. var gl = this._gl;
  17669. if (!this._dummyFramebuffer) {
  17670. var dummy = gl.createFramebuffer();
  17671. if (!dummy) {
  17672. throw new Error("Unable to create dummy framebuffer");
  17673. }
  17674. this._dummyFramebuffer = dummy;
  17675. }
  17676. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  17677. if (faceIndex > -1) {
  17678. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  17679. }
  17680. else {
  17681. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  17682. }
  17683. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  17684. switch (readType) {
  17685. case gl.UNSIGNED_BYTE:
  17686. if (!buffer) {
  17687. buffer = new Uint8Array(4 * width * height);
  17688. }
  17689. readType = gl.UNSIGNED_BYTE;
  17690. break;
  17691. default:
  17692. if (!buffer) {
  17693. buffer = new Float32Array(4 * width * height);
  17694. }
  17695. readType = gl.FLOAT;
  17696. break;
  17697. }
  17698. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  17699. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  17700. return buffer;
  17701. };
  17702. Engine.prototype._canRenderToFloatFramebuffer = function () {
  17703. if (this._webGLVersion > 1) {
  17704. return this._caps.colorBufferFloat;
  17705. }
  17706. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  17707. };
  17708. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  17709. if (this._webGLVersion > 1) {
  17710. return this._caps.colorBufferFloat;
  17711. }
  17712. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  17713. };
  17714. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  17715. Engine.prototype._canRenderToFramebuffer = function (type) {
  17716. var gl = this._gl;
  17717. //clear existing errors
  17718. while (gl.getError() !== gl.NO_ERROR) { }
  17719. var successful = true;
  17720. var texture = gl.createTexture();
  17721. gl.bindTexture(gl.TEXTURE_2D, texture);
  17722. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  17723. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  17724. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  17725. var fb = gl.createFramebuffer();
  17726. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  17727. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  17728. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  17729. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  17730. successful = successful && (gl.getError() === gl.NO_ERROR);
  17731. //try render by clearing frame buffer's color buffer
  17732. if (successful) {
  17733. gl.clear(gl.COLOR_BUFFER_BIT);
  17734. successful = successful && (gl.getError() === gl.NO_ERROR);
  17735. }
  17736. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  17737. if (successful) {
  17738. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  17739. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17740. var readFormat = gl.RGBA;
  17741. var readType = gl.UNSIGNED_BYTE;
  17742. var buffer = new Uint8Array(4);
  17743. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  17744. successful = successful && (gl.getError() === gl.NO_ERROR);
  17745. }
  17746. //clean up
  17747. gl.deleteTexture(texture);
  17748. gl.deleteFramebuffer(fb);
  17749. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17750. //clear accumulated errors
  17751. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  17752. return successful;
  17753. };
  17754. /** @hidden */
  17755. Engine.prototype._getWebGLTextureType = function (type) {
  17756. if (this._webGLVersion === 1) {
  17757. switch (type) {
  17758. case Engine.TEXTURETYPE_FLOAT:
  17759. return this._gl.FLOAT;
  17760. case Engine.TEXTURETYPE_HALF_FLOAT:
  17761. return this._gl.HALF_FLOAT_OES;
  17762. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17763. return this._gl.UNSIGNED_BYTE;
  17764. }
  17765. return this._gl.UNSIGNED_BYTE;
  17766. }
  17767. switch (type) {
  17768. case Engine.TEXTURETYPE_BYTE:
  17769. return this._gl.BYTE;
  17770. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17771. return this._gl.UNSIGNED_BYTE;
  17772. case Engine.TEXTURETYPE_SHORT:
  17773. return this._gl.SHORT;
  17774. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  17775. return this._gl.UNSIGNED_SHORT;
  17776. case Engine.TEXTURETYPE_INT:
  17777. return this._gl.INT;
  17778. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  17779. return this._gl.UNSIGNED_INT;
  17780. case Engine.TEXTURETYPE_FLOAT:
  17781. return this._gl.FLOAT;
  17782. case Engine.TEXTURETYPE_HALF_FLOAT:
  17783. return this._gl.HALF_FLOAT;
  17784. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  17785. return this._gl.UNSIGNED_SHORT_4_4_4_4;
  17786. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  17787. return this._gl.UNSIGNED_SHORT_5_5_5_1;
  17788. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  17789. return this._gl.UNSIGNED_SHORT_5_6_5;
  17790. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  17791. return this._gl.UNSIGNED_INT_2_10_10_10_REV;
  17792. case Engine.TEXTURETYPE_UNSIGNED_INT_24_8:
  17793. return this._gl.UNSIGNED_INT_24_8;
  17794. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  17795. return this._gl.UNSIGNED_INT_10F_11F_11F_REV;
  17796. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  17797. return this._gl.UNSIGNED_INT_5_9_9_9_REV;
  17798. case Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV:
  17799. return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV;
  17800. }
  17801. return this._gl.UNSIGNED_BYTE;
  17802. };
  17803. ;
  17804. Engine.prototype._getInternalFormat = function (format) {
  17805. var internalFormat = this._gl.RGBA;
  17806. switch (format) {
  17807. case Engine.TEXTUREFORMAT_ALPHA:
  17808. internalFormat = this._gl.ALPHA;
  17809. break;
  17810. case Engine.TEXTUREFORMAT_LUMINANCE:
  17811. internalFormat = this._gl.LUMINANCE;
  17812. break;
  17813. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17814. internalFormat = this._gl.LUMINANCE_ALPHA;
  17815. break;
  17816. case Engine.TEXTUREFORMAT_RED:
  17817. internalFormat = this._gl.RED;
  17818. break;
  17819. case Engine.TEXTUREFORMAT_RG:
  17820. internalFormat = this._gl.RG;
  17821. break;
  17822. case Engine.TEXTUREFORMAT_RGB:
  17823. internalFormat = this._gl.RGB;
  17824. break;
  17825. case Engine.TEXTUREFORMAT_RGBA:
  17826. internalFormat = this._gl.RGBA;
  17827. break;
  17828. }
  17829. if (this._webGLVersion > 1) {
  17830. switch (format) {
  17831. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17832. internalFormat = this._gl.RED_INTEGER;
  17833. break;
  17834. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17835. internalFormat = this._gl.RG_INTEGER;
  17836. break;
  17837. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17838. internalFormat = this._gl.RGB_INTEGER;
  17839. break;
  17840. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17841. internalFormat = this._gl.RGBA_INTEGER;
  17842. break;
  17843. }
  17844. }
  17845. return internalFormat;
  17846. };
  17847. /** @hidden */
  17848. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  17849. if (this._webGLVersion === 1) {
  17850. if (format !== undefined) {
  17851. switch (format) {
  17852. case Engine.TEXTUREFORMAT_ALPHA:
  17853. return this._gl.ALPHA;
  17854. case Engine.TEXTUREFORMAT_LUMINANCE:
  17855. return this._gl.LUMINANCE;
  17856. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17857. return this._gl.LUMINANCE_ALPHA;
  17858. }
  17859. }
  17860. return this._gl.RGBA;
  17861. }
  17862. switch (type) {
  17863. case Engine.TEXTURETYPE_BYTE:
  17864. switch (format) {
  17865. case Engine.TEXTUREFORMAT_RED:
  17866. return this._gl.R8_SNORM;
  17867. case Engine.TEXTUREFORMAT_RG:
  17868. return this._gl.RG8_SNORM;
  17869. case Engine.TEXTUREFORMAT_RGB:
  17870. return this._gl.RGB8_SNORM;
  17871. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17872. return this._gl.R8I;
  17873. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17874. return this._gl.RG8I;
  17875. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17876. return this._gl.RGB8I;
  17877. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17878. return this._gl.RGBA8I;
  17879. default:
  17880. return this._gl.RGBA8_SNORM;
  17881. }
  17882. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17883. switch (format) {
  17884. case Engine.TEXTUREFORMAT_RED:
  17885. return this._gl.R8;
  17886. case Engine.TEXTUREFORMAT_RG:
  17887. return this._gl.RG8;
  17888. case Engine.TEXTUREFORMAT_RGB:
  17889. return this._gl.RGB8; // By default. Other possibilities are RGB565, SRGB8.
  17890. case Engine.TEXTUREFORMAT_RGBA:
  17891. return this._gl.RGBA8; // By default. Other possibilities are RGB5_A1, RGBA4, SRGB8_ALPHA8.
  17892. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17893. return this._gl.R8UI;
  17894. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17895. return this._gl.RG8UI;
  17896. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17897. return this._gl.RGB8UI;
  17898. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17899. return this._gl.RGBA8UI;
  17900. default:
  17901. return this._gl.RGBA8;
  17902. }
  17903. case Engine.TEXTURETYPE_SHORT:
  17904. switch (format) {
  17905. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17906. return this._gl.R16I;
  17907. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17908. return this._gl.RG16I;
  17909. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17910. return this._gl.RGB16I;
  17911. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17912. return this._gl.RGBA16I;
  17913. default:
  17914. return this._gl.RGBA16I;
  17915. }
  17916. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  17917. switch (format) {
  17918. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17919. return this._gl.R16UI;
  17920. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17921. return this._gl.RG16UI;
  17922. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17923. return this._gl.RGB16UI;
  17924. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17925. return this._gl.RGBA16UI;
  17926. default:
  17927. return this._gl.RGBA16UI;
  17928. }
  17929. case Engine.TEXTURETYPE_INT:
  17930. switch (format) {
  17931. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17932. return this._gl.R32I;
  17933. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17934. return this._gl.RG32I;
  17935. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17936. return this._gl.RGB32I;
  17937. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17938. return this._gl.RGBA32I;
  17939. default:
  17940. return this._gl.RGBA32I;
  17941. }
  17942. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  17943. switch (format) {
  17944. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17945. return this._gl.R32UI;
  17946. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17947. return this._gl.RG32UI;
  17948. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17949. return this._gl.RGB32UI;
  17950. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17951. return this._gl.RGBA32UI;
  17952. default:
  17953. return this._gl.RGBA32UI;
  17954. }
  17955. case Engine.TEXTURETYPE_FLOAT:
  17956. switch (format) {
  17957. case Engine.TEXTUREFORMAT_RED:
  17958. return this._gl.R32F; // By default. Other possibility is R16F.
  17959. case Engine.TEXTUREFORMAT_RG:
  17960. return this._gl.RG32F; // By default. Other possibility is RG16F.
  17961. case Engine.TEXTUREFORMAT_RGB:
  17962. return this._gl.RGB32F; // By default. Other possibilities are RGB16F, R11F_G11F_B10F, RGB9_E5.
  17963. case Engine.TEXTUREFORMAT_RGBA:
  17964. return this._gl.RGBA32F; // By default. Other possibility is RGBA16F.
  17965. default:
  17966. return this._gl.RGBA32F;
  17967. }
  17968. case Engine.TEXTURETYPE_HALF_FLOAT:
  17969. switch (format) {
  17970. case Engine.TEXTUREFORMAT_RED:
  17971. return this._gl.R16F;
  17972. case Engine.TEXTUREFORMAT_RG:
  17973. return this._gl.RG16F;
  17974. case Engine.TEXTUREFORMAT_RGB:
  17975. return this._gl.RGB16F; // By default. Other possibilities are R11F_G11F_B10F, RGB9_E5.
  17976. case Engine.TEXTUREFORMAT_RGBA:
  17977. return this._gl.RGBA16F;
  17978. default:
  17979. return this._gl.RGBA16F;
  17980. }
  17981. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  17982. return this._gl.RGB565;
  17983. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  17984. return this._gl.R11F_G11F_B10F;
  17985. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  17986. return this._gl.RGB9_E5;
  17987. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  17988. return this._gl.RGBA4;
  17989. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  17990. return this._gl.RGB5_A1;
  17991. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  17992. switch (format) {
  17993. case Engine.TEXTUREFORMAT_RGBA:
  17994. return this._gl.RGB10_A2; // By default. Other possibility is RGB5_A1.
  17995. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17996. return this._gl.RGB10_A2UI;
  17997. default:
  17998. return this._gl.RGB10_A2;
  17999. }
  18000. }
  18001. return this._gl.RGBA8;
  18002. };
  18003. ;
  18004. /** @hidden */
  18005. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  18006. if (type === Engine.TEXTURETYPE_FLOAT) {
  18007. return this._gl.RGBA32F;
  18008. }
  18009. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  18010. return this._gl.RGBA16F;
  18011. }
  18012. return this._gl.RGBA8;
  18013. };
  18014. ;
  18015. /** @hidden */
  18016. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  18017. var _this = this;
  18018. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  18019. this._activeRequests.push(request);
  18020. request.onCompleteObservable.add(function (request) {
  18021. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  18022. });
  18023. return request;
  18024. };
  18025. /** @hidden */
  18026. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  18027. var _this = this;
  18028. return new Promise(function (resolve, reject) {
  18029. _this._loadFile(url, function (data) {
  18030. resolve(data);
  18031. }, undefined, database, useArrayBuffer, function (request, exception) {
  18032. reject(exception);
  18033. });
  18034. });
  18035. };
  18036. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  18037. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  18038. var onload = function (data) {
  18039. loadedFiles[index] = data;
  18040. loadedFiles._internalCount++;
  18041. if (loadedFiles._internalCount === 6) {
  18042. onfinish(loadedFiles);
  18043. }
  18044. };
  18045. var onerror = function (request, exception) {
  18046. if (onErrorCallBack && request) {
  18047. onErrorCallBack(request.status + " " + request.statusText, exception);
  18048. }
  18049. };
  18050. this._loadFile(url, onload, undefined, undefined, true, onerror);
  18051. };
  18052. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  18053. if (onError === void 0) { onError = null; }
  18054. var loadedFiles = [];
  18055. loadedFiles._internalCount = 0;
  18056. for (var index = 0; index < 6; index++) {
  18057. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  18058. }
  18059. };
  18060. // Statics
  18061. /**
  18062. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  18063. * @returns true if the engine can be created
  18064. * @ignorenaming
  18065. */
  18066. Engine.isSupported = function () {
  18067. try {
  18068. var tempcanvas = document.createElement("canvas");
  18069. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  18070. return gl != null && !!window.WebGLRenderingContext;
  18071. }
  18072. catch (e) {
  18073. return false;
  18074. }
  18075. };
  18076. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  18077. Engine.ExceptionList = [
  18078. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  18079. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  18080. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  18081. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  18082. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  18083. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  18084. ];
  18085. /** Gets the list of created engines */
  18086. Engine.Instances = new Array();
  18087. /**
  18088. * Hidden
  18089. */
  18090. Engine._TextureLoaders = [];
  18091. // Const statics
  18092. /** Defines that alpha blending is disabled */
  18093. Engine.ALPHA_DISABLE = 0;
  18094. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  18095. Engine.ALPHA_ADD = 1;
  18096. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  18097. Engine.ALPHA_COMBINE = 2;
  18098. /** Defines that alpha blending to DEST - SRC * DEST */
  18099. Engine.ALPHA_SUBTRACT = 3;
  18100. /** Defines that alpha blending to SRC * DEST */
  18101. Engine.ALPHA_MULTIPLY = 4;
  18102. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  18103. Engine.ALPHA_MAXIMIZED = 5;
  18104. /** Defines that alpha blending to SRC + DEST */
  18105. Engine.ALPHA_ONEONE = 6;
  18106. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  18107. Engine.ALPHA_PREMULTIPLIED = 7;
  18108. /**
  18109. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  18110. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  18111. */
  18112. Engine.ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  18113. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  18114. Engine.ALPHA_INTERPOLATE = 9;
  18115. /**
  18116. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  18117. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  18118. */
  18119. Engine.ALPHA_SCREENMODE = 10;
  18120. /** Defines that the ressource is not delayed*/
  18121. Engine.DELAYLOADSTATE_NONE = 0;
  18122. /** Defines that the ressource was successfully delay loaded */
  18123. Engine.DELAYLOADSTATE_LOADED = 1;
  18124. /** Defines that the ressource is currently delay loading */
  18125. Engine.DELAYLOADSTATE_LOADING = 2;
  18126. /** Defines that the ressource is delayed and has not started loading */
  18127. Engine.DELAYLOADSTATE_NOTLOADED = 4;
  18128. // Depht or Stencil test Constants.
  18129. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  18130. Engine.NEVER = 0x0200;
  18131. /** 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 */
  18132. Engine.ALWAYS = 0x0207;
  18133. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  18134. Engine.LESS = 0x0201;
  18135. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  18136. Engine.EQUAL = 0x0202;
  18137. /** 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 */
  18138. Engine.LEQUAL = 0x0203;
  18139. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  18140. Engine.GREATER = 0x0204;
  18141. /** 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 */
  18142. Engine.GEQUAL = 0x0206;
  18143. /** 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 */
  18144. Engine.NOTEQUAL = 0x0205;
  18145. // Stencil Actions Constants.
  18146. /** Passed to stencilOperation to specify that stencil value must be kept */
  18147. Engine.KEEP = 0x1E00;
  18148. /** Passed to stencilOperation to specify that stencil value must be replaced */
  18149. Engine.REPLACE = 0x1E01;
  18150. /** Passed to stencilOperation to specify that stencil value must be incremented */
  18151. Engine.INCR = 0x1E02;
  18152. /** Passed to stencilOperation to specify that stencil value must be decremented */
  18153. Engine.DECR = 0x1E03;
  18154. /** Passed to stencilOperation to specify that stencil value must be inverted */
  18155. Engine.INVERT = 0x150A;
  18156. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  18157. Engine.INCR_WRAP = 0x8507;
  18158. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  18159. Engine.DECR_WRAP = 0x8508;
  18160. /** Texture is not repeating outside of 0..1 UVs */
  18161. Engine.TEXTURE_CLAMP_ADDRESSMODE = 0;
  18162. /** Texture is repeating outside of 0..1 UVs */
  18163. Engine.TEXTURE_WRAP_ADDRESSMODE = 1;
  18164. /** Texture is repeating and mirrored */
  18165. Engine.TEXTURE_MIRROR_ADDRESSMODE = 2;
  18166. /** ALPHA */
  18167. Engine.TEXTUREFORMAT_ALPHA = 0;
  18168. /** LUMINANCE */
  18169. Engine.TEXTUREFORMAT_LUMINANCE = 1;
  18170. /** LUMINANCE_ALPHA */
  18171. Engine.TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  18172. /** RGB */
  18173. Engine.TEXTUREFORMAT_RGB = 4;
  18174. /** RGBA */
  18175. Engine.TEXTUREFORMAT_RGBA = 5;
  18176. /** RED */
  18177. Engine.TEXTUREFORMAT_RED = 6;
  18178. /** RED (2nd reference) */
  18179. Engine.TEXTUREFORMAT_R = 6;
  18180. /** RG */
  18181. Engine.TEXTUREFORMAT_RG = 7;
  18182. /** RED_INTEGER */
  18183. Engine.TEXTUREFORMAT_RED_INTEGER = 8;
  18184. /** RED_INTEGER (2nd reference) */
  18185. Engine.TEXTUREFORMAT_R_INTEGER = 8;
  18186. /** RG_INTEGER */
  18187. Engine.TEXTUREFORMAT_RG_INTEGER = 9;
  18188. /** RGB_INTEGER */
  18189. Engine.TEXTUREFORMAT_RGB_INTEGER = 10;
  18190. /** RGBA_INTEGER */
  18191. Engine.TEXTUREFORMAT_RGBA_INTEGER = 11;
  18192. /** UNSIGNED_BYTE */
  18193. Engine.TEXTURETYPE_UNSIGNED_BYTE = 0;
  18194. /** UNSIGNED_BYTE (2nd reference) */
  18195. Engine.TEXTURETYPE_UNSIGNED_INT = 0;
  18196. /** FLOAT */
  18197. Engine.TEXTURETYPE_FLOAT = 1;
  18198. /** HALF_FLOAT */
  18199. Engine.TEXTURETYPE_HALF_FLOAT = 2;
  18200. /** BYTE */
  18201. Engine.TEXTURETYPE_BYTE = 3;
  18202. /** SHORT */
  18203. Engine.TEXTURETYPE_SHORT = 4;
  18204. /** UNSIGNED_SHORT */
  18205. Engine.TEXTURETYPE_UNSIGNED_SHORT = 5;
  18206. /** INT */
  18207. Engine.TEXTURETYPE_INT = 6;
  18208. /** UNSIGNED_INT */
  18209. Engine.TEXTURETYPE_UNSIGNED_INTEGER = 7;
  18210. /** UNSIGNED_SHORT_4_4_4_4 */
  18211. Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 = 8;
  18212. /** UNSIGNED_SHORT_5_5_5_1 */
  18213. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 = 9;
  18214. /** UNSIGNED_SHORT_5_6_5 */
  18215. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5 = 10;
  18216. /** UNSIGNED_INT_2_10_10_10_REV */
  18217. Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV = 11;
  18218. /** UNSIGNED_INT_24_8 */
  18219. Engine.TEXTURETYPE_UNSIGNED_INT_24_8 = 12;
  18220. /** UNSIGNED_INT_10F_11F_11F_REV */
  18221. Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV = 13;
  18222. /** UNSIGNED_INT_5_9_9_9_REV */
  18223. Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV = 14;
  18224. /** FLOAT_32_UNSIGNED_INT_24_8_REV */
  18225. Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV = 15;
  18226. /** nearest is mag = nearest and min = nearest and mip = linear */
  18227. Engine.TEXTURE_NEAREST_SAMPLINGMODE = 1;
  18228. /** Bilinear is mag = linear and min = linear and mip = nearest */
  18229. Engine.TEXTURE_BILINEAR_SAMPLINGMODE = 2;
  18230. /** Trilinear is mag = linear and min = linear and mip = linear */
  18231. Engine.TEXTURE_TRILINEAR_SAMPLINGMODE = 3;
  18232. /** nearest is mag = nearest and min = nearest and mip = linear */
  18233. Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 1;
  18234. /** Bilinear is mag = linear and min = linear and mip = nearest */
  18235. Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 2;
  18236. /** Trilinear is mag = linear and min = linear and mip = linear */
  18237. Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3;
  18238. /** mag = nearest and min = nearest and mip = nearest */
  18239. Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4;
  18240. /** mag = nearest and min = linear and mip = nearest */
  18241. Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5;
  18242. /** mag = nearest and min = linear and mip = linear */
  18243. Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6;
  18244. /** mag = nearest and min = linear and mip = none */
  18245. Engine.TEXTURE_NEAREST_LINEAR = 7;
  18246. /** mag = nearest and min = nearest and mip = none */
  18247. Engine.TEXTURE_NEAREST_NEAREST = 8;
  18248. /** mag = linear and min = nearest and mip = nearest */
  18249. Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9;
  18250. /** mag = linear and min = nearest and mip = linear */
  18251. Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10;
  18252. /** mag = linear and min = linear and mip = none */
  18253. Engine.TEXTURE_LINEAR_LINEAR = 11;
  18254. /** mag = linear and min = nearest and mip = none */
  18255. Engine.TEXTURE_LINEAR_NEAREST = 12;
  18256. /** Explicit coordinates mode */
  18257. Engine.TEXTURE_EXPLICIT_MODE = 0;
  18258. /** Spherical coordinates mode */
  18259. Engine.TEXTURE_SPHERICAL_MODE = 1;
  18260. /** Planar coordinates mode */
  18261. Engine.TEXTURE_PLANAR_MODE = 2;
  18262. /** Cubic coordinates mode */
  18263. Engine.TEXTURE_CUBIC_MODE = 3;
  18264. /** Projection coordinates mode */
  18265. Engine.TEXTURE_PROJECTION_MODE = 4;
  18266. /** Skybox coordinates mode */
  18267. Engine.TEXTURE_SKYBOX_MODE = 5;
  18268. /** Inverse Cubic coordinates mode */
  18269. Engine.TEXTURE_INVCUBIC_MODE = 6;
  18270. /** Equirectangular coordinates mode */
  18271. Engine.TEXTURE_EQUIRECTANGULAR_MODE = 7;
  18272. /** Equirectangular Fixed coordinates mode */
  18273. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8;
  18274. /** Equirectangular Fixed Mirrored coordinates mode */
  18275. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  18276. // Texture rescaling mode
  18277. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  18278. Engine.SCALEMODE_FLOOR = 1;
  18279. /** Defines that texture rescaling will look for the nearest power of 2 size */
  18280. Engine.SCALEMODE_NEAREST = 2;
  18281. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  18282. Engine.SCALEMODE_CEILING = 3;
  18283. // Updatable statics so stick with vars here
  18284. /**
  18285. * Gets or sets the epsilon value used by collision engine
  18286. */
  18287. Engine.CollisionsEpsilon = 0.001;
  18288. /**
  18289. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  18290. */
  18291. Engine.CodeRepository = "src/";
  18292. /**
  18293. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  18294. */
  18295. Engine.ShadersRepository = "src/Shaders/";
  18296. return Engine;
  18297. }());
  18298. BABYLON.Engine = Engine;
  18299. })(BABYLON || (BABYLON = {}));
  18300. //# sourceMappingURL=babylon.engine.js.map
  18301. var BABYLON;
  18302. (function (BABYLON) {
  18303. /**
  18304. * Node is the basic class for all scene objects (Mesh, Light, Camera.)
  18305. */
  18306. var Node = /** @class */ (function () {
  18307. /**
  18308. * Creates a new Node
  18309. * @param {string} name - the name and id to be given to this node
  18310. * @param {BABYLON.Scene} the scene this node will be added to
  18311. */
  18312. function Node(name, scene) {
  18313. if (scene === void 0) { scene = null; }
  18314. /**
  18315. * Gets or sets a string used to store user defined state for the node
  18316. */
  18317. this.state = "";
  18318. /**
  18319. * Gets or sets an object used to store user defined information for the node
  18320. */
  18321. this.metadata = null;
  18322. /**
  18323. * Gets or sets a boolean used to define if the node must be serialized
  18324. */
  18325. this.doNotSerialize = false;
  18326. /** @hidden */
  18327. this._isDisposed = false;
  18328. /**
  18329. * Gets a list of Animations associated with the node
  18330. */
  18331. this.animations = new Array();
  18332. this._ranges = {};
  18333. this._isEnabled = true;
  18334. this._isParentEnabled = true;
  18335. this._isReady = true;
  18336. /** @hidden */
  18337. this._currentRenderId = -1;
  18338. this._parentRenderId = -1;
  18339. this._childRenderId = -1;
  18340. /** @hidden */
  18341. this._worldMatrix = BABYLON.Matrix.Identity();
  18342. /** @hidden */
  18343. this._worldMatrixDeterminant = 0;
  18344. /** @hidden */
  18345. this._sceneRootNodesIndex = -1;
  18346. this._animationPropertiesOverride = null;
  18347. /**
  18348. * An event triggered when the mesh is disposed
  18349. */
  18350. this.onDisposeObservable = new BABYLON.Observable();
  18351. // Behaviors
  18352. this._behaviors = new Array();
  18353. this.name = name;
  18354. this.id = name;
  18355. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  18356. this.uniqueId = this._scene.getUniqueId();
  18357. this._initCache();
  18358. this.addToSceneRootNodes();
  18359. }
  18360. /**
  18361. * Add a new node constructor
  18362. * @param type defines the type name of the node to construct
  18363. * @param constructorFunc defines the constructor function
  18364. */
  18365. Node.AddNodeConstructor = function (type, constructorFunc) {
  18366. this._NodeConstructors[type] = constructorFunc;
  18367. };
  18368. /**
  18369. * Returns a node constructor based on type name
  18370. * @param type defines the type name
  18371. * @param name defines the new node name
  18372. * @param scene defines the hosting scene
  18373. * @param options defines optional options to transmit to constructors
  18374. * @returns the new constructor or null
  18375. */
  18376. Node.Construct = function (type, name, scene, options) {
  18377. var constructorFunc = this._NodeConstructors[type];
  18378. if (!constructorFunc) {
  18379. return null;
  18380. }
  18381. return constructorFunc(name, scene, options);
  18382. };
  18383. /**
  18384. * Gets a boolean indicating if the node has been disposed
  18385. * @returns true if the node was disposed
  18386. */
  18387. Node.prototype.isDisposed = function () {
  18388. return this._isDisposed;
  18389. };
  18390. Object.defineProperty(Node.prototype, "parent", {
  18391. get: function () {
  18392. return this._parentNode;
  18393. },
  18394. /**
  18395. * Gets or sets the parent of the node
  18396. */
  18397. set: function (parent) {
  18398. if (this._parentNode === parent) {
  18399. return;
  18400. }
  18401. var previousParentNode = this._parentNode;
  18402. // Remove self from list of children of parent
  18403. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  18404. var index = this._parentNode._children.indexOf(this);
  18405. if (index !== -1) {
  18406. this._parentNode._children.splice(index, 1);
  18407. }
  18408. if (!parent) {
  18409. this.addToSceneRootNodes();
  18410. }
  18411. }
  18412. // Store new parent
  18413. this._parentNode = parent;
  18414. // Add as child to new parent
  18415. if (this._parentNode) {
  18416. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  18417. this._parentNode._children = new Array();
  18418. }
  18419. this._parentNode._children.push(this);
  18420. if (!previousParentNode) {
  18421. this.removeFromSceneRootNodes();
  18422. }
  18423. }
  18424. // Enabled state
  18425. this._syncParentEnabledState();
  18426. },
  18427. enumerable: true,
  18428. configurable: true
  18429. });
  18430. Node.prototype.addToSceneRootNodes = function () {
  18431. if (this._sceneRootNodesIndex === -1) {
  18432. this._sceneRootNodesIndex = this._scene.rootNodes.length;
  18433. this._scene.rootNodes.push(this);
  18434. }
  18435. };
  18436. Node.prototype.removeFromSceneRootNodes = function () {
  18437. if (this._sceneRootNodesIndex !== -1) {
  18438. var rootNodes = this._scene.rootNodes;
  18439. var lastIdx = rootNodes.length - 1;
  18440. rootNodes[this._sceneRootNodesIndex] = rootNodes[lastIdx];
  18441. rootNodes[this._sceneRootNodesIndex]._sceneRootNodesIndex = this._sceneRootNodesIndex;
  18442. this._scene.rootNodes.pop();
  18443. this._sceneRootNodesIndex = -1;
  18444. }
  18445. };
  18446. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  18447. /**
  18448. * Gets or sets the animation properties override
  18449. */
  18450. get: function () {
  18451. if (!this._animationPropertiesOverride) {
  18452. return this._scene.animationPropertiesOverride;
  18453. }
  18454. return this._animationPropertiesOverride;
  18455. },
  18456. set: function (value) {
  18457. this._animationPropertiesOverride = value;
  18458. },
  18459. enumerable: true,
  18460. configurable: true
  18461. });
  18462. /**
  18463. * Gets a string idenfifying the name of the class
  18464. * @returns "Node" string
  18465. */
  18466. Node.prototype.getClassName = function () {
  18467. return "Node";
  18468. };
  18469. Object.defineProperty(Node.prototype, "onDispose", {
  18470. /**
  18471. * Sets a callback that will be raised when the node will be disposed
  18472. */
  18473. set: function (callback) {
  18474. if (this._onDisposeObserver) {
  18475. this.onDisposeObservable.remove(this._onDisposeObserver);
  18476. }
  18477. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  18478. },
  18479. enumerable: true,
  18480. configurable: true
  18481. });
  18482. /**
  18483. * Gets the scene of the node
  18484. * @returns a {BABYLON.Scene}
  18485. */
  18486. Node.prototype.getScene = function () {
  18487. return this._scene;
  18488. };
  18489. /**
  18490. * Gets the engine of the node
  18491. * @returns a {BABYLON.Engine}
  18492. */
  18493. Node.prototype.getEngine = function () {
  18494. return this._scene.getEngine();
  18495. };
  18496. /**
  18497. * Attach a behavior to the node
  18498. * @see http://doc.babylonjs.com/features/behaviour
  18499. * @param behavior defines the behavior to attach
  18500. * @param attachImmediately defines that the behavior must be attached even if the scene is still loading
  18501. * @returns the current Node
  18502. */
  18503. Node.prototype.addBehavior = function (behavior, attachImmediately) {
  18504. var _this = this;
  18505. if (attachImmediately === void 0) { attachImmediately = false; }
  18506. var index = this._behaviors.indexOf(behavior);
  18507. if (index !== -1) {
  18508. return this;
  18509. }
  18510. behavior.init();
  18511. if (this._scene.isLoading && !attachImmediately) {
  18512. // We defer the attach when the scene will be loaded
  18513. this._scene.onDataLoadedObservable.addOnce(function () {
  18514. behavior.attach(_this);
  18515. });
  18516. }
  18517. else {
  18518. behavior.attach(this);
  18519. }
  18520. this._behaviors.push(behavior);
  18521. return this;
  18522. };
  18523. /**
  18524. * Remove an attached behavior
  18525. * @see http://doc.babylonjs.com/features/behaviour
  18526. * @param behavior defines the behavior to attach
  18527. * @returns the current Node
  18528. */
  18529. Node.prototype.removeBehavior = function (behavior) {
  18530. var index = this._behaviors.indexOf(behavior);
  18531. if (index === -1) {
  18532. return this;
  18533. }
  18534. this._behaviors[index].detach();
  18535. this._behaviors.splice(index, 1);
  18536. return this;
  18537. };
  18538. Object.defineProperty(Node.prototype, "behaviors", {
  18539. /**
  18540. * Gets the list of attached behaviors
  18541. * @see http://doc.babylonjs.com/features/behaviour
  18542. */
  18543. get: function () {
  18544. return this._behaviors;
  18545. },
  18546. enumerable: true,
  18547. configurable: true
  18548. });
  18549. /**
  18550. * Gets an attached behavior by name
  18551. * @param name defines the name of the behavior to look for
  18552. * @see http://doc.babylonjs.com/features/behaviour
  18553. * @returns null if behavior was not found else the requested behavior
  18554. */
  18555. Node.prototype.getBehaviorByName = function (name) {
  18556. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  18557. var behavior = _a[_i];
  18558. if (behavior.name === name) {
  18559. return behavior;
  18560. }
  18561. }
  18562. return null;
  18563. };
  18564. /**
  18565. * Returns the latest update of the World matrix
  18566. * @returns a Matrix
  18567. */
  18568. Node.prototype.getWorldMatrix = function () {
  18569. if (this._currentRenderId !== this._scene.getRenderId()) {
  18570. this.computeWorldMatrix();
  18571. }
  18572. return this._worldMatrix;
  18573. };
  18574. /** @hidden */
  18575. Node.prototype._getWorldMatrixDeterminant = function () {
  18576. return this._worldMatrixDeterminant;
  18577. };
  18578. Object.defineProperty(Node.prototype, "worldMatrixFromCache", {
  18579. /**
  18580. * Returns directly the latest state of the mesh World matrix.
  18581. * A Matrix is returned.
  18582. */
  18583. get: function () {
  18584. return this._worldMatrix;
  18585. },
  18586. enumerable: true,
  18587. configurable: true
  18588. });
  18589. // override it in derived class if you add new variables to the cache
  18590. // and call the parent class method
  18591. /** @hidden */
  18592. Node.prototype._initCache = function () {
  18593. this._cache = {};
  18594. this._cache.parent = undefined;
  18595. };
  18596. /** @hidden */
  18597. Node.prototype.updateCache = function (force) {
  18598. if (!force && this.isSynchronized())
  18599. return;
  18600. this._cache.parent = this.parent;
  18601. this._updateCache();
  18602. };
  18603. // override it in derived class if you add new variables to the cache
  18604. // and call the parent class method if !ignoreParentClass
  18605. /** @hidden */
  18606. Node.prototype._updateCache = function (ignoreParentClass) {
  18607. };
  18608. // override it in derived class if you add new variables to the cache
  18609. /** @hidden */
  18610. Node.prototype._isSynchronized = function () {
  18611. return true;
  18612. };
  18613. /** @hidden */
  18614. Node.prototype._markSyncedWithParent = function () {
  18615. if (this._parentNode) {
  18616. this._parentRenderId = this._parentNode._childRenderId;
  18617. }
  18618. };
  18619. /** @hidden */
  18620. Node.prototype.isSynchronizedWithParent = function () {
  18621. if (!this._parentNode) {
  18622. return true;
  18623. }
  18624. if (this._parentRenderId !== this._parentNode._childRenderId) {
  18625. return false;
  18626. }
  18627. return this._parentNode.isSynchronized();
  18628. };
  18629. /** @hidden */
  18630. Node.prototype.isSynchronized = function () {
  18631. if (this._cache.parent != this._parentNode) {
  18632. this._cache.parent = this._parentNode;
  18633. return false;
  18634. }
  18635. if (this._parentNode && !this.isSynchronizedWithParent()) {
  18636. return false;
  18637. }
  18638. return this._isSynchronized();
  18639. };
  18640. /**
  18641. * Is this node ready to be used/rendered
  18642. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  18643. * @return true if the node is ready
  18644. */
  18645. Node.prototype.isReady = function (completeCheck) {
  18646. if (completeCheck === void 0) { completeCheck = false; }
  18647. return this._isReady;
  18648. };
  18649. /**
  18650. * Is this node enabled?
  18651. * 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
  18652. * @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
  18653. * @return whether this node (and its parent) is enabled
  18654. */
  18655. Node.prototype.isEnabled = function (checkAncestors) {
  18656. if (checkAncestors === void 0) { checkAncestors = true; }
  18657. if (checkAncestors === false) {
  18658. return this._isEnabled;
  18659. }
  18660. if (!this._isEnabled) {
  18661. return false;
  18662. }
  18663. return this._isParentEnabled;
  18664. };
  18665. /** @hidden */
  18666. Node.prototype._syncParentEnabledState = function () {
  18667. this._isParentEnabled = this._parentNode ? this._parentNode.isEnabled() : true;
  18668. if (this._children) {
  18669. this._children.forEach(function (c) {
  18670. c._syncParentEnabledState(); // Force children to update accordingly
  18671. });
  18672. }
  18673. };
  18674. /**
  18675. * Set the enabled state of this node
  18676. * @param value defines the new enabled state
  18677. */
  18678. Node.prototype.setEnabled = function (value) {
  18679. this._isEnabled = value;
  18680. this._syncParentEnabledState();
  18681. };
  18682. /**
  18683. * Is this node a descendant of the given node?
  18684. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  18685. * @param ancestor defines the parent node to inspect
  18686. * @returns a boolean indicating if this node is a descendant of the given node
  18687. */
  18688. Node.prototype.isDescendantOf = function (ancestor) {
  18689. if (this.parent) {
  18690. if (this.parent === ancestor) {
  18691. return true;
  18692. }
  18693. return this.parent.isDescendantOf(ancestor);
  18694. }
  18695. return false;
  18696. };
  18697. /** @hidden */
  18698. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  18699. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  18700. if (!this._children) {
  18701. return;
  18702. }
  18703. for (var index = 0; index < this._children.length; index++) {
  18704. var item = this._children[index];
  18705. if (!predicate || predicate(item)) {
  18706. results.push(item);
  18707. }
  18708. if (!directDescendantsOnly) {
  18709. item._getDescendants(results, false, predicate);
  18710. }
  18711. }
  18712. };
  18713. /**
  18714. * Will return all nodes that have this node as ascendant
  18715. * @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
  18716. * @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
  18717. * @return all children nodes of all types
  18718. */
  18719. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  18720. var results = new Array();
  18721. this._getDescendants(results, directDescendantsOnly, predicate);
  18722. return results;
  18723. };
  18724. /**
  18725. * Get all child-meshes of this node
  18726. * @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
  18727. * @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
  18728. * @returns an array of {BABYLON.AbstractMesh}
  18729. */
  18730. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  18731. var results = [];
  18732. this._getDescendants(results, directDescendantsOnly, function (node) {
  18733. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  18734. });
  18735. return results;
  18736. };
  18737. /**
  18738. * Get all child-transformNodes of this node
  18739. * @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
  18740. * @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
  18741. * @returns an array of {BABYLON.TransformNode}
  18742. */
  18743. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  18744. var results = [];
  18745. this._getDescendants(results, directDescendantsOnly, function (node) {
  18746. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  18747. });
  18748. return results;
  18749. };
  18750. /**
  18751. * Get all direct children of this node
  18752. * @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
  18753. * @returns an array of {BABYLON.Node}
  18754. */
  18755. Node.prototype.getChildren = function (predicate) {
  18756. return this.getDescendants(true, predicate);
  18757. };
  18758. /** @hidden */
  18759. Node.prototype._setReady = function (state) {
  18760. if (state === this._isReady) {
  18761. return;
  18762. }
  18763. if (!state) {
  18764. this._isReady = false;
  18765. return;
  18766. }
  18767. if (this.onReady) {
  18768. this.onReady(this);
  18769. }
  18770. this._isReady = true;
  18771. };
  18772. /**
  18773. * Get an animation by name
  18774. * @param name defines the name of the animation to look for
  18775. * @returns null if not found else the requested animation
  18776. */
  18777. Node.prototype.getAnimationByName = function (name) {
  18778. for (var i = 0; i < this.animations.length; i++) {
  18779. var animation = this.animations[i];
  18780. if (animation.name === name) {
  18781. return animation;
  18782. }
  18783. }
  18784. return null;
  18785. };
  18786. /**
  18787. * Creates an animation range for this node
  18788. * @param name defines the name of the range
  18789. * @param from defines the starting key
  18790. * @param to defines the end key
  18791. */
  18792. Node.prototype.createAnimationRange = function (name, from, to) {
  18793. // check name not already in use
  18794. if (!this._ranges[name]) {
  18795. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  18796. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18797. if (this.animations[i]) {
  18798. this.animations[i].createRange(name, from, to);
  18799. }
  18800. }
  18801. }
  18802. };
  18803. /**
  18804. * Delete a specific animation range
  18805. * @param name defines the name of the range to delete
  18806. * @param deleteFrames defines if animation frames from the range must be deleted as well
  18807. */
  18808. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  18809. if (deleteFrames === void 0) { deleteFrames = true; }
  18810. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18811. if (this.animations[i]) {
  18812. this.animations[i].deleteRange(name, deleteFrames);
  18813. }
  18814. }
  18815. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  18816. };
  18817. /**
  18818. * Get an animation range by name
  18819. * @param name defines the name of the animation range to look for
  18820. * @returns null if not found else the requested animation range
  18821. */
  18822. Node.prototype.getAnimationRange = function (name) {
  18823. return this._ranges[name];
  18824. };
  18825. /**
  18826. * Will start the animation sequence
  18827. * @param name defines the range frames for animation sequence
  18828. * @param loop defines if the animation should loop (false by default)
  18829. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  18830. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  18831. * @returns the object created for this animation. If range does not exist, it will return null
  18832. */
  18833. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  18834. var range = this.getAnimationRange(name);
  18835. if (!range) {
  18836. return null;
  18837. }
  18838. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  18839. };
  18840. /**
  18841. * Serialize animation ranges into a JSON compatible object
  18842. * @returns serialization object
  18843. */
  18844. Node.prototype.serializeAnimationRanges = function () {
  18845. var serializationRanges = [];
  18846. for (var name in this._ranges) {
  18847. var localRange = this._ranges[name];
  18848. if (!localRange) {
  18849. continue;
  18850. }
  18851. var range = {};
  18852. range.name = name;
  18853. range.from = localRange.from;
  18854. range.to = localRange.to;
  18855. serializationRanges.push(range);
  18856. }
  18857. return serializationRanges;
  18858. };
  18859. /**
  18860. * Computes the world matrix of the node
  18861. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  18862. * @returns the world matrix
  18863. */
  18864. Node.prototype.computeWorldMatrix = function (force) {
  18865. if (!this._worldMatrix) {
  18866. this._worldMatrix = BABYLON.Matrix.Identity();
  18867. }
  18868. return this._worldMatrix;
  18869. };
  18870. /**
  18871. * Releases resources associated with this node.
  18872. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18873. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18874. */
  18875. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18876. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18877. if (!doNotRecurse) {
  18878. var nodes = this.getDescendants(true);
  18879. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  18880. var node = nodes_1[_i];
  18881. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  18882. }
  18883. }
  18884. else {
  18885. var transformNodes = this.getChildTransformNodes(true);
  18886. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  18887. var transformNode = transformNodes_1[_a];
  18888. transformNode.parent = null;
  18889. transformNode.computeWorldMatrix(true);
  18890. }
  18891. }
  18892. if (!this.parent) {
  18893. this.removeFromSceneRootNodes();
  18894. }
  18895. else {
  18896. this.parent = null;
  18897. }
  18898. // Callback
  18899. this.onDisposeObservable.notifyObservers(this);
  18900. this.onDisposeObservable.clear();
  18901. // Behaviors
  18902. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  18903. var behavior = _c[_b];
  18904. behavior.detach();
  18905. }
  18906. this._behaviors = [];
  18907. this._isDisposed = true;
  18908. };
  18909. /**
  18910. * Parse animation range data from a serialization object and store them into a given node
  18911. * @param node defines where to store the animation ranges
  18912. * @param parsedNode defines the serialization object to read data from
  18913. * @param scene defines the hosting scene
  18914. */
  18915. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  18916. if (parsedNode.ranges) {
  18917. for (var index = 0; index < parsedNode.ranges.length; index++) {
  18918. var data = parsedNode.ranges[index];
  18919. node.createAnimationRange(data.name, data.from, data.to);
  18920. }
  18921. }
  18922. };
  18923. Node._NodeConstructors = {};
  18924. __decorate([
  18925. BABYLON.serialize()
  18926. ], Node.prototype, "name", void 0);
  18927. __decorate([
  18928. BABYLON.serialize()
  18929. ], Node.prototype, "id", void 0);
  18930. __decorate([
  18931. BABYLON.serialize()
  18932. ], Node.prototype, "uniqueId", void 0);
  18933. __decorate([
  18934. BABYLON.serialize()
  18935. ], Node.prototype, "state", void 0);
  18936. __decorate([
  18937. BABYLON.serialize()
  18938. ], Node.prototype, "metadata", void 0);
  18939. return Node;
  18940. }());
  18941. BABYLON.Node = Node;
  18942. })(BABYLON || (BABYLON = {}));
  18943. //# sourceMappingURL=babylon.node.js.map
  18944. var BABYLON;
  18945. (function (BABYLON) {
  18946. // This matrix is used as a value to reset the bounding box.
  18947. var _identityMatrix = BABYLON.Matrix.Identity();
  18948. /**
  18949. * Class used to store bounding sphere information
  18950. */
  18951. var BoundingSphere = /** @class */ (function () {
  18952. /**
  18953. * Creates a new bounding sphere
  18954. * @param min defines the minimum vector (in local space)
  18955. * @param max defines the maximum vector (in local space)
  18956. */
  18957. function BoundingSphere(min, max) {
  18958. /**
  18959. * Gets the center of the bounding sphere in local space
  18960. */
  18961. this.center = BABYLON.Vector3.Zero();
  18962. /**
  18963. * Gets the center of the bounding sphere in world space
  18964. */
  18965. this.centerWorld = BABYLON.Vector3.Zero();
  18966. /**
  18967. * Gets the minimum vector in local space
  18968. */
  18969. this.minimum = BABYLON.Vector3.Zero();
  18970. /**
  18971. * Gets the maximum vector in local space
  18972. */
  18973. this.maximum = BABYLON.Vector3.Zero();
  18974. this.reConstruct(min, max);
  18975. }
  18976. /**
  18977. * Recreates the entire bounding sphere from scratch
  18978. * @param min defines the new minimum vector (in local space)
  18979. * @param max defines the new maximum vector (in local space)
  18980. */
  18981. BoundingSphere.prototype.reConstruct = function (min, max) {
  18982. this.minimum.copyFrom(min);
  18983. this.maximum.copyFrom(max);
  18984. var distance = BABYLON.Vector3.Distance(min, max);
  18985. BABYLON.Vector3.LerpToRef(min, max, 0.5, this.center);
  18986. this.radius = distance * 0.5;
  18987. this.centerWorld.set(0, 0, 0);
  18988. this._update(_identityMatrix);
  18989. };
  18990. /**
  18991. * Scale the current bounding sphere by applying a scale factor
  18992. * @param factor defines the scale factor to apply
  18993. * @returns the current bounding box
  18994. */
  18995. BoundingSphere.prototype.scale = function (factor) {
  18996. var newRadius = this.radius * factor;
  18997. var tempRadiusVector = BABYLON.Tmp.Vector3[0].set(newRadius, newRadius, newRadius);
  18998. var min = BABYLON.Tmp.Vector3[1].copyFrom(this.center).subtractInPlace(tempRadiusVector);
  18999. var max = BABYLON.Tmp.Vector3[2].copyFrom(this.center).addInPlace(tempRadiusVector);
  19000. this.reConstruct(min, max);
  19001. return this;
  19002. };
  19003. // Methods
  19004. /** @hidden */
  19005. BoundingSphere.prototype._update = function (world) {
  19006. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  19007. var tempVector = BABYLON.Tmp.Vector3[0];
  19008. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, tempVector);
  19009. this.radiusWorld = Math.max(Math.abs(tempVector.x), Math.abs(tempVector.y), Math.abs(tempVector.z)) * this.radius;
  19010. };
  19011. /**
  19012. * Tests if the bounding sphere is intersecting the frustum planes
  19013. * @param frustumPlanes defines the frustum planes to test
  19014. * @returns true if there is an intersection
  19015. */
  19016. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  19017. for (var i = 0; i < 6; i++) {
  19018. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  19019. return false;
  19020. }
  19021. return true;
  19022. };
  19023. /**
  19024. * Tests if a point is inside the bounding sphere
  19025. * @param point defines the point to test
  19026. * @returns true if the point is inside the bounding sphere
  19027. */
  19028. BoundingSphere.prototype.intersectsPoint = function (point) {
  19029. var x = this.centerWorld.x - point.x;
  19030. var y = this.centerWorld.y - point.y;
  19031. var z = this.centerWorld.z - point.z;
  19032. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  19033. if (this.radiusWorld < distance)
  19034. return false;
  19035. return true;
  19036. };
  19037. // Statics
  19038. /**
  19039. * Checks if two sphere intersct
  19040. * @param sphere0 sphere 0
  19041. * @param sphere1 sphere 1
  19042. * @returns true if the speres intersect
  19043. */
  19044. BoundingSphere.Intersects = function (sphere0, sphere1) {
  19045. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  19046. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  19047. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  19048. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  19049. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  19050. return false;
  19051. return true;
  19052. };
  19053. return BoundingSphere;
  19054. }());
  19055. BABYLON.BoundingSphere = BoundingSphere;
  19056. })(BABYLON || (BABYLON = {}));
  19057. //# sourceMappingURL=babylon.boundingSphere.js.map
  19058. var BABYLON;
  19059. (function (BABYLON) {
  19060. /**
  19061. * Class used to store bounding box information
  19062. */
  19063. var BoundingBox = /** @class */ (function () {
  19064. /**
  19065. * Creates a new bounding box
  19066. * @param min defines the minimum vector (in local space)
  19067. * @param max defines the maximum vector (in local space)
  19068. */
  19069. function BoundingBox(min, max) {
  19070. /**
  19071. * Gets the 8 vectors representing the bounding box in local space
  19072. */
  19073. this.vectors = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  19074. /**
  19075. * Gets the center of the bounding box in local space
  19076. */
  19077. this.center = BABYLON.Vector3.Zero();
  19078. /**
  19079. * Gets the center of the bounding box in world space
  19080. */
  19081. this.centerWorld = BABYLON.Vector3.Zero();
  19082. /**
  19083. * Gets the extend size in local space
  19084. */
  19085. this.extendSize = BABYLON.Vector3.Zero();
  19086. /**
  19087. * Gets the extend size in world space
  19088. */
  19089. this.extendSizeWorld = BABYLON.Vector3.Zero();
  19090. /**
  19091. * Gets the OBB (object bounding box) directions
  19092. */
  19093. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  19094. /**
  19095. * Gets the 8 vectors representing the bounding box in world space
  19096. */
  19097. this.vectorsWorld = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  19098. /**
  19099. * Gets the minimum vector in world space
  19100. */
  19101. this.minimumWorld = BABYLON.Vector3.Zero();
  19102. /**
  19103. * Gets the maximum vector in world space
  19104. */
  19105. this.maximumWorld = BABYLON.Vector3.Zero();
  19106. /**
  19107. * Gets the minimum vector in local space
  19108. */
  19109. this.minimum = BABYLON.Vector3.Zero();
  19110. /**
  19111. * Gets the maximum vector in local space
  19112. */
  19113. this.maximum = BABYLON.Vector3.Zero();
  19114. this.reConstruct(min, max);
  19115. }
  19116. ;
  19117. // Methods
  19118. /**
  19119. * Recreates the entire bounding box from scratch
  19120. * @param min defines the new minimum vector (in local space)
  19121. * @param max defines the new maximum vector (in local space)
  19122. */
  19123. BoundingBox.prototype.reConstruct = function (min, max) {
  19124. this.minimum.copyFrom(min);
  19125. this.maximum.copyFrom(max);
  19126. // Bounding vectors
  19127. this.vectors[0].copyFrom(this.minimum);
  19128. this.vectors[1].copyFrom(this.maximum);
  19129. this.vectors[2].copyFrom(this.minimum);
  19130. this.vectors[3].copyFrom(this.minimum);
  19131. this.vectors[4].copyFrom(this.minimum);
  19132. this.vectors[5].copyFrom(this.maximum);
  19133. this.vectors[6].copyFrom(this.maximum);
  19134. this.vectors[7].copyFrom(this.maximum);
  19135. this.vectors[2].x = this.maximum.x;
  19136. this.vectors[3].y = this.maximum.y;
  19137. this.vectors[4].z = this.maximum.z;
  19138. this.vectors[5].z = this.minimum.z;
  19139. this.vectors[6].x = this.minimum.x;
  19140. this.vectors[7].y = this.minimum.y;
  19141. // OBB
  19142. this.center.copyFrom(this.maximum).addInPlace(this.minimum).scaleInPlace(0.5);
  19143. this.extendSize.copyFrom(this.maximum).subtractInPlace(this.minimum).scaleInPlace(0.5);
  19144. for (var index = 0; index < 3; index++) {
  19145. this.directions[index].copyFromFloats(0, 0, 0);
  19146. }
  19147. // World
  19148. for (var index = 0; index < 8; index++) {
  19149. this.vectorsWorld[index].copyFromFloats(0, 0, 0);
  19150. }
  19151. this.minimumWorld.copyFromFloats(0, 0, 0);
  19152. this.maximumWorld.copyFromFloats(0, 0, 0);
  19153. this.centerWorld.copyFromFloats(0, 0, 0);
  19154. this.extendSizeWorld.copyFromFloats(0, 0, 0);
  19155. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  19156. };
  19157. /**
  19158. * Scale the current bounding box by applying a scale factor
  19159. * @param factor defines the scale factor to apply
  19160. * @returns the current bounding box
  19161. */
  19162. BoundingBox.prototype.scale = function (factor) {
  19163. var diff = BABYLON.Tmp.Vector3[0].copyFrom(this.maximum).subtractInPlace(this.minimum);
  19164. var distance = diff.length() * factor;
  19165. diff.normalize();
  19166. var newRadius = diff.scaleInPlace(distance * 0.5);
  19167. var min = BABYLON.Tmp.Vector3[1].copyFrom(this.center).subtractInPlace(newRadius);
  19168. var max = BABYLON.Tmp.Vector3[2].copyFrom(this.center).addInPlace(newRadius);
  19169. this.reConstruct(min, max);
  19170. return this;
  19171. };
  19172. /**
  19173. * Gets the world matrix of the bounding box
  19174. * @returns a matrix
  19175. */
  19176. BoundingBox.prototype.getWorldMatrix = function () {
  19177. return this._worldMatrix;
  19178. };
  19179. /**
  19180. * Sets the world matrix stored in the bounding box
  19181. * @param matrix defines the matrix to store
  19182. * @returns current bounding box
  19183. */
  19184. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  19185. this._worldMatrix.copyFrom(matrix);
  19186. return this;
  19187. };
  19188. /** @hidden */
  19189. BoundingBox.prototype._update = function (world) {
  19190. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  19191. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  19192. for (var index = 0; index < 8; index++) {
  19193. var v = this.vectorsWorld[index];
  19194. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  19195. this.minimumWorld.minimizeInPlace(v);
  19196. this.maximumWorld.maximizeInPlace(v);
  19197. }
  19198. // Extend
  19199. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  19200. this.extendSizeWorld.scaleInPlace(0.5);
  19201. // OBB
  19202. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  19203. this.centerWorld.scaleInPlace(0.5);
  19204. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  19205. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  19206. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  19207. this._worldMatrix = world;
  19208. };
  19209. /**
  19210. * Tests if the bounding box is intersecting the frustum planes
  19211. * @param frustumPlanes defines the frustum planes to test
  19212. * @returns true if there is an intersection
  19213. */
  19214. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  19215. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  19216. };
  19217. /**
  19218. * Tests if the bounding box is entirely inside the frustum planes
  19219. * @param frustumPlanes defines the frustum planes to test
  19220. * @returns true if there is an inclusion
  19221. */
  19222. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  19223. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  19224. };
  19225. /**
  19226. * Tests if a point is inside the bounding box
  19227. * @param point defines the point to test
  19228. * @returns true if the point is inside the bounding box
  19229. */
  19230. BoundingBox.prototype.intersectsPoint = function (point) {
  19231. var delta = -BABYLON.Epsilon;
  19232. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  19233. return false;
  19234. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  19235. return false;
  19236. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  19237. return false;
  19238. return true;
  19239. };
  19240. /**
  19241. * Tests if the bounding box intersects with a bounding sphere
  19242. * @param sphere defines the sphere to test
  19243. * @returns true if there is an intersection
  19244. */
  19245. BoundingBox.prototype.intersectsSphere = function (sphere) {
  19246. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  19247. };
  19248. /**
  19249. * Tests if the bounding box intersects with a box defined by a min and max vectors
  19250. * @param min defines the min vector to use
  19251. * @param max defines the max vector to use
  19252. * @returns true if there is an intersection
  19253. */
  19254. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  19255. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  19256. return false;
  19257. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  19258. return false;
  19259. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  19260. return false;
  19261. return true;
  19262. };
  19263. // Statics
  19264. /**
  19265. * Tests if two bounding boxes are intersections
  19266. * @param box0 defines the first box to test
  19267. * @param box1 defines the second box to test
  19268. * @returns true if there is an intersection
  19269. */
  19270. BoundingBox.Intersects = function (box0, box1) {
  19271. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  19272. return false;
  19273. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  19274. return false;
  19275. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  19276. return false;
  19277. return true;
  19278. };
  19279. /**
  19280. * Tests if a bounding box defines by a min/max vectors intersects a sphere
  19281. * @param minPoint defines the minimum vector of the bounding box
  19282. * @param maxPoint defines the maximum vector of the bounding box
  19283. * @param sphereCenter defines the sphere center
  19284. * @param sphereRadius defines the sphere radius
  19285. * @returns true if there is an intersection
  19286. */
  19287. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  19288. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  19289. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  19290. return (num <= (sphereRadius * sphereRadius));
  19291. };
  19292. /**
  19293. * Tests if a bounding box defined with 8 vectors is entirely inside frustum planes
  19294. * @param boundingVectors defines an array of 8 vectors representing a bounding box
  19295. * @param frustumPlanes defines the frustum planes to test
  19296. * @return true if there is an inclusion
  19297. */
  19298. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  19299. for (var p = 0; p < 6; p++) {
  19300. for (var i = 0; i < 8; i++) {
  19301. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  19302. return false;
  19303. }
  19304. }
  19305. }
  19306. return true;
  19307. };
  19308. /**
  19309. * Tests if a bounding box defined with 8 vectors intersects frustum planes
  19310. * @param boundingVectors defines an array of 8 vectors representing a bounding box
  19311. * @param frustumPlanes defines the frustum planes to test
  19312. * @return true if there is an intersection
  19313. */
  19314. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  19315. for (var p = 0; p < 6; p++) {
  19316. var inCount = 8;
  19317. for (var i = 0; i < 8; i++) {
  19318. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  19319. --inCount;
  19320. }
  19321. else {
  19322. break;
  19323. }
  19324. }
  19325. if (inCount === 0)
  19326. return false;
  19327. }
  19328. return true;
  19329. };
  19330. return BoundingBox;
  19331. }());
  19332. BABYLON.BoundingBox = BoundingBox;
  19333. })(BABYLON || (BABYLON = {}));
  19334. //# sourceMappingURL=babylon.boundingBox.js.map
  19335. var BABYLON;
  19336. (function (BABYLON) {
  19337. var computeBoxExtents = function (axis, box) {
  19338. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  19339. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  19340. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  19341. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  19342. var r = r0 + r1 + r2;
  19343. return {
  19344. min: p - r,
  19345. max: p + r
  19346. };
  19347. };
  19348. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  19349. var axisOverlap = function (axis, box0, box1) {
  19350. var result0 = computeBoxExtents(axis, box0);
  19351. var result1 = computeBoxExtents(axis, box1);
  19352. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  19353. };
  19354. /**
  19355. * Info for a bounding data of a mesh
  19356. */
  19357. var BoundingInfo = /** @class */ (function () {
  19358. /**
  19359. * Constructs bounding info
  19360. * @param minimum min vector of the bounding box/sphere
  19361. * @param maximum max vector of the bounding box/sphere
  19362. */
  19363. function BoundingInfo(minimum, maximum) {
  19364. this._isLocked = false;
  19365. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  19366. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  19367. }
  19368. Object.defineProperty(BoundingInfo.prototype, "minimum", {
  19369. /**
  19370. * min vector of the bounding box/sphere
  19371. */
  19372. get: function () {
  19373. return this.boundingBox.minimum;
  19374. },
  19375. enumerable: true,
  19376. configurable: true
  19377. });
  19378. Object.defineProperty(BoundingInfo.prototype, "maximum", {
  19379. /**
  19380. * max vector of the bounding box/sphere
  19381. */
  19382. get: function () {
  19383. return this.boundingBox.maximum;
  19384. },
  19385. enumerable: true,
  19386. configurable: true
  19387. });
  19388. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  19389. /**
  19390. * If the info is locked and won't be updated to avoid perf overhead
  19391. */
  19392. get: function () {
  19393. return this._isLocked;
  19394. },
  19395. set: function (value) {
  19396. this._isLocked = value;
  19397. },
  19398. enumerable: true,
  19399. configurable: true
  19400. });
  19401. // Methods
  19402. /**
  19403. * Updates the boudning sphere and box
  19404. * @param world world matrix to be used to update
  19405. */
  19406. BoundingInfo.prototype.update = function (world) {
  19407. if (this._isLocked) {
  19408. return;
  19409. }
  19410. this.boundingBox._update(world);
  19411. this.boundingSphere._update(world);
  19412. };
  19413. /**
  19414. * Recreate the bounding info to be centered around a specific point given a specific extend.
  19415. * @param center New center of the bounding info
  19416. * @param extend New extend of the bounding info
  19417. * @returns the current bounding info
  19418. */
  19419. BoundingInfo.prototype.centerOn = function (center, extend) {
  19420. var minimum = BABYLON.Tmp.Vector3[0].copyFrom(center).subtractInPlace(extend);
  19421. var maximum = BABYLON.Tmp.Vector3[1].copyFrom(center).addInPlace(extend);
  19422. this.boundingBox.reConstruct(minimum, maximum);
  19423. this.boundingSphere.reConstruct(minimum, maximum);
  19424. return this;
  19425. };
  19426. /**
  19427. * Scale the current bounding info by applying a scale factor
  19428. * @param factor defines the scale factor to apply
  19429. * @returns the current bounding info
  19430. */
  19431. BoundingInfo.prototype.scale = function (factor) {
  19432. this.boundingBox.scale(factor);
  19433. this.boundingSphere.scale(factor);
  19434. return this;
  19435. };
  19436. /**
  19437. * Returns `true` if the bounding info is within the frustum defined by the passed array of planes.
  19438. * @param frustumPlanes defines the frustum to test
  19439. * @param strategy defines the strategy to use for the culling (default is BABYLON.Scene.CULLINGSTRATEGY_STANDARD)
  19440. * @returns true if the bounding info is in the frustum planes
  19441. */
  19442. BoundingInfo.prototype.isInFrustum = function (frustumPlanes, strategy) {
  19443. if (strategy === void 0) { strategy = BABYLON.AbstractMesh.CULLINGSTRATEGY_STANDARD; }
  19444. if (!this.boundingSphere.isInFrustum(frustumPlanes)) {
  19445. return false;
  19446. }
  19447. if (strategy === BABYLON.AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY) {
  19448. return true;
  19449. }
  19450. return this.boundingBox.isInFrustum(frustumPlanes);
  19451. };
  19452. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  19453. /**
  19454. * Gets the world distance between the min and max points of the bounding box
  19455. */
  19456. get: function () {
  19457. var boundingBox = this.boundingBox;
  19458. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  19459. return size.length();
  19460. },
  19461. enumerable: true,
  19462. configurable: true
  19463. });
  19464. /**
  19465. * Checks if a cullable object (mesh...) is in the camera frustum
  19466. * Unlike isInFrustum this cheks the full bounding box
  19467. * @param frustumPlanes Camera near/planes
  19468. * @returns true if the object is in frustum otherwise false
  19469. */
  19470. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  19471. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  19472. };
  19473. /** @hidden */
  19474. BoundingInfo.prototype._checkCollision = function (collider) {
  19475. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  19476. };
  19477. /**
  19478. * Checks if a point is inside the bounding box and bounding sphere or the mesh
  19479. * @see https://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  19480. * @param point the point to check intersection with
  19481. * @returns if the point intersects
  19482. */
  19483. BoundingInfo.prototype.intersectsPoint = function (point) {
  19484. if (!this.boundingSphere.centerWorld) {
  19485. return false;
  19486. }
  19487. if (!this.boundingSphere.intersectsPoint(point)) {
  19488. return false;
  19489. }
  19490. if (!this.boundingBox.intersectsPoint(point)) {
  19491. return false;
  19492. }
  19493. return true;
  19494. };
  19495. /**
  19496. * Checks if another bounding info intersects the bounding box and bounding sphere or the mesh
  19497. * @see https://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  19498. * @param boundingInfo the bounding info to check intersection with
  19499. * @param precise if the intersection should be done using OBB
  19500. * @returns if the bounding info intersects
  19501. */
  19502. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  19503. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  19504. return false;
  19505. }
  19506. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  19507. return false;
  19508. }
  19509. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  19510. return false;
  19511. }
  19512. if (!precise) {
  19513. return true;
  19514. }
  19515. var box0 = this.boundingBox;
  19516. var box1 = boundingInfo.boundingBox;
  19517. if (!axisOverlap(box0.directions[0], box0, box1))
  19518. return false;
  19519. if (!axisOverlap(box0.directions[1], box0, box1))
  19520. return false;
  19521. if (!axisOverlap(box0.directions[2], box0, box1))
  19522. return false;
  19523. if (!axisOverlap(box1.directions[0], box0, box1))
  19524. return false;
  19525. if (!axisOverlap(box1.directions[1], box0, box1))
  19526. return false;
  19527. if (!axisOverlap(box1.directions[2], box0, box1))
  19528. return false;
  19529. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  19530. return false;
  19531. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  19532. return false;
  19533. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  19534. return false;
  19535. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  19536. return false;
  19537. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  19538. return false;
  19539. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  19540. return false;
  19541. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  19542. return false;
  19543. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  19544. return false;
  19545. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  19546. return false;
  19547. return true;
  19548. };
  19549. return BoundingInfo;
  19550. }());
  19551. BABYLON.BoundingInfo = BoundingInfo;
  19552. })(BABYLON || (BABYLON = {}));
  19553. //# sourceMappingURL=babylon.boundingInfo.js.map
  19554. var BABYLON;
  19555. (function (BABYLON) {
  19556. /**
  19557. * A TransformNode is an object that is not rendered but can be used as a center of transformation. This can decrease memory usage and increase rendering speed compared to using an empty mesh as a parent and is less complicated than using a pivot matrix.
  19558. * @see https://doc.babylonjs.com/how_to/transformnode
  19559. */
  19560. var TransformNode = /** @class */ (function (_super) {
  19561. __extends(TransformNode, _super);
  19562. function TransformNode(name, scene, isPure) {
  19563. if (scene === void 0) { scene = null; }
  19564. if (isPure === void 0) { isPure = true; }
  19565. var _this = _super.call(this, name, scene) || this;
  19566. _this._forward = new BABYLON.Vector3(0, 0, 1);
  19567. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  19568. _this._up = new BABYLON.Vector3(0, 1, 0);
  19569. _this._right = new BABYLON.Vector3(1, 0, 0);
  19570. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  19571. // Properties
  19572. _this._position = BABYLON.Vector3.Zero();
  19573. _this._rotation = BABYLON.Vector3.Zero();
  19574. _this._scaling = BABYLON.Vector3.One();
  19575. _this._isDirty = false;
  19576. /**
  19577. * Set the billboard mode. Default is 0.
  19578. *
  19579. * | Value | Type | Description |
  19580. * | --- | --- | --- |
  19581. * | 0 | BILLBOARDMODE_NONE | |
  19582. * | 1 | BILLBOARDMODE_X | |
  19583. * | 2 | BILLBOARDMODE_Y | |
  19584. * | 4 | BILLBOARDMODE_Z | |
  19585. * | 7 | BILLBOARDMODE_ALL | |
  19586. *
  19587. */
  19588. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  19589. /**
  19590. * Multiplication factor on scale x/y/z when computing the world matrix. Eg. for a 1x1x1 cube setting this to 2 will make it a 2x2x2 cube
  19591. */
  19592. _this.scalingDeterminant = 1;
  19593. /**
  19594. * Sets the distance of the object to max, often used by skybox
  19595. */
  19596. _this.infiniteDistance = false;
  19597. /**
  19598. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  19599. * By default the system will update normals to compensate
  19600. */
  19601. _this.ignoreNonUniformScaling = false;
  19602. _this._localWorld = BABYLON.Matrix.Zero();
  19603. _this._absolutePosition = BABYLON.Vector3.Zero();
  19604. _this._pivotMatrix = BABYLON.Matrix.Identity();
  19605. _this._postMultiplyPivotMatrix = false;
  19606. _this._isWorldMatrixFrozen = false;
  19607. /**
  19608. * An event triggered after the world matrix is updated
  19609. */
  19610. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  19611. _this._nonUniformScaling = false;
  19612. if (isPure) {
  19613. _this.getScene().addTransformNode(_this);
  19614. }
  19615. return _this;
  19616. }
  19617. /**
  19618. * Gets a string identifying the name of the class
  19619. * @returns "TransformNode" string
  19620. */
  19621. TransformNode.prototype.getClassName = function () {
  19622. return "TransformNode";
  19623. };
  19624. Object.defineProperty(TransformNode.prototype, "position", {
  19625. /**
  19626. * Gets or set the node position (default is (0.0, 0.0, 0.0))
  19627. */
  19628. get: function () {
  19629. return this._position;
  19630. },
  19631. set: function (newPosition) {
  19632. this._position = newPosition;
  19633. this._isDirty = true;
  19634. },
  19635. enumerable: true,
  19636. configurable: true
  19637. });
  19638. Object.defineProperty(TransformNode.prototype, "rotation", {
  19639. /**
  19640. * Gets or sets the rotation property : a Vector3 defining the rotation value in radians around each local axis X, Y, Z (default is (0.0, 0.0, 0.0)).
  19641. * If rotation quaternion is set, this Vector3 will be ignored and copy from the quaternion
  19642. */
  19643. get: function () {
  19644. return this._rotation;
  19645. },
  19646. set: function (newRotation) {
  19647. this._rotation = newRotation;
  19648. this._isDirty = true;
  19649. },
  19650. enumerable: true,
  19651. configurable: true
  19652. });
  19653. Object.defineProperty(TransformNode.prototype, "scaling", {
  19654. /**
  19655. * Gets or sets the scaling property : a Vector3 defining the node scaling along each local axis X, Y, Z (default is (0.0, 0.0, 0.0)).
  19656. */
  19657. get: function () {
  19658. return this._scaling;
  19659. },
  19660. set: function (newScaling) {
  19661. this._scaling = newScaling;
  19662. this._isDirty = true;
  19663. },
  19664. enumerable: true,
  19665. configurable: true
  19666. });
  19667. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  19668. /**
  19669. * Gets or sets the rotation Quaternion property : this a Quaternion object defining the node rotation by using a unit quaternion (null by default).
  19670. * If set, only the rotationQuaternion is then used to compute the node rotation (ie. node.rotation will be ignored)
  19671. */
  19672. get: function () {
  19673. return this._rotationQuaternion;
  19674. },
  19675. set: function (quaternion) {
  19676. this._rotationQuaternion = quaternion;
  19677. //reset the rotation vector.
  19678. if (quaternion && this.rotation.length()) {
  19679. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  19680. }
  19681. },
  19682. enumerable: true,
  19683. configurable: true
  19684. });
  19685. Object.defineProperty(TransformNode.prototype, "forward", {
  19686. /**
  19687. * The forward direction of that transform in world space.
  19688. */
  19689. get: function () {
  19690. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  19691. },
  19692. enumerable: true,
  19693. configurable: true
  19694. });
  19695. Object.defineProperty(TransformNode.prototype, "up", {
  19696. /**
  19697. * The up direction of that transform in world space.
  19698. */
  19699. get: function () {
  19700. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  19701. },
  19702. enumerable: true,
  19703. configurable: true
  19704. });
  19705. Object.defineProperty(TransformNode.prototype, "right", {
  19706. /**
  19707. * The right direction of that transform in world space.
  19708. */
  19709. get: function () {
  19710. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  19711. },
  19712. enumerable: true,
  19713. configurable: true
  19714. });
  19715. /**
  19716. * Copies the parameter passed Matrix into the mesh Pose matrix.
  19717. * @param matrix the matrix to copy the pose from
  19718. * @returns this TransformNode.
  19719. */
  19720. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  19721. this._poseMatrix.copyFrom(matrix);
  19722. return this;
  19723. };
  19724. /**
  19725. * Returns the mesh Pose matrix.
  19726. * @returns the pose matrix
  19727. */
  19728. TransformNode.prototype.getPoseMatrix = function () {
  19729. return this._poseMatrix;
  19730. };
  19731. /** @hidden */
  19732. TransformNode.prototype._isSynchronized = function () {
  19733. if (this._isDirty) {
  19734. return false;
  19735. }
  19736. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  19737. return false;
  19738. if (this._cache.pivotMatrixUpdated) {
  19739. return false;
  19740. }
  19741. if (this.infiniteDistance) {
  19742. return false;
  19743. }
  19744. if (!this._cache.position.equals(this._position))
  19745. return false;
  19746. if (this._rotationQuaternion) {
  19747. if (!this._cache.rotationQuaternion.equals(this._rotationQuaternion))
  19748. return false;
  19749. }
  19750. if (!this._cache.rotation.equals(this._rotation))
  19751. return false;
  19752. if (!this._cache.scaling.equals(this._scaling))
  19753. return false;
  19754. return true;
  19755. };
  19756. /** @hidden */
  19757. TransformNode.prototype._initCache = function () {
  19758. _super.prototype._initCache.call(this);
  19759. this._cache.localMatrixUpdated = false;
  19760. this._cache.position = BABYLON.Vector3.Zero();
  19761. this._cache.scaling = BABYLON.Vector3.Zero();
  19762. this._cache.rotation = BABYLON.Vector3.Zero();
  19763. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  19764. this._cache.billboardMode = -1;
  19765. };
  19766. /**
  19767. * Flag the transform node as dirty (Forcing it to update everything)
  19768. * @param property if set to "rotation" the objects rotationQuaternion will be set to null
  19769. * @returns this transform node
  19770. */
  19771. TransformNode.prototype.markAsDirty = function (property) {
  19772. if (property === "rotation") {
  19773. this.rotationQuaternion = null;
  19774. }
  19775. this._currentRenderId = Number.MAX_VALUE;
  19776. this._isDirty = true;
  19777. return this;
  19778. };
  19779. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  19780. /**
  19781. * Returns the current mesh absolute position.
  19782. * Returns a Vector3.
  19783. */
  19784. get: function () {
  19785. return this._absolutePosition;
  19786. },
  19787. enumerable: true,
  19788. configurable: true
  19789. });
  19790. /**
  19791. * Sets a new matrix to apply before all other transformation
  19792. * @param matrix defines the transform matrix
  19793. * @returns the current TransformNode
  19794. */
  19795. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  19796. return this.setPivotMatrix(matrix, false);
  19797. };
  19798. /**
  19799. * Sets a new pivot matrix to the current node
  19800. * @param matrix defines the new pivot matrix to use
  19801. * @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
  19802. * @returns the current TransformNode
  19803. */
  19804. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  19805. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  19806. this._pivotMatrix = matrix.clone();
  19807. this._cache.pivotMatrixUpdated = true;
  19808. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  19809. if (this._postMultiplyPivotMatrix) {
  19810. if (!this._pivotMatrixInverse) {
  19811. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  19812. }
  19813. else {
  19814. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  19815. }
  19816. }
  19817. return this;
  19818. };
  19819. /**
  19820. * Returns the mesh pivot matrix.
  19821. * Default : Identity.
  19822. * @returns the matrix
  19823. */
  19824. TransformNode.prototype.getPivotMatrix = function () {
  19825. return this._pivotMatrix;
  19826. };
  19827. /**
  19828. * Prevents the World matrix to be computed any longer.
  19829. * @returns the TransformNode.
  19830. */
  19831. TransformNode.prototype.freezeWorldMatrix = function () {
  19832. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  19833. this.computeWorldMatrix(true);
  19834. this._isWorldMatrixFrozen = true;
  19835. return this;
  19836. };
  19837. /**
  19838. * Allows back the World matrix computation.
  19839. * @returns the TransformNode.
  19840. */
  19841. TransformNode.prototype.unfreezeWorldMatrix = function () {
  19842. this._isWorldMatrixFrozen = false;
  19843. this.computeWorldMatrix(true);
  19844. return this;
  19845. };
  19846. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  19847. /**
  19848. * True if the World matrix has been frozen.
  19849. */
  19850. get: function () {
  19851. return this._isWorldMatrixFrozen;
  19852. },
  19853. enumerable: true,
  19854. configurable: true
  19855. });
  19856. /**
  19857. * Retuns the mesh absolute position in the World.
  19858. * @returns a Vector3.
  19859. */
  19860. TransformNode.prototype.getAbsolutePosition = function () {
  19861. this.computeWorldMatrix();
  19862. return this._absolutePosition;
  19863. };
  19864. /**
  19865. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  19866. * @param absolutePosition the absolute position to set
  19867. * @returns the TransformNode.
  19868. */
  19869. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  19870. if (!absolutePosition) {
  19871. return this;
  19872. }
  19873. var absolutePositionX;
  19874. var absolutePositionY;
  19875. var absolutePositionZ;
  19876. if (absolutePosition.x === undefined) {
  19877. if (arguments.length < 3) {
  19878. return this;
  19879. }
  19880. absolutePositionX = arguments[0];
  19881. absolutePositionY = arguments[1];
  19882. absolutePositionZ = arguments[2];
  19883. }
  19884. else {
  19885. absolutePositionX = absolutePosition.x;
  19886. absolutePositionY = absolutePosition.y;
  19887. absolutePositionZ = absolutePosition.z;
  19888. }
  19889. if (this.parent) {
  19890. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  19891. invertParentWorldMatrix.invert();
  19892. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  19893. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  19894. }
  19895. else {
  19896. this.position.x = absolutePositionX;
  19897. this.position.y = absolutePositionY;
  19898. this.position.z = absolutePositionZ;
  19899. }
  19900. return this;
  19901. };
  19902. /**
  19903. * Sets the mesh position in its local space.
  19904. * @param vector3 the position to set in localspace
  19905. * @returns the TransformNode.
  19906. */
  19907. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  19908. this.computeWorldMatrix();
  19909. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  19910. return this;
  19911. };
  19912. /**
  19913. * Returns the mesh position in the local space from the current World matrix values.
  19914. * @returns a new Vector3.
  19915. */
  19916. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  19917. this.computeWorldMatrix();
  19918. var invLocalWorldMatrix = this._localWorld.clone();
  19919. invLocalWorldMatrix.invert();
  19920. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  19921. };
  19922. /**
  19923. * Translates the mesh along the passed Vector3 in its local space.
  19924. * @param vector3 the distance to translate in localspace
  19925. * @returns the TransformNode.
  19926. */
  19927. TransformNode.prototype.locallyTranslate = function (vector3) {
  19928. this.computeWorldMatrix(true);
  19929. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  19930. return this;
  19931. };
  19932. /**
  19933. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  19934. * @param targetPoint the position (must be in same space as current mesh) to look at
  19935. * @param yawCor optional yaw (y-axis) correction in radians
  19936. * @param pitchCor optional pitch (x-axis) correction in radians
  19937. * @param rollCor optional roll (z-axis) correction in radians
  19938. * @param space the choosen space of the target
  19939. * @returns the TransformNode.
  19940. */
  19941. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  19942. if (yawCor === void 0) { yawCor = 0; }
  19943. if (pitchCor === void 0) { pitchCor = 0; }
  19944. if (rollCor === void 0) { rollCor = 0; }
  19945. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  19946. var dv = TransformNode._lookAtVectorCache;
  19947. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  19948. targetPoint.subtractToRef(pos, dv);
  19949. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  19950. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  19951. var pitch = Math.atan2(dv.y, len);
  19952. if (this.rotationQuaternion) {
  19953. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  19954. }
  19955. else {
  19956. this.rotation.x = pitch + pitchCor;
  19957. this.rotation.y = yaw + yawCor;
  19958. this.rotation.z = rollCor;
  19959. }
  19960. return this;
  19961. };
  19962. /**
  19963. * Returns a new Vector3 that is the localAxis, expressed in the mesh local space, rotated like the mesh.
  19964. * This Vector3 is expressed in the World space.
  19965. * @param localAxis axis to rotate
  19966. * @returns a new Vector3 that is the localAxis, expressed in the mesh local space, rotated like the mesh.
  19967. */
  19968. TransformNode.prototype.getDirection = function (localAxis) {
  19969. var result = BABYLON.Vector3.Zero();
  19970. this.getDirectionToRef(localAxis, result);
  19971. return result;
  19972. };
  19973. /**
  19974. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  19975. * localAxis is expressed in the mesh local space.
  19976. * result is computed in the Wordl space from the mesh World matrix.
  19977. * @param localAxis axis to rotate
  19978. * @param result the resulting transformnode
  19979. * @returns this TransformNode.
  19980. */
  19981. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  19982. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  19983. return this;
  19984. };
  19985. /**
  19986. * Sets a new pivot point to the current node
  19987. * @param point defines the new pivot point to use
  19988. * @param space defines if the point is in world or local space (local by default)
  19989. * @returns the current TransformNode
  19990. */
  19991. TransformNode.prototype.setPivotPoint = function (point, space) {
  19992. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  19993. if (this.getScene().getRenderId() == 0) {
  19994. this.computeWorldMatrix(true);
  19995. }
  19996. var wm = this.getWorldMatrix();
  19997. if (space == BABYLON.Space.WORLD) {
  19998. var tmat = BABYLON.Tmp.Matrix[0];
  19999. wm.invertToRef(tmat);
  20000. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  20001. }
  20002. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  20003. };
  20004. /**
  20005. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  20006. * @returns the pivot point
  20007. */
  20008. TransformNode.prototype.getPivotPoint = function () {
  20009. var point = BABYLON.Vector3.Zero();
  20010. this.getPivotPointToRef(point);
  20011. return point;
  20012. };
  20013. /**
  20014. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  20015. * @param result the vector3 to store the result
  20016. * @returns this TransformNode.
  20017. */
  20018. TransformNode.prototype.getPivotPointToRef = function (result) {
  20019. result.x = -this._pivotMatrix.m[12];
  20020. result.y = -this._pivotMatrix.m[13];
  20021. result.z = -this._pivotMatrix.m[14];
  20022. return this;
  20023. };
  20024. /**
  20025. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  20026. * @returns a new Vector3 set with the mesh pivot point World coordinates.
  20027. */
  20028. TransformNode.prototype.getAbsolutePivotPoint = function () {
  20029. var point = BABYLON.Vector3.Zero();
  20030. this.getAbsolutePivotPointToRef(point);
  20031. return point;
  20032. };
  20033. /**
  20034. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  20035. * @param result vector3 to store the result
  20036. * @returns this TransformNode.
  20037. */
  20038. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  20039. result.x = this._pivotMatrix.m[12];
  20040. result.y = this._pivotMatrix.m[13];
  20041. result.z = this._pivotMatrix.m[14];
  20042. this.getPivotPointToRef(result);
  20043. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  20044. return this;
  20045. };
  20046. /**
  20047. * Defines the passed node as the parent of the current node.
  20048. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  20049. * @param node the node ot set as the parent
  20050. * @returns this TransformNode.
  20051. */
  20052. TransformNode.prototype.setParent = function (node) {
  20053. if (!node && !this.parent) {
  20054. return this;
  20055. }
  20056. if (!node) {
  20057. var rotation = BABYLON.Tmp.Quaternion[0];
  20058. var position = BABYLON.Tmp.Vector3[0];
  20059. var scale = BABYLON.Tmp.Vector3[1];
  20060. if (this.parent && this.parent.computeWorldMatrix) {
  20061. this.parent.computeWorldMatrix(true);
  20062. }
  20063. this.computeWorldMatrix(true);
  20064. this.getWorldMatrix().decompose(scale, rotation, position);
  20065. if (this.rotationQuaternion) {
  20066. this.rotationQuaternion.copyFrom(rotation);
  20067. }
  20068. else {
  20069. rotation.toEulerAnglesToRef(this.rotation);
  20070. }
  20071. this.scaling.x = scale.x;
  20072. this.scaling.y = scale.y;
  20073. this.scaling.z = scale.z;
  20074. this.position.x = position.x;
  20075. this.position.y = position.y;
  20076. this.position.z = position.z;
  20077. }
  20078. else {
  20079. var rotation = BABYLON.Tmp.Quaternion[0];
  20080. var position = BABYLON.Tmp.Vector3[0];
  20081. var scale = BABYLON.Tmp.Vector3[1];
  20082. var diffMatrix = BABYLON.Tmp.Matrix[0];
  20083. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  20084. this.computeWorldMatrix(true);
  20085. node.computeWorldMatrix(true);
  20086. node.getWorldMatrix().invertToRef(invParentMatrix);
  20087. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  20088. diffMatrix.decompose(scale, rotation, position);
  20089. if (this.rotationQuaternion) {
  20090. this.rotationQuaternion.copyFrom(rotation);
  20091. }
  20092. else {
  20093. rotation.toEulerAnglesToRef(this.rotation);
  20094. }
  20095. this.position.x = position.x;
  20096. this.position.y = position.y;
  20097. this.position.z = position.z;
  20098. this.scaling.x = scale.x;
  20099. this.scaling.y = scale.y;
  20100. this.scaling.z = scale.z;
  20101. }
  20102. this.parent = node;
  20103. return this;
  20104. };
  20105. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  20106. /**
  20107. * True if the scaling property of this object is non uniform eg. (1,2,1)
  20108. */
  20109. get: function () {
  20110. return this._nonUniformScaling;
  20111. },
  20112. enumerable: true,
  20113. configurable: true
  20114. });
  20115. /** @hidden */
  20116. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  20117. if (this._nonUniformScaling === value) {
  20118. return false;
  20119. }
  20120. this._nonUniformScaling = value;
  20121. return true;
  20122. };
  20123. /**
  20124. * Attach the current TransformNode to another TransformNode associated with a bone
  20125. * @param bone Bone affecting the TransformNode
  20126. * @param affectedTransformNode TransformNode associated with the bone
  20127. * @returns this object
  20128. */
  20129. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  20130. this._transformToBoneReferal = affectedTransformNode;
  20131. this.parent = bone;
  20132. if (bone.getWorldMatrix().determinant() < 0) {
  20133. this.scalingDeterminant *= -1;
  20134. }
  20135. return this;
  20136. };
  20137. /**
  20138. * Detach the transform node if its associated with a bone
  20139. * @returns this object
  20140. */
  20141. TransformNode.prototype.detachFromBone = function () {
  20142. if (!this.parent) {
  20143. return this;
  20144. }
  20145. if (this.parent.getWorldMatrix().determinant() < 0) {
  20146. this.scalingDeterminant *= -1;
  20147. }
  20148. this._transformToBoneReferal = null;
  20149. this.parent = null;
  20150. return this;
  20151. };
  20152. /**
  20153. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  20154. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  20155. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  20156. * The passed axis is also normalized.
  20157. * @param axis the axis to rotate around
  20158. * @param amount the amount to rotate in radians
  20159. * @param space Space to rotate in (Default: local)
  20160. * @returns the TransformNode.
  20161. */
  20162. TransformNode.prototype.rotate = function (axis, amount, space) {
  20163. axis.normalize();
  20164. if (!this.rotationQuaternion) {
  20165. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20166. this.rotation = BABYLON.Vector3.Zero();
  20167. }
  20168. var rotationQuaternion;
  20169. if (!space || space === BABYLON.Space.LOCAL) {
  20170. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  20171. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  20172. }
  20173. else {
  20174. if (this.parent) {
  20175. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  20176. invertParentWorldMatrix.invert();
  20177. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  20178. }
  20179. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  20180. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  20181. }
  20182. return this;
  20183. };
  20184. /**
  20185. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  20186. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  20187. * The passed axis is also normalized. .
  20188. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  20189. * @param point the point to rotate around
  20190. * @param axis the axis to rotate around
  20191. * @param amount the amount to rotate in radians
  20192. * @returns the TransformNode
  20193. */
  20194. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  20195. axis.normalize();
  20196. if (!this.rotationQuaternion) {
  20197. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20198. this.rotation.copyFromFloats(0, 0, 0);
  20199. }
  20200. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  20201. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  20202. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  20203. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  20204. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  20205. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  20206. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  20207. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  20208. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  20209. return this;
  20210. };
  20211. /**
  20212. * Translates the mesh along the axis vector for the passed distance in the given space.
  20213. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  20214. * @param axis the axis to translate in
  20215. * @param distance the distance to translate
  20216. * @param space Space to rotate in (Default: local)
  20217. * @returns the TransformNode.
  20218. */
  20219. TransformNode.prototype.translate = function (axis, distance, space) {
  20220. var displacementVector = axis.scale(distance);
  20221. if (!space || space === BABYLON.Space.LOCAL) {
  20222. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  20223. this.setPositionWithLocalVector(tempV3);
  20224. }
  20225. else {
  20226. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  20227. }
  20228. return this;
  20229. };
  20230. /**
  20231. * Adds a rotation step to the mesh current rotation.
  20232. * x, y, z are Euler angles expressed in radians.
  20233. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  20234. * This means this rotation is made in the mesh local space only.
  20235. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  20236. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  20237. * ```javascript
  20238. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  20239. * ```
  20240. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  20241. * 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.
  20242. * @param x Rotation to add
  20243. * @param y Rotation to add
  20244. * @param z Rotation to add
  20245. * @returns the TransformNode.
  20246. */
  20247. TransformNode.prototype.addRotation = function (x, y, z) {
  20248. var rotationQuaternion;
  20249. if (this.rotationQuaternion) {
  20250. rotationQuaternion = this.rotationQuaternion;
  20251. }
  20252. else {
  20253. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  20254. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  20255. }
  20256. var accumulation = BABYLON.Tmp.Quaternion[0];
  20257. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  20258. rotationQuaternion.multiplyInPlace(accumulation);
  20259. if (!this.rotationQuaternion) {
  20260. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  20261. }
  20262. return this;
  20263. };
  20264. /**
  20265. * Computes the world matrix of the node
  20266. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  20267. * @returns the world matrix
  20268. */
  20269. TransformNode.prototype.computeWorldMatrix = function (force) {
  20270. if (this._isWorldMatrixFrozen) {
  20271. return this._worldMatrix;
  20272. }
  20273. if (!force && this.isSynchronized()) {
  20274. this._currentRenderId = this.getScene().getRenderId();
  20275. return this._worldMatrix;
  20276. }
  20277. this._updateCache();
  20278. this._cache.position.copyFrom(this.position);
  20279. this._cache.scaling.copyFrom(this.scaling);
  20280. this._cache.pivotMatrixUpdated = false;
  20281. this._cache.billboardMode = this.billboardMode;
  20282. this._currentRenderId = this.getScene().getRenderId();
  20283. this._childRenderId = this.getScene().getRenderId();
  20284. this._isDirty = false;
  20285. // Scaling
  20286. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  20287. // Rotation
  20288. //rotate, if quaternion is set and rotation was used
  20289. if (this.rotationQuaternion) {
  20290. var len = this.rotation.length();
  20291. if (len) {
  20292. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  20293. this.rotation.copyFromFloats(0, 0, 0);
  20294. }
  20295. }
  20296. if (this.rotationQuaternion) {
  20297. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  20298. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  20299. }
  20300. else {
  20301. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  20302. this._cache.rotation.copyFrom(this.rotation);
  20303. }
  20304. // Translation
  20305. var camera = this.getScene().activeCamera;
  20306. if (this.infiniteDistance && !this.parent && camera) {
  20307. var cameraWorldMatrix = camera.getWorldMatrix();
  20308. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  20309. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  20310. }
  20311. else {
  20312. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  20313. }
  20314. // Composing transformations
  20315. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  20316. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  20317. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  20318. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  20319. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  20320. // Need to decompose each rotation here
  20321. var currentPosition = BABYLON.Tmp.Vector3[3];
  20322. if (this.parent && this.parent.getWorldMatrix) {
  20323. if (this._transformToBoneReferal) {
  20324. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  20325. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  20326. }
  20327. else {
  20328. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  20329. }
  20330. }
  20331. else {
  20332. currentPosition.copyFrom(this.position);
  20333. }
  20334. currentPosition.subtractInPlace(camera.globalPosition);
  20335. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  20336. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  20337. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  20338. }
  20339. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  20340. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  20341. }
  20342. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  20343. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  20344. }
  20345. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  20346. }
  20347. else {
  20348. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  20349. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  20350. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  20351. }
  20352. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  20353. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  20354. }
  20355. // Post multiply inverse of pivotMatrix
  20356. if (this._postMultiplyPivotMatrix) {
  20357. BABYLON.Tmp.Matrix[5].multiplyToRef(this._pivotMatrixInverse, BABYLON.Tmp.Matrix[5]);
  20358. }
  20359. // Local world
  20360. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  20361. // Parent
  20362. if (this.parent && this.parent.getWorldMatrix) {
  20363. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  20364. if (this._transformToBoneReferal) {
  20365. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  20366. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  20367. }
  20368. else {
  20369. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  20370. }
  20371. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  20372. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  20373. this._worldMatrix.copyFrom(this._localWorld);
  20374. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  20375. }
  20376. else {
  20377. if (this._transformToBoneReferal) {
  20378. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  20379. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  20380. }
  20381. else {
  20382. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  20383. }
  20384. }
  20385. this._markSyncedWithParent();
  20386. }
  20387. else {
  20388. this._worldMatrix.copyFrom(this._localWorld);
  20389. }
  20390. // Normal matrix
  20391. if (!this.ignoreNonUniformScaling) {
  20392. if (this.scaling.isNonUniform) {
  20393. this._updateNonUniformScalingState(true);
  20394. }
  20395. else if (this.parent && this.parent._nonUniformScaling) {
  20396. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  20397. }
  20398. else {
  20399. this._updateNonUniformScalingState(false);
  20400. }
  20401. }
  20402. else {
  20403. this._updateNonUniformScalingState(false);
  20404. }
  20405. this._afterComputeWorldMatrix();
  20406. // Absolute position
  20407. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  20408. // Callbacks
  20409. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  20410. if (!this._poseMatrix) {
  20411. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  20412. }
  20413. // Cache the determinant
  20414. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  20415. return this._worldMatrix;
  20416. };
  20417. TransformNode.prototype._afterComputeWorldMatrix = function () {
  20418. };
  20419. /**
  20420. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  20421. * @param func callback function to add
  20422. *
  20423. * @returns the TransformNode.
  20424. */
  20425. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  20426. this.onAfterWorldMatrixUpdateObservable.add(func);
  20427. return this;
  20428. };
  20429. /**
  20430. * Removes a registered callback function.
  20431. * @param func callback function to remove
  20432. * @returns the TransformNode.
  20433. */
  20434. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  20435. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  20436. return this;
  20437. };
  20438. /**
  20439. * Clone the current transform node
  20440. * @param name Name of the new clone
  20441. * @param newParent New parent for the clone
  20442. * @param doNotCloneChildren Do not clone children hierarchy
  20443. * @returns the new transform node
  20444. */
  20445. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20446. var _this = this;
  20447. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  20448. result.name = name;
  20449. result.id = name;
  20450. if (newParent) {
  20451. result.parent = newParent;
  20452. }
  20453. if (!doNotCloneChildren) {
  20454. // Children
  20455. var directDescendants = this.getDescendants(true);
  20456. for (var index = 0; index < directDescendants.length; index++) {
  20457. var child = directDescendants[index];
  20458. if (child.clone) {
  20459. child.clone(name + "." + child.name, result);
  20460. }
  20461. }
  20462. }
  20463. return result;
  20464. };
  20465. /**
  20466. * Serializes the objects information.
  20467. * @param currentSerializationObject defines the object to serialize in
  20468. * @returns the serialized object
  20469. */
  20470. TransformNode.prototype.serialize = function (currentSerializationObject) {
  20471. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  20472. serializationObject.type = this.getClassName();
  20473. // Parent
  20474. if (this.parent) {
  20475. serializationObject.parentId = this.parent.id;
  20476. }
  20477. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  20478. serializationObject.tags = BABYLON.Tags.GetTags(this);
  20479. }
  20480. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  20481. serializationObject.isEnabled = this.isEnabled();
  20482. // Parent
  20483. if (this.parent) {
  20484. serializationObject.parentId = this.parent.id;
  20485. }
  20486. return serializationObject;
  20487. };
  20488. // Statics
  20489. /**
  20490. * Returns a new TransformNode object parsed from the source provided.
  20491. * @param parsedTransformNode is the source.
  20492. * @param scene the scne the object belongs to
  20493. * @param rootUrl is a string, it's the root URL to prefix the `delayLoadingFile` property with
  20494. * @returns a new TransformNode object parsed from the source provided.
  20495. */
  20496. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  20497. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  20498. if (BABYLON.Tags) {
  20499. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  20500. }
  20501. if (parsedTransformNode.localMatrix) {
  20502. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  20503. }
  20504. else if (parsedTransformNode.pivotMatrix) {
  20505. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  20506. }
  20507. transformNode.setEnabled(parsedTransformNode.isEnabled);
  20508. // Parent
  20509. if (parsedTransformNode.parentId) {
  20510. transformNode._waitingParentId = parsedTransformNode.parentId;
  20511. }
  20512. return transformNode;
  20513. };
  20514. /**
  20515. * Releases resources associated with this transform node.
  20516. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20517. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20518. */
  20519. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20520. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20521. // Animations
  20522. this.getScene().stopAnimation(this);
  20523. // Remove from scene
  20524. this.getScene().removeTransformNode(this);
  20525. this.onAfterWorldMatrixUpdateObservable.clear();
  20526. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20527. };
  20528. // Statics
  20529. /**
  20530. * Object will not rotate to face the camera
  20531. */
  20532. TransformNode.BILLBOARDMODE_NONE = 0;
  20533. /**
  20534. * Object will rotate to face the camera but only on the x axis
  20535. */
  20536. TransformNode.BILLBOARDMODE_X = 1;
  20537. /**
  20538. * Object will rotate to face the camera but only on the y axis
  20539. */
  20540. TransformNode.BILLBOARDMODE_Y = 2;
  20541. /**
  20542. * Object will rotate to face the camera but only on the z axis
  20543. */
  20544. TransformNode.BILLBOARDMODE_Z = 4;
  20545. /**
  20546. * Object will rotate to face the camera
  20547. */
  20548. TransformNode.BILLBOARDMODE_ALL = 7;
  20549. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  20550. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  20551. __decorate([
  20552. BABYLON.serializeAsVector3("position")
  20553. ], TransformNode.prototype, "_position", void 0);
  20554. __decorate([
  20555. BABYLON.serializeAsVector3("rotation")
  20556. ], TransformNode.prototype, "_rotation", void 0);
  20557. __decorate([
  20558. BABYLON.serializeAsQuaternion("rotationQuaternion")
  20559. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  20560. __decorate([
  20561. BABYLON.serializeAsVector3("scaling")
  20562. ], TransformNode.prototype, "_scaling", void 0);
  20563. __decorate([
  20564. BABYLON.serialize()
  20565. ], TransformNode.prototype, "billboardMode", void 0);
  20566. __decorate([
  20567. BABYLON.serialize()
  20568. ], TransformNode.prototype, "scalingDeterminant", void 0);
  20569. __decorate([
  20570. BABYLON.serialize()
  20571. ], TransformNode.prototype, "infiniteDistance", void 0);
  20572. __decorate([
  20573. BABYLON.serialize()
  20574. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  20575. return TransformNode;
  20576. }(BABYLON.Node));
  20577. BABYLON.TransformNode = TransformNode;
  20578. })(BABYLON || (BABYLON = {}));
  20579. //# sourceMappingURL=babylon.transformNode.js.map
  20580. var BABYLON;
  20581. (function (BABYLON) {
  20582. /** @hidden */
  20583. var _FacetDataStorage = /** @class */ (function () {
  20584. function _FacetDataStorage() {
  20585. this.facetNb = 0; // facet number
  20586. this.partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  20587. this.partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  20588. this.facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  20589. this.facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  20590. this.bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  20591. this.subDiv = {
  20592. max: 1,
  20593. X: 1,
  20594. Y: 1,
  20595. Z: 1
  20596. };
  20597. this.facetDepthSort = false; // is the facet depth sort to be computed
  20598. this.facetDepthSortEnabled = false; // is the facet depth sort initialized
  20599. }
  20600. return _FacetDataStorage;
  20601. }());
  20602. /**
  20603. * Class used to store all common mesh properties
  20604. */
  20605. var AbstractMesh = /** @class */ (function (_super) {
  20606. __extends(AbstractMesh, _super);
  20607. // Constructor
  20608. /**
  20609. * Creates a new AbstractMesh
  20610. * @param name defines the name of the mesh
  20611. * @param scene defines the hosting scene
  20612. */
  20613. function AbstractMesh(name, scene) {
  20614. if (scene === void 0) { scene = null; }
  20615. var _this = _super.call(this, name, scene, false) || this;
  20616. _this._facetData = new _FacetDataStorage();
  20617. /** Gets ot sets the culling strategy to use to find visible meshes */
  20618. _this.cullingStrategy = AbstractMesh.CULLINGSTRATEGY_STANDARD;
  20619. // Events
  20620. /**
  20621. * An event triggered when this mesh collides with another one
  20622. */
  20623. _this.onCollideObservable = new BABYLON.Observable();
  20624. /**
  20625. * An event triggered when the collision's position changes
  20626. */
  20627. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  20628. /**
  20629. * An event triggered when material is changed
  20630. */
  20631. _this.onMaterialChangedObservable = new BABYLON.Observable();
  20632. // Properties
  20633. /**
  20634. * Gets or sets the orientation for POV movement & rotation
  20635. */
  20636. _this.definedFacingForward = true;
  20637. _this._visibility = 1.0;
  20638. /** Gets or sets the alpha index used to sort transparent meshes
  20639. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  20640. */
  20641. _this.alphaIndex = Number.MAX_VALUE;
  20642. /**
  20643. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  20644. */
  20645. _this.isVisible = true;
  20646. /**
  20647. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  20648. */
  20649. _this.isPickable = true;
  20650. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  20651. _this.showSubMeshesBoundingBox = false;
  20652. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  20653. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  20654. */
  20655. _this.isBlocker = false;
  20656. /**
  20657. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  20658. */
  20659. _this.enablePointerMoveEvents = false;
  20660. /**
  20661. * Specifies the rendering group id for this mesh (0 by default)
  20662. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  20663. */
  20664. _this.renderingGroupId = 0;
  20665. _this._receiveShadows = false;
  20666. /** Defines color to use when rendering outline */
  20667. _this.outlineColor = BABYLON.Color3.Red();
  20668. /** Define width to use when rendering outline */
  20669. _this.outlineWidth = 0.02;
  20670. /** Defines color to use when rendering overlay */
  20671. _this.overlayColor = BABYLON.Color3.Red();
  20672. /** Defines alpha to use when rendering overlay */
  20673. _this.overlayAlpha = 0.5;
  20674. _this._hasVertexAlpha = false;
  20675. _this._useVertexColors = true;
  20676. _this._computeBonesUsingShaders = true;
  20677. _this._numBoneInfluencers = 4;
  20678. _this._applyFog = true;
  20679. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  20680. _this.useOctreeForRenderingSelection = true;
  20681. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  20682. _this.useOctreeForPicking = true;
  20683. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  20684. _this.useOctreeForCollisions = true;
  20685. _this._layerMask = 0x0FFFFFFF;
  20686. /**
  20687. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  20688. */
  20689. _this.alwaysSelectAsActiveMesh = false;
  20690. /**
  20691. * Gets or sets the current action manager
  20692. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  20693. */
  20694. _this.actionManager = null;
  20695. // Collisions
  20696. _this._checkCollisions = false;
  20697. _this._collisionMask = -1;
  20698. _this._collisionGroup = -1;
  20699. /**
  20700. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  20701. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20702. */
  20703. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  20704. /**
  20705. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  20706. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20707. */
  20708. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  20709. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  20710. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  20711. // Edges
  20712. /**
  20713. * Defines edge width used when edgesRenderer is enabled
  20714. * @see https://www.babylonjs-playground.com/#10OJSG#13
  20715. */
  20716. _this.edgesWidth = 1;
  20717. /**
  20718. * Defines edge color used when edgesRenderer is enabled
  20719. * @see https://www.babylonjs-playground.com/#10OJSG#13
  20720. */
  20721. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  20722. /** @hidden */
  20723. _this._renderId = 0;
  20724. /** @hidden */
  20725. _this._intersectionsInProgress = new Array();
  20726. /** @hidden */
  20727. _this._unIndexed = false;
  20728. /** @hidden */
  20729. _this._lightSources = new Array();
  20730. /**
  20731. * An event triggered when the mesh is rebuilt.
  20732. */
  20733. _this.onRebuildObservable = new BABYLON.Observable();
  20734. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  20735. if (collidedMesh === void 0) { collidedMesh = null; }
  20736. //TODO move this to the collision coordinator!
  20737. if (_this.getScene().workerCollisions)
  20738. newPosition.multiplyInPlace(_this._collider._radius);
  20739. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  20740. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  20741. _this.position.addInPlace(_this._diffPositionForCollisions);
  20742. }
  20743. if (collidedMesh) {
  20744. _this.onCollideObservable.notifyObservers(collidedMesh);
  20745. }
  20746. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  20747. };
  20748. _this.getScene().addMesh(_this);
  20749. _this._resyncLightSources();
  20750. return _this;
  20751. }
  20752. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  20753. /**
  20754. * No billboard
  20755. */
  20756. get: function () {
  20757. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  20758. },
  20759. enumerable: true,
  20760. configurable: true
  20761. });
  20762. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  20763. /** Billboard on X axis */
  20764. get: function () {
  20765. return BABYLON.TransformNode.BILLBOARDMODE_X;
  20766. },
  20767. enumerable: true,
  20768. configurable: true
  20769. });
  20770. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  20771. /** Billboard on Y axis */
  20772. get: function () {
  20773. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  20774. },
  20775. enumerable: true,
  20776. configurable: true
  20777. });
  20778. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  20779. /** Billboard on Z axis */
  20780. get: function () {
  20781. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  20782. },
  20783. enumerable: true,
  20784. configurable: true
  20785. });
  20786. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  20787. /** Billboard on all axes */
  20788. get: function () {
  20789. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  20790. },
  20791. enumerable: true,
  20792. configurable: true
  20793. });
  20794. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  20795. /**
  20796. * Gets the number of facets in the mesh
  20797. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  20798. */
  20799. get: function () {
  20800. return this._facetData.facetNb;
  20801. },
  20802. enumerable: true,
  20803. configurable: true
  20804. });
  20805. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  20806. /**
  20807. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  20808. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  20809. */
  20810. get: function () {
  20811. return this._facetData.partitioningSubdivisions;
  20812. },
  20813. set: function (nb) {
  20814. this._facetData.partitioningSubdivisions = nb;
  20815. },
  20816. enumerable: true,
  20817. configurable: true
  20818. });
  20819. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  20820. /**
  20821. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  20822. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  20823. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  20824. */
  20825. get: function () {
  20826. return this._facetData.partitioningBBoxRatio;
  20827. },
  20828. set: function (ratio) {
  20829. this._facetData.partitioningBBoxRatio = ratio;
  20830. },
  20831. enumerable: true,
  20832. configurable: true
  20833. });
  20834. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  20835. /**
  20836. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  20837. * Works only for updatable meshes.
  20838. * Doesn't work with multi-materials
  20839. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  20840. */
  20841. get: function () {
  20842. return this._facetData.facetDepthSort;
  20843. },
  20844. set: function (sort) {
  20845. this._facetData.facetDepthSort = sort;
  20846. },
  20847. enumerable: true,
  20848. configurable: true
  20849. });
  20850. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  20851. /**
  20852. * The location (Vector3) where the facet depth sort must be computed from.
  20853. * By default, the active camera position.
  20854. * Used only when facet depth sort is enabled
  20855. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  20856. */
  20857. get: function () {
  20858. return this._facetData.facetDepthSortFrom;
  20859. },
  20860. set: function (location) {
  20861. this._facetData.facetDepthSortFrom = location;
  20862. },
  20863. enumerable: true,
  20864. configurable: true
  20865. });
  20866. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  20867. /**
  20868. * gets a boolean indicating if facetData is enabled
  20869. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  20870. */
  20871. get: function () {
  20872. return this._facetData.facetDataEnabled;
  20873. },
  20874. enumerable: true,
  20875. configurable: true
  20876. });
  20877. /** @hidden */
  20878. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  20879. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  20880. return false;
  20881. }
  20882. this._markSubMeshesAsMiscDirty();
  20883. return true;
  20884. };
  20885. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  20886. /** Set a function to call when this mesh collides with another one */
  20887. set: function (callback) {
  20888. if (this._onCollideObserver) {
  20889. this.onCollideObservable.remove(this._onCollideObserver);
  20890. }
  20891. this._onCollideObserver = this.onCollideObservable.add(callback);
  20892. },
  20893. enumerable: true,
  20894. configurable: true
  20895. });
  20896. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  20897. /** Set a function to call when the collision's position changes */
  20898. set: function (callback) {
  20899. if (this._onCollisionPositionChangeObserver) {
  20900. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  20901. }
  20902. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  20903. },
  20904. enumerable: true,
  20905. configurable: true
  20906. });
  20907. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  20908. /**
  20909. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  20910. */
  20911. get: function () {
  20912. return this._visibility;
  20913. },
  20914. /**
  20915. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  20916. */
  20917. set: function (value) {
  20918. if (this._visibility === value) {
  20919. return;
  20920. }
  20921. this._visibility = value;
  20922. this._markSubMeshesAsMiscDirty();
  20923. },
  20924. enumerable: true,
  20925. configurable: true
  20926. });
  20927. Object.defineProperty(AbstractMesh.prototype, "material", {
  20928. /** Gets or sets current material */
  20929. get: function () {
  20930. return this._material;
  20931. },
  20932. set: function (value) {
  20933. if (this._material === value) {
  20934. return;
  20935. }
  20936. this._material = value;
  20937. if (this.onMaterialChangedObservable.hasObservers) {
  20938. this.onMaterialChangedObservable.notifyObservers(this);
  20939. }
  20940. if (!this.subMeshes) {
  20941. return;
  20942. }
  20943. this._unBindEffect();
  20944. },
  20945. enumerable: true,
  20946. configurable: true
  20947. });
  20948. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  20949. /**
  20950. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  20951. * @see http://doc.babylonjs.com/babylon101/shadows
  20952. */
  20953. get: function () {
  20954. return this._receiveShadows;
  20955. },
  20956. set: function (value) {
  20957. if (this._receiveShadows === value) {
  20958. return;
  20959. }
  20960. this._receiveShadows = value;
  20961. this._markSubMeshesAsLightDirty();
  20962. },
  20963. enumerable: true,
  20964. configurable: true
  20965. });
  20966. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  20967. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  20968. get: function () {
  20969. return this._hasVertexAlpha;
  20970. },
  20971. set: function (value) {
  20972. if (this._hasVertexAlpha === value) {
  20973. return;
  20974. }
  20975. this._hasVertexAlpha = value;
  20976. this._markSubMeshesAsAttributesDirty();
  20977. this._markSubMeshesAsMiscDirty();
  20978. },
  20979. enumerable: true,
  20980. configurable: true
  20981. });
  20982. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  20983. /** 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) */
  20984. get: function () {
  20985. return this._useVertexColors;
  20986. },
  20987. set: function (value) {
  20988. if (this._useVertexColors === value) {
  20989. return;
  20990. }
  20991. this._useVertexColors = value;
  20992. this._markSubMeshesAsAttributesDirty();
  20993. },
  20994. enumerable: true,
  20995. configurable: true
  20996. });
  20997. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  20998. /**
  20999. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  21000. */
  21001. get: function () {
  21002. return this._computeBonesUsingShaders;
  21003. },
  21004. set: function (value) {
  21005. if (this._computeBonesUsingShaders === value) {
  21006. return;
  21007. }
  21008. this._computeBonesUsingShaders = value;
  21009. this._markSubMeshesAsAttributesDirty();
  21010. },
  21011. enumerable: true,
  21012. configurable: true
  21013. });
  21014. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  21015. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  21016. get: function () {
  21017. return this._numBoneInfluencers;
  21018. },
  21019. set: function (value) {
  21020. if (this._numBoneInfluencers === value) {
  21021. return;
  21022. }
  21023. this._numBoneInfluencers = value;
  21024. this._markSubMeshesAsAttributesDirty();
  21025. },
  21026. enumerable: true,
  21027. configurable: true
  21028. });
  21029. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  21030. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  21031. get: function () {
  21032. return this._applyFog;
  21033. },
  21034. set: function (value) {
  21035. if (this._applyFog === value) {
  21036. return;
  21037. }
  21038. this._applyFog = value;
  21039. this._markSubMeshesAsMiscDirty();
  21040. },
  21041. enumerable: true,
  21042. configurable: true
  21043. });
  21044. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  21045. /**
  21046. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  21047. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  21048. */
  21049. get: function () {
  21050. return this._layerMask;
  21051. },
  21052. set: function (value) {
  21053. if (value === this._layerMask) {
  21054. return;
  21055. }
  21056. this._layerMask = value;
  21057. this._resyncLightSources();
  21058. },
  21059. enumerable: true,
  21060. configurable: true
  21061. });
  21062. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  21063. /**
  21064. * Gets or sets a collision mask used to mask collisions (default is -1).
  21065. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  21066. */
  21067. get: function () {
  21068. return this._collisionMask;
  21069. },
  21070. set: function (mask) {
  21071. this._collisionMask = !isNaN(mask) ? mask : -1;
  21072. },
  21073. enumerable: true,
  21074. configurable: true
  21075. });
  21076. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  21077. /**
  21078. * Gets or sets the current collision group mask (-1 by default).
  21079. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  21080. */
  21081. get: function () {
  21082. return this._collisionGroup;
  21083. },
  21084. set: function (mask) {
  21085. this._collisionGroup = !isNaN(mask) ? mask : -1;
  21086. },
  21087. enumerable: true,
  21088. configurable: true
  21089. });
  21090. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  21091. /** @hidden */
  21092. get: function () {
  21093. return null;
  21094. },
  21095. enumerable: true,
  21096. configurable: true
  21097. });
  21098. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  21099. get: function () {
  21100. return this._skeleton;
  21101. },
  21102. /**
  21103. * Gets or sets a skeleton to apply skining transformations
  21104. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  21105. */
  21106. set: function (value) {
  21107. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  21108. this._skeleton._unregisterMeshWithPoseMatrix(this);
  21109. }
  21110. if (value && value.needInitialSkinMatrix) {
  21111. value._registerMeshWithPoseMatrix(this);
  21112. }
  21113. this._skeleton = value;
  21114. if (!this._skeleton) {
  21115. this._bonesTransformMatrices = null;
  21116. }
  21117. this._markSubMeshesAsAttributesDirty();
  21118. },
  21119. enumerable: true,
  21120. configurable: true
  21121. });
  21122. /**
  21123. * Returns the string "AbstractMesh"
  21124. * @returns "AbstractMesh"
  21125. */
  21126. AbstractMesh.prototype.getClassName = function () {
  21127. return "AbstractMesh";
  21128. };
  21129. /**
  21130. * Gets a string representation of the current mesh
  21131. * @param fullDetails defines a boolean indicating if full details must be included
  21132. * @returns a string representation of the current mesh
  21133. */
  21134. AbstractMesh.prototype.toString = function (fullDetails) {
  21135. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  21136. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  21137. if (this._skeleton) {
  21138. ret += ", skeleton: " + this._skeleton.name;
  21139. }
  21140. if (fullDetails) {
  21141. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  21142. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  21143. }
  21144. return ret;
  21145. };
  21146. /** @hidden */
  21147. AbstractMesh.prototype._rebuild = function () {
  21148. this.onRebuildObservable.notifyObservers(this);
  21149. if (this._occlusionQuery) {
  21150. this._occlusionQuery = null;
  21151. }
  21152. if (!this.subMeshes) {
  21153. return;
  21154. }
  21155. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  21156. var subMesh = _a[_i];
  21157. subMesh._rebuild();
  21158. }
  21159. };
  21160. /** @hidden */
  21161. AbstractMesh.prototype._resyncLightSources = function () {
  21162. this._lightSources.length = 0;
  21163. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  21164. var light = _a[_i];
  21165. if (!light.isEnabled()) {
  21166. continue;
  21167. }
  21168. if (light.canAffectMesh(this)) {
  21169. this._lightSources.push(light);
  21170. }
  21171. }
  21172. this._markSubMeshesAsLightDirty();
  21173. };
  21174. /** @hidden */
  21175. AbstractMesh.prototype._resyncLighSource = function (light) {
  21176. var isIn = light.isEnabled() && light.canAffectMesh(this);
  21177. var index = this._lightSources.indexOf(light);
  21178. if (index === -1) {
  21179. if (!isIn) {
  21180. return;
  21181. }
  21182. this._lightSources.push(light);
  21183. }
  21184. else {
  21185. if (isIn) {
  21186. return;
  21187. }
  21188. this._lightSources.splice(index, 1);
  21189. }
  21190. this._markSubMeshesAsLightDirty();
  21191. };
  21192. /** @hidden */
  21193. AbstractMesh.prototype._unBindEffect = function () {
  21194. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  21195. var subMesh = _a[_i];
  21196. subMesh.setEffect(null);
  21197. }
  21198. };
  21199. /** @hidden */
  21200. AbstractMesh.prototype._removeLightSource = function (light) {
  21201. var index = this._lightSources.indexOf(light);
  21202. if (index === -1) {
  21203. return;
  21204. }
  21205. this._lightSources.splice(index, 1);
  21206. this._markSubMeshesAsLightDirty();
  21207. };
  21208. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  21209. if (!this.subMeshes) {
  21210. return;
  21211. }
  21212. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  21213. var subMesh = _a[_i];
  21214. if (subMesh._materialDefines) {
  21215. func(subMesh._materialDefines);
  21216. }
  21217. }
  21218. };
  21219. /** @hidden */
  21220. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  21221. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  21222. };
  21223. /** @hidden */
  21224. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  21225. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  21226. };
  21227. /** @hidden */
  21228. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  21229. if (!this.subMeshes) {
  21230. return;
  21231. }
  21232. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  21233. var subMesh = _a[_i];
  21234. var material = subMesh.getMaterial();
  21235. if (material) {
  21236. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  21237. }
  21238. }
  21239. };
  21240. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  21241. /**
  21242. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  21243. */
  21244. get: function () {
  21245. return this._scaling;
  21246. },
  21247. set: function (newScaling) {
  21248. this._scaling = newScaling;
  21249. if (this.physicsImpostor) {
  21250. this.physicsImpostor.forceUpdate();
  21251. }
  21252. },
  21253. enumerable: true,
  21254. configurable: true
  21255. });
  21256. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  21257. // Methods
  21258. /**
  21259. * Returns true if the mesh is blocked. Implemented by child classes
  21260. */
  21261. get: function () {
  21262. return false;
  21263. },
  21264. enumerable: true,
  21265. configurable: true
  21266. });
  21267. /**
  21268. * Returns the mesh itself by default. Implemented by child classes
  21269. * @param camera defines the camera to use to pick the right LOD level
  21270. * @returns the currentAbstractMesh
  21271. */
  21272. AbstractMesh.prototype.getLOD = function (camera) {
  21273. return this;
  21274. };
  21275. /**
  21276. * Returns 0 by default. Implemented by child classes
  21277. * @returns an integer
  21278. */
  21279. AbstractMesh.prototype.getTotalVertices = function () {
  21280. return 0;
  21281. };
  21282. /**
  21283. * Returns null by default. Implemented by child classes
  21284. * @returns null
  21285. */
  21286. AbstractMesh.prototype.getIndices = function () {
  21287. return null;
  21288. };
  21289. /**
  21290. * Returns the array of the requested vertex data kind. Implemented by child classes
  21291. * @param kind defines the vertex data kind to use
  21292. * @returns null
  21293. */
  21294. AbstractMesh.prototype.getVerticesData = function (kind) {
  21295. return null;
  21296. };
  21297. /**
  21298. * Sets the vertex data of the mesh geometry for the requested `kind`.
  21299. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  21300. * Note that a new underlying VertexBuffer object is created each call.
  21301. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  21302. * @param kind defines vertex data kind:
  21303. * * BABYLON.VertexBuffer.PositionKind
  21304. * * BABYLON.VertexBuffer.UVKind
  21305. * * BABYLON.VertexBuffer.UV2Kind
  21306. * * BABYLON.VertexBuffer.UV3Kind
  21307. * * BABYLON.VertexBuffer.UV4Kind
  21308. * * BABYLON.VertexBuffer.UV5Kind
  21309. * * BABYLON.VertexBuffer.UV6Kind
  21310. * * BABYLON.VertexBuffer.ColorKind
  21311. * * BABYLON.VertexBuffer.MatricesIndicesKind
  21312. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21313. * * BABYLON.VertexBuffer.MatricesWeightsKind
  21314. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21315. * @param data defines the data source
  21316. * @param updatable defines if the data must be flagged as updatable (or static)
  21317. * @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
  21318. * @returns the current mesh
  21319. */
  21320. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  21321. return this;
  21322. };
  21323. /**
  21324. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  21325. * If the mesh has no geometry, it is simply returned as it is.
  21326. * @param kind defines vertex data kind:
  21327. * * BABYLON.VertexBuffer.PositionKind
  21328. * * BABYLON.VertexBuffer.UVKind
  21329. * * BABYLON.VertexBuffer.UV2Kind
  21330. * * BABYLON.VertexBuffer.UV3Kind
  21331. * * BABYLON.VertexBuffer.UV4Kind
  21332. * * BABYLON.VertexBuffer.UV5Kind
  21333. * * BABYLON.VertexBuffer.UV6Kind
  21334. * * BABYLON.VertexBuffer.ColorKind
  21335. * * BABYLON.VertexBuffer.MatricesIndicesKind
  21336. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21337. * * BABYLON.VertexBuffer.MatricesWeightsKind
  21338. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21339. * @param data defines the data source
  21340. * @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
  21341. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  21342. * @returns the current mesh
  21343. */
  21344. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  21345. return this;
  21346. };
  21347. /**
  21348. * Sets the mesh indices,
  21349. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  21350. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  21351. * @param totalVertices Defines the total number of vertices
  21352. * @returns the current mesh
  21353. */
  21354. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  21355. return this;
  21356. };
  21357. /**
  21358. * Gets a boolean indicating if specific vertex data is present
  21359. * @param kind defines the vertex data kind to use
  21360. * @returns true is data kind is present
  21361. */
  21362. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  21363. return false;
  21364. };
  21365. /**
  21366. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  21367. * @returns a BoundingInfo
  21368. */
  21369. AbstractMesh.prototype.getBoundingInfo = function () {
  21370. if (this._masterMesh) {
  21371. return this._masterMesh.getBoundingInfo();
  21372. }
  21373. if (!this._boundingInfo) {
  21374. // this._boundingInfo is being created here
  21375. this._updateBoundingInfo();
  21376. }
  21377. // cannot be null.
  21378. return this._boundingInfo;
  21379. };
  21380. /**
  21381. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  21382. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  21383. * @returns the current mesh
  21384. */
  21385. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  21386. if (includeDescendants === void 0) { includeDescendants = true; }
  21387. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  21388. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  21389. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  21390. if (maxDimension === 0) {
  21391. return this;
  21392. }
  21393. var scale = 1 / maxDimension;
  21394. this.scaling.scaleInPlace(scale);
  21395. return this;
  21396. };
  21397. /**
  21398. * Overwrite the current bounding info
  21399. * @param boundingInfo defines the new bounding info
  21400. * @returns the current mesh
  21401. */
  21402. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  21403. this._boundingInfo = boundingInfo;
  21404. return this;
  21405. };
  21406. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  21407. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  21408. get: function () {
  21409. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  21410. },
  21411. enumerable: true,
  21412. configurable: true
  21413. });
  21414. /** @hidden */
  21415. AbstractMesh.prototype._preActivate = function () {
  21416. };
  21417. /** @hidden */
  21418. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  21419. };
  21420. /** @hidden */
  21421. AbstractMesh.prototype._activate = function (renderId) {
  21422. this._renderId = renderId;
  21423. };
  21424. /**
  21425. * Gets the current world matrix
  21426. * @returns a Matrix
  21427. */
  21428. AbstractMesh.prototype.getWorldMatrix = function () {
  21429. if (this._masterMesh) {
  21430. return this._masterMesh.getWorldMatrix();
  21431. }
  21432. return _super.prototype.getWorldMatrix.call(this);
  21433. };
  21434. /** @hidden */
  21435. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  21436. if (this._masterMesh) {
  21437. return this._masterMesh._getWorldMatrixDeterminant();
  21438. }
  21439. return _super.prototype._getWorldMatrixDeterminant.call(this);
  21440. };
  21441. // ================================== Point of View Movement =================================
  21442. /**
  21443. * Perform relative position change from the point of view of behind the front of the mesh.
  21444. * This is performed taking into account the meshes current rotation, so you do not have to care.
  21445. * Supports definition of mesh facing forward or backward
  21446. * @param amountRight defines the distance on the right axis
  21447. * @param amountUp defines the distance on the up axis
  21448. * @param amountForward defines the distance on the forward axis
  21449. * @returns the current mesh
  21450. */
  21451. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  21452. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  21453. return this;
  21454. };
  21455. /**
  21456. * Calculate relative position change from the point of view of behind the front of the mesh.
  21457. * This is performed taking into account the meshes current rotation, so you do not have to care.
  21458. * Supports definition of mesh facing forward or backward
  21459. * @param amountRight defines the distance on the right axis
  21460. * @param amountUp defines the distance on the up axis
  21461. * @param amountForward defines the distance on the forward axis
  21462. * @returns the new displacement vector
  21463. */
  21464. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  21465. var rotMatrix = new BABYLON.Matrix();
  21466. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  21467. rotQuaternion.toRotationMatrix(rotMatrix);
  21468. var translationDelta = BABYLON.Vector3.Zero();
  21469. var defForwardMult = this.definedFacingForward ? -1 : 1;
  21470. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  21471. return translationDelta;
  21472. };
  21473. // ================================== Point of View Rotation =================================
  21474. /**
  21475. * Perform relative rotation change from the point of view of behind the front of the mesh.
  21476. * Supports definition of mesh facing forward or backward
  21477. * @param flipBack defines the flip
  21478. * @param twirlClockwise defines the twirl
  21479. * @param tiltRight defines the tilt
  21480. * @returns the current mesh
  21481. */
  21482. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  21483. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  21484. return this;
  21485. };
  21486. /**
  21487. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  21488. * Supports definition of mesh facing forward or backward.
  21489. * @param flipBack defines the flip
  21490. * @param twirlClockwise defines the twirl
  21491. * @param tiltRight defines the tilt
  21492. * @returns the new rotation vector
  21493. */
  21494. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  21495. var defForwardMult = this.definedFacingForward ? 1 : -1;
  21496. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  21497. };
  21498. /**
  21499. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  21500. * @param includeDescendants Include bounding info from descendants as well (true by default)
  21501. * @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
  21502. * @returns the new bounding vectors
  21503. */
  21504. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  21505. if (includeDescendants === void 0) { includeDescendants = true; }
  21506. if (predicate === void 0) { predicate = null; }
  21507. // Ensures that all world matrix will be recomputed.
  21508. this.getScene().incrementRenderId();
  21509. this.computeWorldMatrix(true);
  21510. var min;
  21511. var max;
  21512. var boundingInfo = this.getBoundingInfo();
  21513. if (!this.subMeshes) {
  21514. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  21515. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  21516. }
  21517. else {
  21518. min = boundingInfo.boundingBox.minimumWorld;
  21519. max = boundingInfo.boundingBox.maximumWorld;
  21520. }
  21521. if (includeDescendants) {
  21522. var descendants = this.getDescendants(false);
  21523. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  21524. var descendant = descendants_1[_i];
  21525. var childMesh = descendant;
  21526. childMesh.computeWorldMatrix(true);
  21527. // Filters meshes based on custom predicate function.
  21528. if (predicate && !predicate(childMesh)) {
  21529. continue;
  21530. }
  21531. //make sure we have the needed params to get mix and max
  21532. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  21533. continue;
  21534. }
  21535. var childBoundingInfo = childMesh.getBoundingInfo();
  21536. var boundingBox = childBoundingInfo.boundingBox;
  21537. var minBox = boundingBox.minimumWorld;
  21538. var maxBox = boundingBox.maximumWorld;
  21539. BABYLON.Tools.CheckExtends(minBox, min, max);
  21540. BABYLON.Tools.CheckExtends(maxBox, min, max);
  21541. }
  21542. }
  21543. return {
  21544. min: min,
  21545. max: max
  21546. };
  21547. };
  21548. /** @hidden */
  21549. AbstractMesh.prototype._updateBoundingInfo = function () {
  21550. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  21551. this._boundingInfo.update(this.worldMatrixFromCache);
  21552. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  21553. return this;
  21554. };
  21555. /** @hidden */
  21556. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  21557. if (!this.subMeshes) {
  21558. return this;
  21559. }
  21560. var count = this.subMeshes.length;
  21561. for (var subIndex = 0; subIndex < count; subIndex++) {
  21562. var subMesh = this.subMeshes[subIndex];
  21563. if (count > 1 || !subMesh.IsGlobal) {
  21564. subMesh.updateBoundingInfo(matrix);
  21565. }
  21566. }
  21567. return this;
  21568. };
  21569. /** @hidden */
  21570. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  21571. // Bounding info
  21572. this._updateBoundingInfo();
  21573. };
  21574. /**
  21575. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  21576. * A mesh is in the frustum if its bounding box intersects the frustum
  21577. * @param frustumPlanes defines the frustum to test
  21578. * @returns true if the mesh is in the frustum planes
  21579. */
  21580. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  21581. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes, this.cullingStrategy);
  21582. };
  21583. /**
  21584. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  21585. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  21586. * @param frustumPlanes defines the frustum to test
  21587. * @returns true if the mesh is completely in the frustum planes
  21588. */
  21589. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  21590. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  21591. };
  21592. /**
  21593. * True if the mesh intersects another mesh or a SolidParticle object
  21594. * @param mesh defines a target mesh or SolidParticle to test
  21595. * @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)
  21596. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  21597. * @returns true if there is an intersection
  21598. */
  21599. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  21600. if (precise === void 0) { precise = false; }
  21601. if (!this._boundingInfo || !mesh._boundingInfo) {
  21602. return false;
  21603. }
  21604. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  21605. return true;
  21606. }
  21607. if (includeDescendants) {
  21608. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  21609. var child = _a[_i];
  21610. if (child.intersectsMesh(mesh, precise, true)) {
  21611. return true;
  21612. }
  21613. }
  21614. }
  21615. return false;
  21616. };
  21617. /**
  21618. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  21619. * @param point defines the point to test
  21620. * @returns true if there is an intersection
  21621. */
  21622. AbstractMesh.prototype.intersectsPoint = function (point) {
  21623. if (!this._boundingInfo) {
  21624. return false;
  21625. }
  21626. return this._boundingInfo.intersectsPoint(point);
  21627. };
  21628. /**
  21629. * Gets the position of the current mesh in camera space
  21630. * @param camera defines the camera to use
  21631. * @returns a position
  21632. */
  21633. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  21634. if (camera === void 0) { camera = null; }
  21635. if (!camera) {
  21636. camera = this.getScene().activeCamera;
  21637. }
  21638. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  21639. };
  21640. /**
  21641. * Returns the distance from the mesh to the active camera
  21642. * @param camera defines the camera to use
  21643. * @returns the distance
  21644. */
  21645. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  21646. if (camera === void 0) { camera = null; }
  21647. if (!camera) {
  21648. camera = this.getScene().activeCamera;
  21649. }
  21650. return this.absolutePosition.subtract(camera.position).length();
  21651. };
  21652. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  21653. // Collisions
  21654. /**
  21655. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  21656. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  21657. */
  21658. get: function () {
  21659. return this._checkCollisions;
  21660. },
  21661. set: function (collisionEnabled) {
  21662. this._checkCollisions = collisionEnabled;
  21663. if (this.getScene().workerCollisions) {
  21664. this.getScene().collisionCoordinator.onMeshUpdated(this);
  21665. }
  21666. },
  21667. enumerable: true,
  21668. configurable: true
  21669. });
  21670. Object.defineProperty(AbstractMesh.prototype, "collider", {
  21671. /**
  21672. * Gets Collider object used to compute collisions (not physics)
  21673. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  21674. */
  21675. get: function () {
  21676. return this._collider;
  21677. },
  21678. enumerable: true,
  21679. configurable: true
  21680. });
  21681. /**
  21682. * Move the mesh using collision engine
  21683. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  21684. * @param displacement defines the requested displacement vector
  21685. * @returns the current mesh
  21686. */
  21687. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  21688. var globalPosition = this.getAbsolutePosition();
  21689. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  21690. if (!this._collider) {
  21691. this._collider = new BABYLON.Collider();
  21692. }
  21693. this._collider._radius = this.ellipsoid;
  21694. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  21695. return this;
  21696. };
  21697. // Collisions
  21698. /** @hidden */
  21699. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  21700. this._generatePointsArray();
  21701. if (!this._positions) {
  21702. return this;
  21703. }
  21704. // Transformation
  21705. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  21706. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  21707. subMesh._lastColliderWorldVertices = [];
  21708. subMesh._trianglePlanes = [];
  21709. var start = subMesh.verticesStart;
  21710. var end = (subMesh.verticesStart + subMesh.verticesCount);
  21711. for (var i = start; i < end; i++) {
  21712. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  21713. }
  21714. }
  21715. // Collide
  21716. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  21717. if (collider.collisionFound) {
  21718. collider.collidedMesh = this;
  21719. }
  21720. return this;
  21721. };
  21722. /** @hidden */
  21723. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  21724. var subMeshes = this._scene.getCollidingSubMeshCandidates(this, collider);
  21725. var len = subMeshes.length;
  21726. for (var index = 0; index < len; index++) {
  21727. var subMesh = subMeshes.data[index];
  21728. // Bounding test
  21729. if (len > 1 && !subMesh._checkCollision(collider))
  21730. continue;
  21731. this._collideForSubMesh(subMesh, transformMatrix, collider);
  21732. }
  21733. return this;
  21734. };
  21735. /** @hidden */
  21736. AbstractMesh.prototype._checkCollision = function (collider) {
  21737. // Bounding box test
  21738. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  21739. return this;
  21740. // Transformation matrix
  21741. var collisionsScalingMatrix = BABYLON.Tmp.Matrix[0];
  21742. var collisionsTransformMatrix = BABYLON.Tmp.Matrix[1];
  21743. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, collisionsScalingMatrix);
  21744. this.worldMatrixFromCache.multiplyToRef(collisionsScalingMatrix, collisionsTransformMatrix);
  21745. this._processCollisionsForSubMeshes(collider, collisionsTransformMatrix);
  21746. return this;
  21747. };
  21748. // Picking
  21749. /** @hidden */
  21750. AbstractMesh.prototype._generatePointsArray = function () {
  21751. return false;
  21752. };
  21753. /**
  21754. * Checks if the passed Ray intersects with the mesh
  21755. * @param ray defines the ray to use
  21756. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  21757. * @returns the picking info
  21758. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  21759. */
  21760. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  21761. var pickingInfo = new BABYLON.PickingInfo();
  21762. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  21763. return pickingInfo;
  21764. }
  21765. if (!this._generatePointsArray()) {
  21766. return pickingInfo;
  21767. }
  21768. var intersectInfo = null;
  21769. var subMeshes = this._scene.getIntersectingSubMeshCandidates(this, ray);
  21770. var len = subMeshes.length;
  21771. for (var index = 0; index < len; index++) {
  21772. var subMesh = subMeshes.data[index];
  21773. // Bounding test
  21774. if (len > 1 && !subMesh.canIntersects(ray))
  21775. continue;
  21776. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  21777. if (currentIntersectInfo) {
  21778. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  21779. intersectInfo = currentIntersectInfo;
  21780. intersectInfo.subMeshId = index;
  21781. if (fastCheck) {
  21782. break;
  21783. }
  21784. }
  21785. }
  21786. }
  21787. if (intersectInfo) {
  21788. // Get picked point
  21789. var world = this.getWorldMatrix();
  21790. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  21791. var direction = ray.direction.clone();
  21792. direction = direction.scale(intersectInfo.distance);
  21793. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  21794. var pickedPoint = worldOrigin.add(worldDirection);
  21795. // Return result
  21796. pickingInfo.hit = true;
  21797. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  21798. pickingInfo.pickedPoint = pickedPoint;
  21799. pickingInfo.pickedMesh = this;
  21800. pickingInfo.bu = intersectInfo.bu || 0;
  21801. pickingInfo.bv = intersectInfo.bv || 0;
  21802. pickingInfo.faceId = intersectInfo.faceId;
  21803. pickingInfo.subMeshId = intersectInfo.subMeshId;
  21804. return pickingInfo;
  21805. }
  21806. return pickingInfo;
  21807. };
  21808. /**
  21809. * Clones the current mesh
  21810. * @param name defines the mesh name
  21811. * @param newParent defines the new mesh parent
  21812. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  21813. * @returns the new mesh
  21814. */
  21815. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  21816. return null;
  21817. };
  21818. /**
  21819. * Disposes all the submeshes of the current meshnp
  21820. * @returns the current mesh
  21821. */
  21822. AbstractMesh.prototype.releaseSubMeshes = function () {
  21823. if (this.subMeshes) {
  21824. while (this.subMeshes.length) {
  21825. this.subMeshes[0].dispose();
  21826. }
  21827. }
  21828. else {
  21829. this.subMeshes = new Array();
  21830. }
  21831. return this;
  21832. };
  21833. /**
  21834. * Releases resources associated with this abstract mesh.
  21835. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21836. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21837. */
  21838. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21839. var _this = this;
  21840. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21841. var index;
  21842. // Smart Array Retainers.
  21843. this.getScene().freeActiveMeshes();
  21844. this.getScene().freeRenderingGroups();
  21845. // Action manager
  21846. if (this.actionManager !== undefined && this.actionManager !== null) {
  21847. this.actionManager.dispose();
  21848. this.actionManager = null;
  21849. }
  21850. // Skeleton
  21851. this._skeleton = null;
  21852. // Intersections in progress
  21853. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  21854. var other = this._intersectionsInProgress[index];
  21855. var pos = other._intersectionsInProgress.indexOf(this);
  21856. other._intersectionsInProgress.splice(pos, 1);
  21857. }
  21858. this._intersectionsInProgress = [];
  21859. // Lights
  21860. var lights = this.getScene().lights;
  21861. lights.forEach(function (light) {
  21862. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  21863. if (meshIndex !== -1) {
  21864. light.includedOnlyMeshes.splice(meshIndex, 1);
  21865. }
  21866. meshIndex = light.excludedMeshes.indexOf(_this);
  21867. if (meshIndex !== -1) {
  21868. light.excludedMeshes.splice(meshIndex, 1);
  21869. }
  21870. // Shadow generators
  21871. var generator = light.getShadowGenerator();
  21872. if (generator) {
  21873. var shadowMap = generator.getShadowMap();
  21874. if (shadowMap && shadowMap.renderList) {
  21875. meshIndex = shadowMap.renderList.indexOf(_this);
  21876. if (meshIndex !== -1) {
  21877. shadowMap.renderList.splice(meshIndex, 1);
  21878. }
  21879. }
  21880. }
  21881. });
  21882. // SubMeshes
  21883. if (this.getClassName() !== "InstancedMesh") {
  21884. this.releaseSubMeshes();
  21885. }
  21886. // Query
  21887. var engine = this.getScene().getEngine();
  21888. if (this._occlusionQuery) {
  21889. this.isOcclusionQueryInProgress = false;
  21890. engine.deleteQuery(this._occlusionQuery);
  21891. this._occlusionQuery = null;
  21892. }
  21893. // Engine
  21894. engine.wipeCaches();
  21895. // Remove from scene
  21896. this.getScene().removeMesh(this);
  21897. if (disposeMaterialAndTextures) {
  21898. if (this.material) {
  21899. this.material.dispose(false, true);
  21900. }
  21901. }
  21902. if (!doNotRecurse) {
  21903. // Particles
  21904. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  21905. if (this.getScene().particleSystems[index].emitter === this) {
  21906. this.getScene().particleSystems[index].dispose();
  21907. index--;
  21908. }
  21909. }
  21910. }
  21911. // facet data
  21912. if (this._facetData.facetDataEnabled) {
  21913. this.disableFacetData();
  21914. }
  21915. this.onAfterWorldMatrixUpdateObservable.clear();
  21916. this.onCollideObservable.clear();
  21917. this.onCollisionPositionChangeObservable.clear();
  21918. this.onRebuildObservable.clear();
  21919. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21920. };
  21921. /**
  21922. * Adds the passed mesh as a child to the current mesh
  21923. * @param mesh defines the child mesh
  21924. * @returns the current mesh
  21925. */
  21926. AbstractMesh.prototype.addChild = function (mesh) {
  21927. mesh.setParent(this);
  21928. return this;
  21929. };
  21930. /**
  21931. * Removes the passed mesh from the current mesh children list
  21932. * @param mesh defines the child mesh
  21933. * @returns the current mesh
  21934. */
  21935. AbstractMesh.prototype.removeChild = function (mesh) {
  21936. mesh.setParent(null);
  21937. return this;
  21938. };
  21939. // Facet data
  21940. /** @hidden */
  21941. AbstractMesh.prototype._initFacetData = function () {
  21942. var data = this._facetData;
  21943. if (!data.facetNormals) {
  21944. data.facetNormals = new Array();
  21945. }
  21946. if (!data.facetPositions) {
  21947. data.facetPositions = new Array();
  21948. }
  21949. if (!data.facetPartitioning) {
  21950. data.facetPartitioning = new Array();
  21951. }
  21952. data.facetNb = (this.getIndices().length / 3) | 0;
  21953. data.partitioningSubdivisions = (data.partitioningSubdivisions) ? data.partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  21954. data.partitioningBBoxRatio = (data.partitioningBBoxRatio) ? data.partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  21955. for (var f = 0; f < data.facetNb; f++) {
  21956. data.facetNormals[f] = BABYLON.Vector3.Zero();
  21957. data.facetPositions[f] = BABYLON.Vector3.Zero();
  21958. }
  21959. data.facetDataEnabled = true;
  21960. return this;
  21961. };
  21962. /**
  21963. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  21964. * This method can be called within the render loop.
  21965. * 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
  21966. * @returns the current mesh
  21967. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21968. */
  21969. AbstractMesh.prototype.updateFacetData = function () {
  21970. var data = this._facetData;
  21971. if (!data.facetDataEnabled) {
  21972. this._initFacetData();
  21973. }
  21974. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21975. var indices = this.getIndices();
  21976. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21977. var bInfo = this.getBoundingInfo();
  21978. if (data.facetDepthSort && !data.facetDepthSortEnabled) {
  21979. // init arrays, matrix and sort function on first call
  21980. data.facetDepthSortEnabled = true;
  21981. if (indices instanceof Uint16Array) {
  21982. data.depthSortedIndices = new Uint16Array(indices);
  21983. }
  21984. else if (indices instanceof Uint32Array) {
  21985. data.depthSortedIndices = new Uint32Array(indices);
  21986. }
  21987. else {
  21988. var needs32bits = false;
  21989. for (var i = 0; i < indices.length; i++) {
  21990. if (indices[i] > 65535) {
  21991. needs32bits = true;
  21992. break;
  21993. }
  21994. }
  21995. if (needs32bits) {
  21996. data.depthSortedIndices = new Uint32Array(indices);
  21997. }
  21998. else {
  21999. data.depthSortedIndices = new Uint16Array(indices);
  22000. }
  22001. }
  22002. data.facetDepthSortFunction = function (f1, f2) {
  22003. return (f2.sqDistance - f1.sqDistance);
  22004. };
  22005. if (!data.facetDepthSortFrom) {
  22006. var camera = this.getScene().activeCamera;
  22007. data.facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  22008. }
  22009. data.depthSortedFacets = [];
  22010. for (var f = 0; f < data.facetNb; f++) {
  22011. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  22012. data.depthSortedFacets.push(depthSortedFacet);
  22013. }
  22014. data.invertedMatrix = BABYLON.Matrix.Identity();
  22015. data.facetDepthSortOrigin = BABYLON.Vector3.Zero();
  22016. }
  22017. data.bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  22018. data.bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  22019. data.bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  22020. var bbSizeMax = (data.bbSize.x > data.bbSize.y) ? data.bbSize.x : data.bbSize.y;
  22021. bbSizeMax = (bbSizeMax > data.bbSize.z) ? bbSizeMax : data.bbSize.z;
  22022. data.subDiv.max = data.partitioningSubdivisions;
  22023. data.subDiv.X = Math.floor(data.subDiv.max * data.bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  22024. data.subDiv.Y = Math.floor(data.subDiv.max * data.bbSize.y / bbSizeMax); // according to each bbox size per axis
  22025. data.subDiv.Z = Math.floor(data.subDiv.max * data.bbSize.z / bbSizeMax);
  22026. data.subDiv.X = data.subDiv.X < 1 ? 1 : data.subDiv.X; // at least one subdivision
  22027. data.subDiv.Y = data.subDiv.Y < 1 ? 1 : data.subDiv.Y;
  22028. data.subDiv.Z = data.subDiv.Z < 1 ? 1 : data.subDiv.Z;
  22029. // set the parameters for ComputeNormals()
  22030. data.facetParameters.facetNormals = this.getFacetLocalNormals();
  22031. data.facetParameters.facetPositions = this.getFacetLocalPositions();
  22032. data.facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  22033. data.facetParameters.bInfo = bInfo;
  22034. data.facetParameters.bbSize = data.bbSize;
  22035. data.facetParameters.subDiv = data.subDiv;
  22036. data.facetParameters.ratio = this.partitioningBBoxRatio;
  22037. data.facetParameters.depthSort = data.facetDepthSort;
  22038. if (data.facetDepthSort && data.facetDepthSortEnabled) {
  22039. this.computeWorldMatrix(true);
  22040. this._worldMatrix.invertToRef(data.invertedMatrix);
  22041. BABYLON.Vector3.TransformCoordinatesToRef(data.facetDepthSortFrom, data.invertedMatrix, data.facetDepthSortOrigin);
  22042. data.facetParameters.distanceTo = data.facetDepthSortOrigin;
  22043. }
  22044. data.facetParameters.depthSortedFacets = data.depthSortedFacets;
  22045. BABYLON.VertexData.ComputeNormals(positions, indices, normals, data.facetParameters);
  22046. if (data.facetDepthSort && data.facetDepthSortEnabled) {
  22047. data.depthSortedFacets.sort(data.facetDepthSortFunction);
  22048. var l = (data.depthSortedIndices.length / 3) | 0;
  22049. for (var f = 0; f < l; f++) {
  22050. var sind = data.depthSortedFacets[f].ind;
  22051. data.depthSortedIndices[f * 3] = indices[sind];
  22052. data.depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  22053. data.depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  22054. }
  22055. this.updateIndices(data.depthSortedIndices);
  22056. }
  22057. return this;
  22058. };
  22059. /**
  22060. * Returns the facetLocalNormals array.
  22061. * The normals are expressed in the mesh local spac
  22062. * @returns an array of Vector3
  22063. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22064. */
  22065. AbstractMesh.prototype.getFacetLocalNormals = function () {
  22066. if (!this._facetData.facetNormals) {
  22067. this.updateFacetData();
  22068. }
  22069. return this._facetData.facetNormals;
  22070. };
  22071. /**
  22072. * Returns the facetLocalPositions array.
  22073. * The facet positions are expressed in the mesh local space
  22074. * @returns an array of Vector3
  22075. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22076. */
  22077. AbstractMesh.prototype.getFacetLocalPositions = function () {
  22078. if (!this._facetData.facetPositions) {
  22079. this.updateFacetData();
  22080. }
  22081. return this._facetData.facetPositions;
  22082. };
  22083. /**
  22084. * Returns the facetLocalPartioning array
  22085. * @returns an array of array of numbers
  22086. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22087. */
  22088. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  22089. if (!this._facetData.facetPartitioning) {
  22090. this.updateFacetData();
  22091. }
  22092. return this._facetData.facetPartitioning;
  22093. };
  22094. /**
  22095. * Returns the i-th facet position in the world system.
  22096. * This method allocates a new Vector3 per call
  22097. * @param i defines the facet index
  22098. * @returns a new Vector3
  22099. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22100. */
  22101. AbstractMesh.prototype.getFacetPosition = function (i) {
  22102. var pos = BABYLON.Vector3.Zero();
  22103. this.getFacetPositionToRef(i, pos);
  22104. return pos;
  22105. };
  22106. /**
  22107. * Sets the reference Vector3 with the i-th facet position in the world system
  22108. * @param i defines the facet index
  22109. * @param ref defines the target vector
  22110. * @returns the current mesh
  22111. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22112. */
  22113. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  22114. var localPos = (this.getFacetLocalPositions())[i];
  22115. var world = this.getWorldMatrix();
  22116. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  22117. return this;
  22118. };
  22119. /**
  22120. * Returns the i-th facet normal in the world system.
  22121. * This method allocates a new Vector3 per call
  22122. * @param i defines the facet index
  22123. * @returns a new Vector3
  22124. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22125. */
  22126. AbstractMesh.prototype.getFacetNormal = function (i) {
  22127. var norm = BABYLON.Vector3.Zero();
  22128. this.getFacetNormalToRef(i, norm);
  22129. return norm;
  22130. };
  22131. /**
  22132. * Sets the reference Vector3 with the i-th facet normal in the world system
  22133. * @param i defines the facet index
  22134. * @param ref defines the target vector
  22135. * @returns the current mesh
  22136. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22137. */
  22138. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  22139. var localNorm = (this.getFacetLocalNormals())[i];
  22140. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  22141. return this;
  22142. };
  22143. /**
  22144. * 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)
  22145. * @param x defines x coordinate
  22146. * @param y defines y coordinate
  22147. * @param z defines z coordinate
  22148. * @returns the array of facet indexes
  22149. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22150. */
  22151. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  22152. var bInfo = this.getBoundingInfo();
  22153. var data = this._facetData;
  22154. var ox = Math.floor((x - bInfo.minimum.x * data.partitioningBBoxRatio) * data.subDiv.X * data.partitioningBBoxRatio / data.bbSize.x);
  22155. var oy = Math.floor((y - bInfo.minimum.y * data.partitioningBBoxRatio) * data.subDiv.Y * data.partitioningBBoxRatio / data.bbSize.y);
  22156. var oz = Math.floor((z - bInfo.minimum.z * data.partitioningBBoxRatio) * data.subDiv.Z * data.partitioningBBoxRatio / data.bbSize.z);
  22157. if (ox < 0 || ox > data.subDiv.max || oy < 0 || oy > data.subDiv.max || oz < 0 || oz > data.subDiv.max) {
  22158. return null;
  22159. }
  22160. return data.facetPartitioning[ox + data.subDiv.max * oy + data.subDiv.max * data.subDiv.max * oz];
  22161. };
  22162. /**
  22163. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  22164. * @param projected sets as the (x,y,z) world projection on the facet
  22165. * @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
  22166. * @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
  22167. * @param x defines x coordinate
  22168. * @param y defines y coordinate
  22169. * @param z defines z coordinate
  22170. * @returns the face index if found (or null instead)
  22171. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22172. */
  22173. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  22174. if (checkFace === void 0) { checkFace = false; }
  22175. if (facing === void 0) { facing = true; }
  22176. var world = this.getWorldMatrix();
  22177. var invMat = BABYLON.Tmp.Matrix[5];
  22178. world.invertToRef(invMat);
  22179. var invVect = BABYLON.Tmp.Vector3[8];
  22180. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  22181. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  22182. if (projected) {
  22183. // tranform the local computed projected vector to world coordinates
  22184. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  22185. }
  22186. return closest;
  22187. };
  22188. /**
  22189. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  22190. * @param projected sets as the (x,y,z) local projection on the facet
  22191. * @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
  22192. * @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
  22193. * @param x defines x coordinate
  22194. * @param y defines y coordinate
  22195. * @param z defines z coordinate
  22196. * @returns the face index if found (or null instead)
  22197. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22198. */
  22199. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  22200. if (checkFace === void 0) { checkFace = false; }
  22201. if (facing === void 0) { facing = true; }
  22202. var closest = null;
  22203. var tmpx = 0.0;
  22204. var tmpy = 0.0;
  22205. var tmpz = 0.0;
  22206. var d = 0.0; // tmp dot facet normal * facet position
  22207. var t0 = 0.0;
  22208. var projx = 0.0;
  22209. var projy = 0.0;
  22210. var projz = 0.0;
  22211. // Get all the facets in the same partitioning block than (x, y, z)
  22212. var facetPositions = this.getFacetLocalPositions();
  22213. var facetNormals = this.getFacetLocalNormals();
  22214. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  22215. if (!facetsInBlock) {
  22216. return null;
  22217. }
  22218. // Get the closest facet to (x, y, z)
  22219. var shortest = Number.MAX_VALUE; // init distance vars
  22220. var tmpDistance = shortest;
  22221. var fib; // current facet in the block
  22222. var norm; // current facet normal
  22223. var p0; // current facet barycenter position
  22224. // loop on all the facets in the current partitioning block
  22225. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  22226. fib = facetsInBlock[idx];
  22227. norm = facetNormals[fib];
  22228. p0 = facetPositions[fib];
  22229. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  22230. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  22231. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  22232. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  22233. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  22234. projx = x + norm.x * t0;
  22235. projy = y + norm.y * t0;
  22236. projz = z + norm.z * t0;
  22237. tmpx = projx - x;
  22238. tmpy = projy - y;
  22239. tmpz = projz - z;
  22240. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  22241. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  22242. shortest = tmpDistance;
  22243. closest = fib;
  22244. if (projected) {
  22245. projected.x = projx;
  22246. projected.y = projy;
  22247. projected.z = projz;
  22248. }
  22249. }
  22250. }
  22251. }
  22252. return closest;
  22253. };
  22254. /**
  22255. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  22256. * @returns the parameters
  22257. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22258. */
  22259. AbstractMesh.prototype.getFacetDataParameters = function () {
  22260. return this._facetData.facetParameters;
  22261. };
  22262. /**
  22263. * Disables the feature FacetData and frees the related memory
  22264. * @returns the current mesh
  22265. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22266. */
  22267. AbstractMesh.prototype.disableFacetData = function () {
  22268. if (this._facetData.facetDataEnabled) {
  22269. this._facetData.facetDataEnabled = false;
  22270. this._facetData.facetPositions = new Array();
  22271. this._facetData.facetNormals = new Array();
  22272. this._facetData.facetPartitioning = new Array();
  22273. this._facetData.facetParameters = null;
  22274. this._facetData.depthSortedIndices = new Uint32Array(0);
  22275. }
  22276. return this;
  22277. };
  22278. /**
  22279. * Updates the AbstractMesh indices array
  22280. * @param indices defines the data source
  22281. * @returns the current mesh
  22282. */
  22283. AbstractMesh.prototype.updateIndices = function (indices) {
  22284. return this;
  22285. };
  22286. /**
  22287. * Creates new normals data for the mesh
  22288. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  22289. * @returns the current mesh
  22290. */
  22291. AbstractMesh.prototype.createNormals = function (updatable) {
  22292. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22293. var indices = this.getIndices();
  22294. var normals;
  22295. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22296. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22297. }
  22298. else {
  22299. normals = [];
  22300. }
  22301. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  22302. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  22303. return this;
  22304. };
  22305. /**
  22306. * Align the mesh with a normal
  22307. * @param normal defines the normal to use
  22308. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  22309. * @returns the current mesh
  22310. */
  22311. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  22312. if (!upDirection) {
  22313. upDirection = BABYLON.Axis.Y;
  22314. }
  22315. var axisX = BABYLON.Tmp.Vector3[0];
  22316. var axisZ = BABYLON.Tmp.Vector3[1];
  22317. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  22318. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  22319. if (this.rotationQuaternion) {
  22320. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  22321. }
  22322. else {
  22323. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  22324. }
  22325. return this;
  22326. };
  22327. /** @hidden */
  22328. AbstractMesh.prototype._checkOcclusionQuery = function () {
  22329. return false;
  22330. };
  22331. /** No occlusion */
  22332. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  22333. /** Occlusion set to optimisitic */
  22334. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  22335. /** Occlusion set to strict */
  22336. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  22337. /** Use an accurante occlusion algorithm */
  22338. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  22339. /** Use a conservative occlusion algorithm */
  22340. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  22341. /** Default culling strategy with bounding box and bounding sphere and then frustum culling */
  22342. AbstractMesh.CULLINGSTRATEGY_STANDARD = 0;
  22343. /** Culling strategy with bounding sphere only and then frustum culling */
  22344. AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY = 1;
  22345. return AbstractMesh;
  22346. }(BABYLON.TransformNode));
  22347. BABYLON.AbstractMesh = AbstractMesh;
  22348. })(BABYLON || (BABYLON = {}));
  22349. //# sourceMappingURL=babylon.abstractMesh.js.map
  22350. var BABYLON;
  22351. (function (BABYLON) {
  22352. /**
  22353. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  22354. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  22355. * 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.
  22356. */
  22357. var Light = /** @class */ (function (_super) {
  22358. __extends(Light, _super);
  22359. /**
  22360. * Creates a Light object in the scene.
  22361. * Documentation : http://doc.babylonjs.com/tutorials/lights
  22362. * @param name The firendly name of the light
  22363. * @param scene The scene the light belongs too
  22364. */
  22365. function Light(name, scene) {
  22366. var _this = _super.call(this, name, scene) || this;
  22367. /**
  22368. * Diffuse gives the basic color to an object.
  22369. */
  22370. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  22371. /**
  22372. * Specular produces a highlight color on an object.
  22373. * Note: This is note affecting PBR materials.
  22374. */
  22375. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  22376. /**
  22377. * Defines the falloff type for this light. This lets overrriding how punctual light are
  22378. * falling off base on range or angle.
  22379. * This can be set to any values in Light.FALLOFF_x.
  22380. *
  22381. * Note: This is only usefull for PBR Materials at the moment. This could be extended if required to
  22382. * other types of materials.
  22383. */
  22384. _this.falloffType = Light.FALLOFF_DEFAULT;
  22385. /**
  22386. * Strength of the light.
  22387. * Note: By default it is define in the framework own unit.
  22388. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  22389. */
  22390. _this.intensity = 1.0;
  22391. _this._range = Number.MAX_VALUE;
  22392. _this._inverseSquaredRange = 0;
  22393. /**
  22394. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  22395. * of light.
  22396. */
  22397. _this._photometricScale = 1.0;
  22398. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  22399. _this._radius = 0.00001;
  22400. /**
  22401. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  22402. * exceeding the number allowed of the materials.
  22403. */
  22404. _this.renderPriority = 0;
  22405. _this._shadowEnabled = true;
  22406. _this._excludeWithLayerMask = 0;
  22407. _this._includeOnlyWithLayerMask = 0;
  22408. _this._lightmapMode = 0;
  22409. /**
  22410. * @hidden Internal use only.
  22411. */
  22412. _this._excludedMeshesIds = new Array();
  22413. /**
  22414. * @hidden Internal use only.
  22415. */
  22416. _this._includedOnlyMeshesIds = new Array();
  22417. _this.getScene().addLight(_this);
  22418. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  22419. _this._buildUniformLayout();
  22420. _this.includedOnlyMeshes = new Array();
  22421. _this.excludedMeshes = new Array();
  22422. _this._resyncMeshes();
  22423. return _this;
  22424. }
  22425. Object.defineProperty(Light.prototype, "range", {
  22426. /**
  22427. * Defines how far from the source the light is impacting in scene units.
  22428. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  22429. */
  22430. get: function () {
  22431. return this._range;
  22432. },
  22433. /**
  22434. * Defines how far from the source the light is impacting in scene units.
  22435. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  22436. */
  22437. set: function (value) {
  22438. this._range = value;
  22439. this._inverseSquaredRange = 1.0 / (this.range * this.range);
  22440. },
  22441. enumerable: true,
  22442. configurable: true
  22443. });
  22444. Object.defineProperty(Light.prototype, "intensityMode", {
  22445. /**
  22446. * Gets the photometric scale used to interpret the intensity.
  22447. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  22448. */
  22449. get: function () {
  22450. return this._intensityMode;
  22451. },
  22452. /**
  22453. * Sets the photometric scale used to interpret the intensity.
  22454. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  22455. */
  22456. set: function (value) {
  22457. this._intensityMode = value;
  22458. this._computePhotometricScale();
  22459. },
  22460. enumerable: true,
  22461. configurable: true
  22462. });
  22463. ;
  22464. ;
  22465. Object.defineProperty(Light.prototype, "radius", {
  22466. /**
  22467. * Gets the light radius used by PBR Materials to simulate soft area lights.
  22468. */
  22469. get: function () {
  22470. return this._radius;
  22471. },
  22472. /**
  22473. * sets the light radius used by PBR Materials to simulate soft area lights.
  22474. */
  22475. set: function (value) {
  22476. this._radius = value;
  22477. this._computePhotometricScale();
  22478. },
  22479. enumerable: true,
  22480. configurable: true
  22481. });
  22482. ;
  22483. ;
  22484. Object.defineProperty(Light.prototype, "shadowEnabled", {
  22485. /**
  22486. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  22487. * the current shadow generator.
  22488. */
  22489. get: function () {
  22490. return this._shadowEnabled;
  22491. },
  22492. /**
  22493. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  22494. * the current shadow generator.
  22495. */
  22496. set: function (value) {
  22497. if (this._shadowEnabled === value) {
  22498. return;
  22499. }
  22500. this._shadowEnabled = value;
  22501. this._markMeshesAsLightDirty();
  22502. },
  22503. enumerable: true,
  22504. configurable: true
  22505. });
  22506. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  22507. /**
  22508. * Gets the only meshes impacted by this light.
  22509. */
  22510. get: function () {
  22511. return this._includedOnlyMeshes;
  22512. },
  22513. /**
  22514. * Sets the only meshes impacted by this light.
  22515. */
  22516. set: function (value) {
  22517. this._includedOnlyMeshes = value;
  22518. this._hookArrayForIncludedOnly(value);
  22519. },
  22520. enumerable: true,
  22521. configurable: true
  22522. });
  22523. Object.defineProperty(Light.prototype, "excludedMeshes", {
  22524. /**
  22525. * Gets the meshes not impacted by this light.
  22526. */
  22527. get: function () {
  22528. return this._excludedMeshes;
  22529. },
  22530. /**
  22531. * Sets the meshes not impacted by this light.
  22532. */
  22533. set: function (value) {
  22534. this._excludedMeshes = value;
  22535. this._hookArrayForExcluded(value);
  22536. },
  22537. enumerable: true,
  22538. configurable: true
  22539. });
  22540. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  22541. /**
  22542. * Gets the layer id use to find what meshes are not impacted by the light.
  22543. * Inactive if 0
  22544. */
  22545. get: function () {
  22546. return this._excludeWithLayerMask;
  22547. },
  22548. /**
  22549. * Sets the layer id use to find what meshes are not impacted by the light.
  22550. * Inactive if 0
  22551. */
  22552. set: function (value) {
  22553. this._excludeWithLayerMask = value;
  22554. this._resyncMeshes();
  22555. },
  22556. enumerable: true,
  22557. configurable: true
  22558. });
  22559. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  22560. /**
  22561. * Gets the layer id use to find what meshes are impacted by the light.
  22562. * Inactive if 0
  22563. */
  22564. get: function () {
  22565. return this._includeOnlyWithLayerMask;
  22566. },
  22567. /**
  22568. * Sets the layer id use to find what meshes are impacted by the light.
  22569. * Inactive if 0
  22570. */
  22571. set: function (value) {
  22572. this._includeOnlyWithLayerMask = value;
  22573. this._resyncMeshes();
  22574. },
  22575. enumerable: true,
  22576. configurable: true
  22577. });
  22578. Object.defineProperty(Light.prototype, "lightmapMode", {
  22579. /**
  22580. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  22581. */
  22582. get: function () {
  22583. return this._lightmapMode;
  22584. },
  22585. /**
  22586. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  22587. */
  22588. set: function (value) {
  22589. if (this._lightmapMode === value) {
  22590. return;
  22591. }
  22592. this._lightmapMode = value;
  22593. this._markMeshesAsLightDirty();
  22594. },
  22595. enumerable: true,
  22596. configurable: true
  22597. });
  22598. /**
  22599. * Returns the string "Light".
  22600. * @returns the class name
  22601. */
  22602. Light.prototype.getClassName = function () {
  22603. return "Light";
  22604. };
  22605. /**
  22606. * Converts the light information to a readable string for debug purpose.
  22607. * @param fullDetails Supports for multiple levels of logging within scene loading
  22608. * @returns the human readable light info
  22609. */
  22610. Light.prototype.toString = function (fullDetails) {
  22611. var ret = "Name: " + this.name;
  22612. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  22613. if (this.animations) {
  22614. for (var i = 0; i < this.animations.length; i++) {
  22615. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22616. }
  22617. }
  22618. if (fullDetails) {
  22619. }
  22620. return ret;
  22621. };
  22622. /** @hidden */
  22623. Light.prototype._syncParentEnabledState = function () {
  22624. _super.prototype._syncParentEnabledState.call(this);
  22625. this._resyncMeshes();
  22626. };
  22627. /**
  22628. * Set the enabled state of this node.
  22629. * @param value - the new enabled state
  22630. */
  22631. Light.prototype.setEnabled = function (value) {
  22632. _super.prototype.setEnabled.call(this, value);
  22633. this._resyncMeshes();
  22634. };
  22635. /**
  22636. * Returns the Light associated shadow generator if any.
  22637. * @return the associated shadow generator.
  22638. */
  22639. Light.prototype.getShadowGenerator = function () {
  22640. return this._shadowGenerator;
  22641. };
  22642. /**
  22643. * Returns a Vector3, the absolute light position in the World.
  22644. * @returns the world space position of the light
  22645. */
  22646. Light.prototype.getAbsolutePosition = function () {
  22647. return BABYLON.Vector3.Zero();
  22648. };
  22649. /**
  22650. * Specifies if the light will affect the passed mesh.
  22651. * @param mesh The mesh to test against the light
  22652. * @return true the mesh is affected otherwise, false.
  22653. */
  22654. Light.prototype.canAffectMesh = function (mesh) {
  22655. if (!mesh) {
  22656. return true;
  22657. }
  22658. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  22659. return false;
  22660. }
  22661. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  22662. return false;
  22663. }
  22664. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  22665. return false;
  22666. }
  22667. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  22668. return false;
  22669. }
  22670. return true;
  22671. };
  22672. /**
  22673. * Sort function to order lights for rendering.
  22674. * @param a First Light object to compare to second.
  22675. * @param b Second Light object to compare first.
  22676. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  22677. */
  22678. Light.CompareLightsPriority = function (a, b) {
  22679. //shadow-casting lights have priority over non-shadow-casting lights
  22680. //the renderPrioirty is a secondary sort criterion
  22681. if (a.shadowEnabled !== b.shadowEnabled) {
  22682. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  22683. }
  22684. return b.renderPriority - a.renderPriority;
  22685. };
  22686. /**
  22687. * Releases resources associated with this node.
  22688. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22689. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22690. */
  22691. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22692. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22693. if (this._shadowGenerator) {
  22694. this._shadowGenerator.dispose();
  22695. this._shadowGenerator = null;
  22696. }
  22697. // Animations
  22698. this.getScene().stopAnimation(this);
  22699. // Remove from meshes
  22700. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22701. var mesh = _a[_i];
  22702. mesh._removeLightSource(this);
  22703. }
  22704. this._uniformBuffer.dispose();
  22705. // Remove from scene
  22706. this.getScene().removeLight(this);
  22707. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22708. };
  22709. /**
  22710. * Returns the light type ID (integer).
  22711. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  22712. */
  22713. Light.prototype.getTypeID = function () {
  22714. return 0;
  22715. };
  22716. /**
  22717. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  22718. * @returns the scaled intensity in intensity mode unit
  22719. */
  22720. Light.prototype.getScaledIntensity = function () {
  22721. return this._photometricScale * this.intensity;
  22722. };
  22723. /**
  22724. * Returns a new Light object, named "name", from the current one.
  22725. * @param name The name of the cloned light
  22726. * @returns the new created light
  22727. */
  22728. Light.prototype.clone = function (name) {
  22729. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  22730. if (!constructor) {
  22731. return null;
  22732. }
  22733. return BABYLON.SerializationHelper.Clone(constructor, this);
  22734. };
  22735. /**
  22736. * Serializes the current light into a Serialization object.
  22737. * @returns the serialized object.
  22738. */
  22739. Light.prototype.serialize = function () {
  22740. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22741. // Type
  22742. serializationObject.type = this.getTypeID();
  22743. // Parent
  22744. if (this.parent) {
  22745. serializationObject.parentId = this.parent.id;
  22746. }
  22747. // Inclusion / exclusions
  22748. if (this.excludedMeshes.length > 0) {
  22749. serializationObject.excludedMeshesIds = [];
  22750. this.excludedMeshes.forEach(function (mesh) {
  22751. serializationObject.excludedMeshesIds.push(mesh.id);
  22752. });
  22753. }
  22754. if (this.includedOnlyMeshes.length > 0) {
  22755. serializationObject.includedOnlyMeshesIds = [];
  22756. this.includedOnlyMeshes.forEach(function (mesh) {
  22757. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  22758. });
  22759. }
  22760. // Animations
  22761. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22762. serializationObject.ranges = this.serializeAnimationRanges();
  22763. return serializationObject;
  22764. };
  22765. /**
  22766. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  22767. * This new light is named "name" and added to the passed scene.
  22768. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  22769. * @param name The friendly name of the light
  22770. * @param scene The scene the new light will belong to
  22771. * @returns the constructor function
  22772. */
  22773. Light.GetConstructorFromName = function (type, name, scene) {
  22774. var constructorFunc = BABYLON.Node.Construct("Light_Type_" + type, name, scene);
  22775. if (constructorFunc) {
  22776. return constructorFunc;
  22777. }
  22778. // Default to no light for none present once.
  22779. return null;
  22780. };
  22781. /**
  22782. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  22783. * @param parsedLight The JSON representation of the light
  22784. * @param scene The scene to create the parsed light in
  22785. * @returns the created light after parsing
  22786. */
  22787. Light.Parse = function (parsedLight, scene) {
  22788. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  22789. if (!constructor) {
  22790. return null;
  22791. }
  22792. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  22793. // Inclusion / exclusions
  22794. if (parsedLight.excludedMeshesIds) {
  22795. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  22796. }
  22797. if (parsedLight.includedOnlyMeshesIds) {
  22798. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  22799. }
  22800. // Parent
  22801. if (parsedLight.parentId) {
  22802. light._waitingParentId = parsedLight.parentId;
  22803. }
  22804. // Animations
  22805. if (parsedLight.animations) {
  22806. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  22807. var parsedAnimation = parsedLight.animations[animationIndex];
  22808. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22809. }
  22810. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  22811. }
  22812. if (parsedLight.autoAnimate) {
  22813. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  22814. }
  22815. return light;
  22816. };
  22817. Light.prototype._hookArrayForExcluded = function (array) {
  22818. var _this = this;
  22819. var oldPush = array.push;
  22820. array.push = function () {
  22821. var items = [];
  22822. for (var _i = 0; _i < arguments.length; _i++) {
  22823. items[_i] = arguments[_i];
  22824. }
  22825. var result = oldPush.apply(array, items);
  22826. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  22827. var item = items_1[_a];
  22828. item._resyncLighSource(_this);
  22829. }
  22830. return result;
  22831. };
  22832. var oldSplice = array.splice;
  22833. array.splice = function (index, deleteCount) {
  22834. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22835. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  22836. var item = deleted_1[_i];
  22837. item._resyncLighSource(_this);
  22838. }
  22839. return deleted;
  22840. };
  22841. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  22842. var item = array_1[_i];
  22843. item._resyncLighSource(this);
  22844. }
  22845. };
  22846. Light.prototype._hookArrayForIncludedOnly = function (array) {
  22847. var _this = this;
  22848. var oldPush = array.push;
  22849. array.push = function () {
  22850. var items = [];
  22851. for (var _i = 0; _i < arguments.length; _i++) {
  22852. items[_i] = arguments[_i];
  22853. }
  22854. var result = oldPush.apply(array, items);
  22855. _this._resyncMeshes();
  22856. return result;
  22857. };
  22858. var oldSplice = array.splice;
  22859. array.splice = function (index, deleteCount) {
  22860. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22861. _this._resyncMeshes();
  22862. return deleted;
  22863. };
  22864. this._resyncMeshes();
  22865. };
  22866. Light.prototype._resyncMeshes = function () {
  22867. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22868. var mesh = _a[_i];
  22869. mesh._resyncLighSource(this);
  22870. }
  22871. };
  22872. /**
  22873. * Forces the meshes to update their light related information in their rendering used effects
  22874. * @hidden Internal Use Only
  22875. */
  22876. Light.prototype._markMeshesAsLightDirty = function () {
  22877. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22878. var mesh = _a[_i];
  22879. if (mesh._lightSources.indexOf(this) !== -1) {
  22880. mesh._markSubMeshesAsLightDirty();
  22881. }
  22882. }
  22883. };
  22884. /**
  22885. * Recomputes the cached photometric scale if needed.
  22886. */
  22887. Light.prototype._computePhotometricScale = function () {
  22888. this._photometricScale = this._getPhotometricScale();
  22889. this.getScene().resetCachedMaterial();
  22890. };
  22891. /**
  22892. * Returns the Photometric Scale according to the light type and intensity mode.
  22893. */
  22894. Light.prototype._getPhotometricScale = function () {
  22895. var photometricScale = 0.0;
  22896. var lightTypeID = this.getTypeID();
  22897. //get photometric mode
  22898. var photometricMode = this.intensityMode;
  22899. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  22900. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  22901. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  22902. }
  22903. else {
  22904. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  22905. }
  22906. }
  22907. //compute photometric scale
  22908. switch (lightTypeID) {
  22909. case Light.LIGHTTYPEID_POINTLIGHT:
  22910. case Light.LIGHTTYPEID_SPOTLIGHT:
  22911. switch (photometricMode) {
  22912. case Light.INTENSITYMODE_LUMINOUSPOWER:
  22913. photometricScale = 1.0 / (4.0 * Math.PI);
  22914. break;
  22915. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  22916. photometricScale = 1.0;
  22917. break;
  22918. case Light.INTENSITYMODE_LUMINANCE:
  22919. photometricScale = this.radius * this.radius;
  22920. break;
  22921. }
  22922. break;
  22923. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  22924. switch (photometricMode) {
  22925. case Light.INTENSITYMODE_ILLUMINANCE:
  22926. photometricScale = 1.0;
  22927. break;
  22928. case Light.INTENSITYMODE_LUMINANCE:
  22929. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  22930. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  22931. var apexAngleRadians = this.radius;
  22932. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  22933. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  22934. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  22935. photometricScale = solidAngle;
  22936. break;
  22937. }
  22938. break;
  22939. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  22940. // No fall off in hemisperic light.
  22941. photometricScale = 1.0;
  22942. break;
  22943. }
  22944. return photometricScale;
  22945. };
  22946. /**
  22947. * Reorder the light in the scene according to their defined priority.
  22948. * @hidden Internal Use Only
  22949. */
  22950. Light.prototype._reorderLightsInScene = function () {
  22951. var scene = this.getScene();
  22952. if (this._renderPriority != 0) {
  22953. scene.requireLightSorting = true;
  22954. }
  22955. this.getScene().sortLightsByPriority();
  22956. };
  22957. /**
  22958. * Falloff Default: light is falling off following the material specification:
  22959. * standard material is using standard falloff whereas pbr material can request special falloff per materials.
  22960. */
  22961. Light.FALLOFF_DEFAULT = 0;
  22962. /**
  22963. * Falloff Physical: light is falling off following the inverse squared distance law.
  22964. */
  22965. Light.FALLOFF_PHYSICAL = 1;
  22966. /**
  22967. * Falloff gltf: light is falling off as described in the gltf moving to PBR document
  22968. * to enhance interoperability with other engines.
  22969. */
  22970. Light.FALLOFF_GLTF = 2;
  22971. /**
  22972. * Falloff Standard: light is falling off like in the standard material
  22973. * to enhance interoperability with other materials.
  22974. */
  22975. Light.FALLOFF_STANDARD = 3;
  22976. //lightmapMode Consts
  22977. /**
  22978. * If every light affecting the material is in this lightmapMode,
  22979. * material.lightmapTexture adds or multiplies
  22980. * (depends on material.useLightmapAsShadowmap)
  22981. * after every other light calculations.
  22982. */
  22983. Light.LIGHTMAP_DEFAULT = 0;
  22984. /**
  22985. * material.lightmapTexture as only diffuse lighting from this light
  22986. * adds only specular lighting from this light
  22987. * adds dynamic shadows
  22988. */
  22989. Light.LIGHTMAP_SPECULAR = 1;
  22990. /**
  22991. * material.lightmapTexture as only lighting
  22992. * no light calculation from this light
  22993. * only adds dynamic shadows from this light
  22994. */
  22995. Light.LIGHTMAP_SHADOWSONLY = 2;
  22996. // Intensity Mode Consts
  22997. /**
  22998. * Each light type uses the default quantity according to its type:
  22999. * point/spot lights use luminous intensity
  23000. * directional lights use illuminance
  23001. */
  23002. Light.INTENSITYMODE_AUTOMATIC = 0;
  23003. /**
  23004. * lumen (lm)
  23005. */
  23006. Light.INTENSITYMODE_LUMINOUSPOWER = 1;
  23007. /**
  23008. * candela (lm/sr)
  23009. */
  23010. Light.INTENSITYMODE_LUMINOUSINTENSITY = 2;
  23011. /**
  23012. * lux (lm/m^2)
  23013. */
  23014. Light.INTENSITYMODE_ILLUMINANCE = 3;
  23015. /**
  23016. * nit (cd/m^2)
  23017. */
  23018. Light.INTENSITYMODE_LUMINANCE = 4;
  23019. // Light types ids const.
  23020. /**
  23021. * Light type const id of the point light.
  23022. */
  23023. Light.LIGHTTYPEID_POINTLIGHT = 0;
  23024. /**
  23025. * Light type const id of the directional light.
  23026. */
  23027. Light.LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  23028. /**
  23029. * Light type const id of the spot light.
  23030. */
  23031. Light.LIGHTTYPEID_SPOTLIGHT = 2;
  23032. /**
  23033. * Light type const id of the hemispheric light.
  23034. */
  23035. Light.LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  23036. __decorate([
  23037. BABYLON.serializeAsColor3()
  23038. ], Light.prototype, "diffuse", void 0);
  23039. __decorate([
  23040. BABYLON.serializeAsColor3()
  23041. ], Light.prototype, "specular", void 0);
  23042. __decorate([
  23043. BABYLON.serialize()
  23044. ], Light.prototype, "falloffType", void 0);
  23045. __decorate([
  23046. BABYLON.serialize()
  23047. ], Light.prototype, "intensity", void 0);
  23048. __decorate([
  23049. BABYLON.serialize()
  23050. ], Light.prototype, "range", null);
  23051. __decorate([
  23052. BABYLON.serialize()
  23053. ], Light.prototype, "intensityMode", null);
  23054. __decorate([
  23055. BABYLON.serialize()
  23056. ], Light.prototype, "radius", null);
  23057. __decorate([
  23058. BABYLON.serialize()
  23059. ], Light.prototype, "_renderPriority", void 0);
  23060. __decorate([
  23061. BABYLON.expandToProperty("_reorderLightsInScene")
  23062. ], Light.prototype, "renderPriority", void 0);
  23063. __decorate([
  23064. BABYLON.serialize("shadowEnabled")
  23065. ], Light.prototype, "_shadowEnabled", void 0);
  23066. __decorate([
  23067. BABYLON.serialize("excludeWithLayerMask")
  23068. ], Light.prototype, "_excludeWithLayerMask", void 0);
  23069. __decorate([
  23070. BABYLON.serialize("includeOnlyWithLayerMask")
  23071. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  23072. __decorate([
  23073. BABYLON.serialize("lightmapMode")
  23074. ], Light.prototype, "_lightmapMode", void 0);
  23075. return Light;
  23076. }(BABYLON.Node));
  23077. BABYLON.Light = Light;
  23078. })(BABYLON || (BABYLON = {}));
  23079. //# sourceMappingURL=babylon.light.js.map
  23080. var BABYLON;
  23081. (function (BABYLON) {
  23082. /**
  23083. * This is the base class of all the camera used in the application.
  23084. * @see http://doc.babylonjs.com/features/cameras
  23085. */
  23086. var Camera = /** @class */ (function (_super) {
  23087. __extends(Camera, _super);
  23088. /**
  23089. * Instantiates a new camera object.
  23090. * This should not be used directly but through the inherited cameras: ArcRotate, Free...
  23091. * @see http://doc.babylonjs.com/features/cameras
  23092. * @param name Defines the name of the camera in the scene
  23093. * @param position Defines the position of the camera
  23094. * @param scene Defines the scene the camera belongs too
  23095. * @param setActiveOnSceneIfNoneActive Defines if the camera should be set as active after creation if no other camera have been defined in the scene
  23096. */
  23097. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  23098. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  23099. var _this = _super.call(this, name, scene) || this;
  23100. /**
  23101. * The vector the camera should consider as up.
  23102. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  23103. */
  23104. _this.upVector = BABYLON.Vector3.Up();
  23105. /**
  23106. * Define the current limit on the left side for an orthographic camera
  23107. * In scene unit
  23108. */
  23109. _this.orthoLeft = null;
  23110. /**
  23111. * Define the current limit on the right side for an orthographic camera
  23112. * In scene unit
  23113. */
  23114. _this.orthoRight = null;
  23115. /**
  23116. * Define the current limit on the bottom side for an orthographic camera
  23117. * In scene unit
  23118. */
  23119. _this.orthoBottom = null;
  23120. /**
  23121. * Define the current limit on the top side for an orthographic camera
  23122. * In scene unit
  23123. */
  23124. _this.orthoTop = null;
  23125. /**
  23126. * Field Of View is set in Radians. (default is 0.8)
  23127. */
  23128. _this.fov = 0.8;
  23129. /**
  23130. * Define the minimum distance the camera can see from.
  23131. * This is important to note that the depth buffer are not infinite and the closer it starts
  23132. * the more your scene might encounter depth fighting issue.
  23133. */
  23134. _this.minZ = 1;
  23135. /**
  23136. * Define the maximum distance the camera can see to.
  23137. * This is important to note that the depth buffer are not infinite and the further it end
  23138. * the more your scene might encounter depth fighting issue.
  23139. */
  23140. _this.maxZ = 10000.0;
  23141. /**
  23142. * Define the default inertia of the camera.
  23143. * This helps giving a smooth feeling to the camera movement.
  23144. */
  23145. _this.inertia = 0.9;
  23146. /**
  23147. * Define the mode of the camera (Camera.PERSPECTIVE_CAMERA or Camera.PERSPECTIVE_ORTHOGRAPHIC)
  23148. */
  23149. _this.mode = Camera.PERSPECTIVE_CAMERA;
  23150. /**
  23151. * Define wether the camera is intermediate.
  23152. * This is usefull to not present the output directly to the screen in case of rig without post process for instance
  23153. */
  23154. _this.isIntermediate = false;
  23155. /**
  23156. * Define the viewport of the camera.
  23157. * This correspond to the portion of the screen the camera will render to in normalized 0 to 1 unit.
  23158. */
  23159. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  23160. /**
  23161. * Restricts the camera to viewing objects with the same layerMask.
  23162. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  23163. */
  23164. _this.layerMask = 0x0FFFFFFF;
  23165. /**
  23166. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  23167. */
  23168. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  23169. /**
  23170. * Rig mode of the camera.
  23171. * This is usefull to create the camera with two "eyes" instead of one to create VR or stereoscopic scenes.
  23172. * This is normally controlled byt the camera themselves as internal use.
  23173. */
  23174. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  23175. /**
  23176. * Defines the list of custom render target the camera should render to.
  23177. * This is pretty helpfull if you wish to make a camera render to a texture you could reuse somewhere
  23178. * else in the scene.
  23179. */
  23180. _this.customRenderTargets = new Array();
  23181. /**
  23182. * Observable triggered when the camera view matrix has changed.
  23183. */
  23184. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  23185. /**
  23186. * Observable triggered when the camera Projection matrix has changed.
  23187. */
  23188. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  23189. /**
  23190. * Observable triggered when the inputs have been processed.
  23191. */
  23192. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  23193. /**
  23194. * Observable triggered when reset has been called and applied to the camera.
  23195. */
  23196. _this.onRestoreStateObservable = new BABYLON.Observable();
  23197. /** @hidden */
  23198. _this._rigCameras = new Array();
  23199. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  23200. /** @hidden */
  23201. _this._skipRendering = false;
  23202. /** @hidden */
  23203. _this._projectionMatrix = new BABYLON.Matrix();
  23204. /** @hidden */
  23205. _this._postProcesses = new Array();
  23206. /** @hidden */
  23207. _this._activeMeshes = new BABYLON.SmartArray(256);
  23208. _this._globalPosition = BABYLON.Vector3.Zero();
  23209. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  23210. _this._doNotComputeProjectionMatrix = false;
  23211. _this._transformMatrix = BABYLON.Matrix.Zero();
  23212. _this._refreshFrustumPlanes = true;
  23213. _this.getScene().addCamera(_this);
  23214. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  23215. _this.getScene().activeCamera = _this;
  23216. }
  23217. _this.position = position;
  23218. return _this;
  23219. }
  23220. /**
  23221. * Store current camera state (fov, position, etc..)
  23222. * @returns the camera
  23223. */
  23224. Camera.prototype.storeState = function () {
  23225. this._stateStored = true;
  23226. this._storedFov = this.fov;
  23227. return this;
  23228. };
  23229. /**
  23230. * Restores the camera state values if it has been stored. You must call storeState() first
  23231. */
  23232. Camera.prototype._restoreStateValues = function () {
  23233. if (!this._stateStored) {
  23234. return false;
  23235. }
  23236. this.fov = this._storedFov;
  23237. return true;
  23238. };
  23239. /**
  23240. * Restored camera state. You must call storeState() first.
  23241. * @returns true if restored and false otherwise
  23242. */
  23243. Camera.prototype.restoreState = function () {
  23244. if (this._restoreStateValues()) {
  23245. this.onRestoreStateObservable.notifyObservers(this);
  23246. return true;
  23247. }
  23248. return false;
  23249. };
  23250. /**
  23251. * Gets the class name of the camera.
  23252. * @returns the class name
  23253. */
  23254. Camera.prototype.getClassName = function () {
  23255. return "Camera";
  23256. };
  23257. /**
  23258. * Gets a string representation of the camera usefull for debug purpose.
  23259. * @param fullDetails Defines that a more verboe level of logging is required
  23260. * @returns the string representation
  23261. */
  23262. Camera.prototype.toString = function (fullDetails) {
  23263. var ret = "Name: " + this.name;
  23264. ret += ", type: " + this.getClassName();
  23265. if (this.animations) {
  23266. for (var i = 0; i < this.animations.length; i++) {
  23267. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  23268. }
  23269. }
  23270. if (fullDetails) {
  23271. }
  23272. return ret;
  23273. };
  23274. Object.defineProperty(Camera.prototype, "globalPosition", {
  23275. /**
  23276. * Gets the current world space position of the camera.
  23277. */
  23278. get: function () {
  23279. return this._globalPosition;
  23280. },
  23281. enumerable: true,
  23282. configurable: true
  23283. });
  23284. /**
  23285. * Gets the list of active meshes this frame (meshes no culled or excluded by lod s in the frame)
  23286. * @returns the active meshe list
  23287. */
  23288. Camera.prototype.getActiveMeshes = function () {
  23289. return this._activeMeshes;
  23290. };
  23291. /**
  23292. * Check wether a mesh is part of the current active mesh list of the camera
  23293. * @param mesh Defines the mesh to check
  23294. * @returns true if active, false otherwise
  23295. */
  23296. Camera.prototype.isActiveMesh = function (mesh) {
  23297. return (this._activeMeshes.indexOf(mesh) !== -1);
  23298. };
  23299. /**
  23300. * Is this camera ready to be used/rendered
  23301. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  23302. * @return true if the camera is ready
  23303. */
  23304. Camera.prototype.isReady = function (completeCheck) {
  23305. if (completeCheck === void 0) { completeCheck = false; }
  23306. if (completeCheck) {
  23307. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  23308. var pp = _a[_i];
  23309. if (pp && !pp.isReady()) {
  23310. return false;
  23311. }
  23312. }
  23313. }
  23314. return _super.prototype.isReady.call(this, completeCheck);
  23315. };
  23316. /** @hidden */
  23317. Camera.prototype._initCache = function () {
  23318. _super.prototype._initCache.call(this);
  23319. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  23320. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  23321. this._cache.mode = undefined;
  23322. this._cache.minZ = undefined;
  23323. this._cache.maxZ = undefined;
  23324. this._cache.fov = undefined;
  23325. this._cache.fovMode = undefined;
  23326. this._cache.aspectRatio = undefined;
  23327. this._cache.orthoLeft = undefined;
  23328. this._cache.orthoRight = undefined;
  23329. this._cache.orthoBottom = undefined;
  23330. this._cache.orthoTop = undefined;
  23331. this._cache.renderWidth = undefined;
  23332. this._cache.renderHeight = undefined;
  23333. };
  23334. /** @hidden */
  23335. Camera.prototype._updateCache = function (ignoreParentClass) {
  23336. if (!ignoreParentClass) {
  23337. _super.prototype._updateCache.call(this);
  23338. }
  23339. this._cache.position.copyFrom(this.position);
  23340. this._cache.upVector.copyFrom(this.upVector);
  23341. };
  23342. /** @hidden */
  23343. Camera.prototype._isSynchronized = function () {
  23344. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  23345. };
  23346. /** @hidden */
  23347. Camera.prototype._isSynchronizedViewMatrix = function () {
  23348. if (!_super.prototype._isSynchronized.call(this))
  23349. return false;
  23350. return this._cache.position.equals(this.position)
  23351. && this._cache.upVector.equals(this.upVector)
  23352. && this.isSynchronizedWithParent();
  23353. };
  23354. /** @hidden */
  23355. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  23356. var check = this._cache.mode === this.mode
  23357. && this._cache.minZ === this.minZ
  23358. && this._cache.maxZ === this.maxZ;
  23359. if (!check) {
  23360. return false;
  23361. }
  23362. var engine = this.getEngine();
  23363. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  23364. check = this._cache.fov === this.fov
  23365. && this._cache.fovMode === this.fovMode
  23366. && this._cache.aspectRatio === engine.getAspectRatio(this);
  23367. }
  23368. else {
  23369. check = this._cache.orthoLeft === this.orthoLeft
  23370. && this._cache.orthoRight === this.orthoRight
  23371. && this._cache.orthoBottom === this.orthoBottom
  23372. && this._cache.orthoTop === this.orthoTop
  23373. && this._cache.renderWidth === engine.getRenderWidth()
  23374. && this._cache.renderHeight === engine.getRenderHeight();
  23375. }
  23376. return check;
  23377. };
  23378. /**
  23379. * Attach the input controls to a specific dom element to get the input from.
  23380. * @param element Defines the element the controls should be listened from
  23381. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  23382. */
  23383. Camera.prototype.attachControl = function (element, noPreventDefault) {
  23384. };
  23385. /**
  23386. * Detach the current controls from the specified dom element.
  23387. * @param element Defines the element to stop listening the inputs from
  23388. */
  23389. Camera.prototype.detachControl = function (element) {
  23390. };
  23391. /**
  23392. * Update the camera state according to the different inputs gathered during the frame.
  23393. */
  23394. Camera.prototype.update = function () {
  23395. this._checkInputs();
  23396. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  23397. this._updateRigCameras();
  23398. }
  23399. };
  23400. /** @hidden */
  23401. Camera.prototype._checkInputs = function () {
  23402. this.onAfterCheckInputsObservable.notifyObservers(this);
  23403. };
  23404. Object.defineProperty(Camera.prototype, "rigCameras", {
  23405. /** @hidden */
  23406. get: function () {
  23407. return this._rigCameras;
  23408. },
  23409. enumerable: true,
  23410. configurable: true
  23411. });
  23412. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  23413. /**
  23414. * Gets the post process used by the rig cameras
  23415. */
  23416. get: function () {
  23417. return this._rigPostProcess;
  23418. },
  23419. enumerable: true,
  23420. configurable: true
  23421. });
  23422. /**
  23423. * Internal, gets the first post proces.
  23424. * @returns the first post process to be run on this camera.
  23425. */
  23426. Camera.prototype._getFirstPostProcess = function () {
  23427. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  23428. if (this._postProcesses[ppIndex] !== null) {
  23429. return this._postProcesses[ppIndex];
  23430. }
  23431. }
  23432. return null;
  23433. };
  23434. Camera.prototype._cascadePostProcessesToRigCams = function () {
  23435. // invalidate framebuffer
  23436. var firstPostProcess = this._getFirstPostProcess();
  23437. if (firstPostProcess) {
  23438. firstPostProcess.markTextureDirty();
  23439. }
  23440. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  23441. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  23442. var cam = this._rigCameras[i];
  23443. var rigPostProcess = cam._rigPostProcess;
  23444. // for VR rig, there does not have to be a post process
  23445. if (rigPostProcess) {
  23446. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  23447. if (isPass) {
  23448. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  23449. cam.isIntermediate = this._postProcesses.length === 0;
  23450. }
  23451. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  23452. rigPostProcess.markTextureDirty();
  23453. }
  23454. else {
  23455. cam._postProcesses = this._postProcesses.slice(0);
  23456. }
  23457. }
  23458. };
  23459. /**
  23460. * Attach a post process to the camera.
  23461. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocesses#attach-postprocess
  23462. * @param postProcess The post process to attach to the camera
  23463. * @param insertAt The position of the post process in case several of them are in use in the scene
  23464. * @returns the position the post process has been inserted at
  23465. */
  23466. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  23467. if (insertAt === void 0) { insertAt = null; }
  23468. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  23469. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  23470. return 0;
  23471. }
  23472. if (insertAt == null || insertAt < 0) {
  23473. this._postProcesses.push(postProcess);
  23474. }
  23475. else if (this._postProcesses[insertAt] === null) {
  23476. this._postProcesses[insertAt] = postProcess;
  23477. }
  23478. else {
  23479. this._postProcesses.splice(insertAt, 0, postProcess);
  23480. }
  23481. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  23482. return this._postProcesses.indexOf(postProcess);
  23483. };
  23484. /**
  23485. * Detach a post process to the camera.
  23486. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocesses#attach-postprocess
  23487. * @param postProcess The post process to detach from the camera
  23488. */
  23489. Camera.prototype.detachPostProcess = function (postProcess) {
  23490. var idx = this._postProcesses.indexOf(postProcess);
  23491. if (idx !== -1) {
  23492. this._postProcesses[idx] = null;
  23493. }
  23494. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  23495. };
  23496. /**
  23497. * Gets the current world matrix of the camera
  23498. */
  23499. Camera.prototype.getWorldMatrix = function () {
  23500. if (this._isSynchronizedViewMatrix()) {
  23501. return this._worldMatrix;
  23502. }
  23503. // Getting the the view matrix will also compute the world matrix.
  23504. this.getViewMatrix();
  23505. return this._worldMatrix;
  23506. };
  23507. /** @hidden */
  23508. Camera.prototype._getViewMatrix = function () {
  23509. return BABYLON.Matrix.Identity();
  23510. };
  23511. /**
  23512. * Gets the current view matrix of the camera.
  23513. * @param force forces the camera to recompute the matrix without looking at the cached state
  23514. * @returns the view matrix
  23515. */
  23516. Camera.prototype.getViewMatrix = function (force) {
  23517. if (!force && this._isSynchronizedViewMatrix()) {
  23518. return this._computedViewMatrix;
  23519. }
  23520. this.updateCache();
  23521. this._computedViewMatrix = this._getViewMatrix();
  23522. this._currentRenderId = this.getScene().getRenderId();
  23523. this._childRenderId = this._currentRenderId;
  23524. this._refreshFrustumPlanes = true;
  23525. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  23526. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  23527. }
  23528. this.onViewMatrixChangedObservable.notifyObservers(this);
  23529. this._computedViewMatrix.invertToRef(this._worldMatrix);
  23530. return this._computedViewMatrix;
  23531. };
  23532. /**
  23533. * Freeze the projection matrix.
  23534. * It will prevent the cache check of the camera projection compute and can speed up perf
  23535. * if no parameter of the camera are meant to change
  23536. * @param projection Defines manually a projection if necessary
  23537. */
  23538. Camera.prototype.freezeProjectionMatrix = function (projection) {
  23539. this._doNotComputeProjectionMatrix = true;
  23540. if (projection !== undefined) {
  23541. this._projectionMatrix = projection;
  23542. }
  23543. };
  23544. ;
  23545. /**
  23546. * Unfreeze the projection matrix if it has previously been freezed by freezeProjectionMatrix.
  23547. */
  23548. Camera.prototype.unfreezeProjectionMatrix = function () {
  23549. this._doNotComputeProjectionMatrix = false;
  23550. };
  23551. ;
  23552. /**
  23553. * Gets the current projection matrix of the camera.
  23554. * @param force forces the camera to recompute the matrix without looking at the cached state
  23555. * @returns the projection matrix
  23556. */
  23557. Camera.prototype.getProjectionMatrix = function (force) {
  23558. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  23559. return this._projectionMatrix;
  23560. }
  23561. // Cache
  23562. this._cache.mode = this.mode;
  23563. this._cache.minZ = this.minZ;
  23564. this._cache.maxZ = this.maxZ;
  23565. // Matrix
  23566. this._refreshFrustumPlanes = true;
  23567. var engine = this.getEngine();
  23568. var scene = this.getScene();
  23569. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  23570. this._cache.fov = this.fov;
  23571. this._cache.fovMode = this.fovMode;
  23572. this._cache.aspectRatio = engine.getAspectRatio(this);
  23573. if (this.minZ <= 0) {
  23574. this.minZ = 0.1;
  23575. }
  23576. if (scene.useRightHandedSystem) {
  23577. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  23578. }
  23579. else {
  23580. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  23581. }
  23582. }
  23583. else {
  23584. var halfWidth = engine.getRenderWidth() / 2.0;
  23585. var halfHeight = engine.getRenderHeight() / 2.0;
  23586. if (scene.useRightHandedSystem) {
  23587. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  23588. }
  23589. else {
  23590. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  23591. }
  23592. this._cache.orthoLeft = this.orthoLeft;
  23593. this._cache.orthoRight = this.orthoRight;
  23594. this._cache.orthoBottom = this.orthoBottom;
  23595. this._cache.orthoTop = this.orthoTop;
  23596. this._cache.renderWidth = engine.getRenderWidth();
  23597. this._cache.renderHeight = engine.getRenderHeight();
  23598. }
  23599. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  23600. return this._projectionMatrix;
  23601. };
  23602. /**
  23603. * Gets the transformation matrix (ie. the multiplication of view by projection matrices)
  23604. * @returns a Matrix
  23605. */
  23606. Camera.prototype.getTransformationMatrix = function () {
  23607. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  23608. return this._transformMatrix;
  23609. };
  23610. Camera.prototype._updateFrustumPlanes = function () {
  23611. if (!this._refreshFrustumPlanes) {
  23612. return;
  23613. }
  23614. this.getTransformationMatrix();
  23615. if (!this._frustumPlanes) {
  23616. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  23617. }
  23618. else {
  23619. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  23620. }
  23621. this._refreshFrustumPlanes = false;
  23622. };
  23623. /**
  23624. * Checks if a cullable object (mesh...) is in the camera frustum
  23625. * This checks the bounding box center. See isCompletelyInFrustum for a full bounding check
  23626. * @param target The object to check
  23627. * @returns true if the object is in frustum otherwise false
  23628. */
  23629. Camera.prototype.isInFrustum = function (target) {
  23630. this._updateFrustumPlanes();
  23631. return target.isInFrustum(this._frustumPlanes);
  23632. };
  23633. /**
  23634. * Checks if a cullable object (mesh...) is in the camera frustum
  23635. * Unlike isInFrustum this cheks the full bounding box
  23636. * @param target The object to check
  23637. * @returns true if the object is in frustum otherwise false
  23638. */
  23639. Camera.prototype.isCompletelyInFrustum = function (target) {
  23640. this._updateFrustumPlanes();
  23641. return target.isCompletelyInFrustum(this._frustumPlanes);
  23642. };
  23643. /**
  23644. * Gets a ray in the forward direction from the camera.
  23645. * @param length Defines the length of the ray to create
  23646. * @param transform Defines the transform to apply to the ray, by default the world matrx is used to create a workd space ray
  23647. * @param origin Defines the start point of the ray which defaults to the camera position
  23648. * @returns the forward ray
  23649. */
  23650. Camera.prototype.getForwardRay = function (length, transform, origin) {
  23651. if (length === void 0) { length = 100; }
  23652. if (!transform) {
  23653. transform = this.getWorldMatrix();
  23654. }
  23655. if (!origin) {
  23656. origin = this.position;
  23657. }
  23658. var forward = this._scene.useRightHandedSystem ? new BABYLON.Vector3(0, 0, -1) : new BABYLON.Vector3(0, 0, 1);
  23659. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  23660. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  23661. return new BABYLON.Ray(origin, direction, length);
  23662. };
  23663. /**
  23664. * Releases resources associated with this node.
  23665. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  23666. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  23667. */
  23668. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  23669. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  23670. // Observables
  23671. this.onViewMatrixChangedObservable.clear();
  23672. this.onProjectionMatrixChangedObservable.clear();
  23673. this.onAfterCheckInputsObservable.clear();
  23674. this.onRestoreStateObservable.clear();
  23675. // Inputs
  23676. if (this.inputs) {
  23677. this.inputs.clear();
  23678. }
  23679. // Animations
  23680. this.getScene().stopAnimation(this);
  23681. // Remove from scene
  23682. this.getScene().removeCamera(this);
  23683. while (this._rigCameras.length > 0) {
  23684. var camera = this._rigCameras.pop();
  23685. if (camera) {
  23686. camera.dispose();
  23687. }
  23688. }
  23689. // Postprocesses
  23690. if (this._rigPostProcess) {
  23691. this._rigPostProcess.dispose(this);
  23692. this._rigPostProcess = null;
  23693. this._postProcesses = [];
  23694. }
  23695. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  23696. this._rigPostProcess = null;
  23697. this._postProcesses = [];
  23698. }
  23699. else {
  23700. var i = this._postProcesses.length;
  23701. while (--i >= 0) {
  23702. var postProcess = this._postProcesses[i];
  23703. if (postProcess) {
  23704. postProcess.dispose(this);
  23705. }
  23706. }
  23707. }
  23708. // Render targets
  23709. var i = this.customRenderTargets.length;
  23710. while (--i >= 0) {
  23711. this.customRenderTargets[i].dispose();
  23712. }
  23713. this.customRenderTargets = [];
  23714. // Active Meshes
  23715. this._activeMeshes.dispose();
  23716. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  23717. };
  23718. Object.defineProperty(Camera.prototype, "leftCamera", {
  23719. /**
  23720. * Gets the left camera of a rig setup in case of Rigged Camera
  23721. */
  23722. get: function () {
  23723. if (this._rigCameras.length < 1) {
  23724. return null;
  23725. }
  23726. return this._rigCameras[0];
  23727. },
  23728. enumerable: true,
  23729. configurable: true
  23730. });
  23731. Object.defineProperty(Camera.prototype, "rightCamera", {
  23732. /**
  23733. * Gets the right camera of a rig setup in case of Rigged Camera
  23734. */
  23735. get: function () {
  23736. if (this._rigCameras.length < 2) {
  23737. return null;
  23738. }
  23739. return this._rigCameras[1];
  23740. },
  23741. enumerable: true,
  23742. configurable: true
  23743. });
  23744. /**
  23745. * Gets the left camera target of a rig setup in case of Rigged Camera
  23746. * @returns the target position
  23747. */
  23748. Camera.prototype.getLeftTarget = function () {
  23749. if (this._rigCameras.length < 1) {
  23750. return null;
  23751. }
  23752. return this._rigCameras[0].getTarget();
  23753. };
  23754. /**
  23755. * Gets the right camera target of a rig setup in case of Rigged Camera
  23756. * @returns the target position
  23757. */
  23758. Camera.prototype.getRightTarget = function () {
  23759. if (this._rigCameras.length < 2) {
  23760. return null;
  23761. }
  23762. return this._rigCameras[1].getTarget();
  23763. };
  23764. /**
  23765. * @hidden
  23766. */
  23767. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  23768. if (this.cameraRigMode === mode) {
  23769. return;
  23770. }
  23771. while (this._rigCameras.length > 0) {
  23772. var camera = this._rigCameras.pop();
  23773. if (camera) {
  23774. camera.dispose();
  23775. }
  23776. }
  23777. this.cameraRigMode = mode;
  23778. this._cameraRigParams = {};
  23779. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  23780. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  23781. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  23782. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  23783. // create the rig cameras, unless none
  23784. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  23785. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  23786. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  23787. if (leftCamera && rightCamera) {
  23788. this._rigCameras.push(leftCamera);
  23789. this._rigCameras.push(rightCamera);
  23790. }
  23791. }
  23792. switch (this.cameraRigMode) {
  23793. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  23794. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  23795. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  23796. break;
  23797. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  23798. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  23799. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  23800. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  23801. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  23802. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  23803. break;
  23804. case Camera.RIG_MODE_VR:
  23805. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  23806. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  23807. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  23808. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23809. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  23810. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  23811. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  23812. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  23813. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  23814. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23815. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  23816. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  23817. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  23818. if (metrics.compensateDistortion) {
  23819. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  23820. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  23821. }
  23822. break;
  23823. case Camera.RIG_MODE_WEBVR:
  23824. if (rigParams.vrDisplay) {
  23825. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  23826. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  23827. //Left eye
  23828. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  23829. this._rigCameras[0].setCameraRigParameter("left", true);
  23830. //leaving this for future reference
  23831. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  23832. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  23833. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  23834. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  23835. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23836. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  23837. this._rigCameras[0].parent = this;
  23838. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  23839. //Right eye
  23840. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  23841. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  23842. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  23843. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  23844. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  23845. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23846. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  23847. this._rigCameras[1].parent = this;
  23848. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  23849. if (Camera.UseAlternateWebVRRendering) {
  23850. this._rigCameras[1]._skipRendering = true;
  23851. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  23852. }
  23853. }
  23854. break;
  23855. }
  23856. this._cascadePostProcessesToRigCams();
  23857. this.update();
  23858. };
  23859. Camera.prototype._getVRProjectionMatrix = function () {
  23860. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  23861. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  23862. return this._projectionMatrix;
  23863. };
  23864. Camera.prototype._updateCameraRotationMatrix = function () {
  23865. //Here for WebVR
  23866. };
  23867. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  23868. //Here for WebVR
  23869. };
  23870. /**
  23871. * This function MUST be overwritten by the different WebVR cameras available.
  23872. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  23873. */
  23874. Camera.prototype._getWebVRProjectionMatrix = function () {
  23875. return BABYLON.Matrix.Identity();
  23876. };
  23877. /**
  23878. * This function MUST be overwritten by the different WebVR cameras available.
  23879. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  23880. */
  23881. Camera.prototype._getWebVRViewMatrix = function () {
  23882. return BABYLON.Matrix.Identity();
  23883. };
  23884. /** @hidden */
  23885. Camera.prototype.setCameraRigParameter = function (name, value) {
  23886. if (!this._cameraRigParams) {
  23887. this._cameraRigParams = {};
  23888. }
  23889. this._cameraRigParams[name] = value;
  23890. //provisionnally:
  23891. if (name === "interaxialDistance") {
  23892. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  23893. }
  23894. };
  23895. /**
  23896. * needs to be overridden by children so sub has required properties to be copied
  23897. * @hidden
  23898. */
  23899. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  23900. return null;
  23901. };
  23902. /**
  23903. * May need to be overridden by children
  23904. * @hidden
  23905. */
  23906. Camera.prototype._updateRigCameras = function () {
  23907. for (var i = 0; i < this._rigCameras.length; i++) {
  23908. this._rigCameras[i].minZ = this.minZ;
  23909. this._rigCameras[i].maxZ = this.maxZ;
  23910. this._rigCameras[i].fov = this.fov;
  23911. }
  23912. // only update viewport when ANAGLYPH
  23913. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  23914. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  23915. }
  23916. };
  23917. /** @hidden */
  23918. Camera.prototype._setupInputs = function () {
  23919. };
  23920. /**
  23921. * Serialiaze the camera setup to a json represention
  23922. * @returns the JSON representation
  23923. */
  23924. Camera.prototype.serialize = function () {
  23925. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  23926. // Type
  23927. serializationObject.type = this.getClassName();
  23928. // Parent
  23929. if (this.parent) {
  23930. serializationObject.parentId = this.parent.id;
  23931. }
  23932. if (this.inputs) {
  23933. this.inputs.serialize(serializationObject);
  23934. }
  23935. // Animations
  23936. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  23937. serializationObject.ranges = this.serializeAnimationRanges();
  23938. return serializationObject;
  23939. };
  23940. /**
  23941. * Clones the current camera.
  23942. * @param name The cloned camera name
  23943. * @returns the cloned camera
  23944. */
  23945. Camera.prototype.clone = function (name) {
  23946. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  23947. };
  23948. /**
  23949. * Gets the direction of the camera relative to a given local axis.
  23950. * @param localAxis Defines the reference axis to provide a relative direction.
  23951. * @return the direction
  23952. */
  23953. Camera.prototype.getDirection = function (localAxis) {
  23954. var result = BABYLON.Vector3.Zero();
  23955. this.getDirectionToRef(localAxis, result);
  23956. return result;
  23957. };
  23958. /**
  23959. * Gets the direction of the camera relative to a given local axis into a passed vector.
  23960. * @param localAxis Defines the reference axis to provide a relative direction.
  23961. * @param result Defines the vector to store the result in
  23962. */
  23963. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  23964. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  23965. };
  23966. /**
  23967. * Gets a camera constructor for a given camera type
  23968. * @param type The type of the camera to construct (should be equal to one of the camera class name)
  23969. * @param name The name of the camera the result will be able to instantiate
  23970. * @param scene The scene the result will construct the camera in
  23971. * @param interaxial_distance In case of stereoscopic setup, the distance between both eyes
  23972. * @param isStereoscopicSideBySide In case of stereoscopic setup, should the sereo be side b side
  23973. * @returns a factory method to construc the camera
  23974. */
  23975. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  23976. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  23977. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  23978. var constructorFunc = BABYLON.Node.Construct(type, name, scene, {
  23979. interaxial_distance: interaxial_distance,
  23980. isStereoscopicSideBySide: isStereoscopicSideBySide
  23981. });
  23982. if (constructorFunc) {
  23983. return constructorFunc;
  23984. }
  23985. // Default to universal camera
  23986. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  23987. };
  23988. /**
  23989. * Compute the world matrix of the camera.
  23990. * @returns the camera workd matrix
  23991. */
  23992. Camera.prototype.computeWorldMatrix = function () {
  23993. return this.getWorldMatrix();
  23994. };
  23995. /**
  23996. * Parse a JSON and creates the camera from the parsed information
  23997. * @param parsedCamera The JSON to parse
  23998. * @param scene The scene to instantiate the camera in
  23999. * @returns the newly constructed camera
  24000. */
  24001. Camera.Parse = function (parsedCamera, scene) {
  24002. var type = parsedCamera.type;
  24003. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  24004. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  24005. // Parent
  24006. if (parsedCamera.parentId) {
  24007. camera._waitingParentId = parsedCamera.parentId;
  24008. }
  24009. //If camera has an input manager, let it parse inputs settings
  24010. if (camera.inputs) {
  24011. camera.inputs.parse(parsedCamera);
  24012. camera._setupInputs();
  24013. }
  24014. if (camera.setPosition) { // need to force position
  24015. camera.position.copyFromFloats(0, 0, 0);
  24016. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  24017. }
  24018. // Target
  24019. if (parsedCamera.target) {
  24020. if (camera.setTarget) {
  24021. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  24022. }
  24023. }
  24024. // Apply 3d rig, when found
  24025. if (parsedCamera.cameraRigMode) {
  24026. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  24027. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  24028. }
  24029. // Animations
  24030. if (parsedCamera.animations) {
  24031. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  24032. var parsedAnimation = parsedCamera.animations[animationIndex];
  24033. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  24034. }
  24035. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  24036. }
  24037. if (parsedCamera.autoAnimate) {
  24038. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  24039. }
  24040. return camera;
  24041. };
  24042. /**
  24043. * This is the default projection mode used by the cameras.
  24044. * It helps recreating a feeling of perspective and better appreciate depth.
  24045. * This is the best way to simulate real life cameras.
  24046. */
  24047. Camera.PERSPECTIVE_CAMERA = 0;
  24048. /**
  24049. * This helps creating camera with an orthographic mode.
  24050. * Orthographic is commonly used in engineering as a means to produce object specifications that communicate dimensions unambiguously, each line of 1 unit length (cm, meter..whatever) will appear to have the same length everywhere on the drawing. This allows the drafter to dimension only a subset of lines and let the reader know that other lines of that length on the drawing are also that length in reality. Every parallel line in the drawing is also parallel in the object.
  24051. */
  24052. Camera.ORTHOGRAPHIC_CAMERA = 1;
  24053. /**
  24054. * This is the default FOV mode for perspective cameras.
  24055. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  24056. */
  24057. Camera.FOVMODE_VERTICAL_FIXED = 0;
  24058. /**
  24059. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  24060. */
  24061. Camera.FOVMODE_HORIZONTAL_FIXED = 1;
  24062. /**
  24063. * This specifies ther is no need for a camera rig.
  24064. * Basically only one eye is rendered corresponding to the camera.
  24065. */
  24066. Camera.RIG_MODE_NONE = 0;
  24067. /**
  24068. * Simulates a camera Rig with one blue eye and one red eye.
  24069. * This can be use with 3d blue and red glasses.
  24070. */
  24071. Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  24072. /**
  24073. * Defines that both eyes of the camera will be rendered side by side with a parallel target.
  24074. */
  24075. Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  24076. /**
  24077. * Defines that both eyes of the camera will be rendered side by side with a none parallel target.
  24078. */
  24079. Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  24080. /**
  24081. * Defines that both eyes of the camera will be rendered over under each other.
  24082. */
  24083. Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  24084. /**
  24085. * Defines that both eyes of the camera should be renderered in a VR mode (carbox).
  24086. */
  24087. Camera.RIG_MODE_VR = 20;
  24088. /**
  24089. * Defines that both eyes of the camera should be renderered in a VR mode (webVR).
  24090. */
  24091. Camera.RIG_MODE_WEBVR = 21;
  24092. /**
  24093. * Defines if by default attaching controls should prevent the default javascript event to continue.
  24094. */
  24095. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  24096. /**
  24097. * @hidden
  24098. * Might be removed once multiview will be a thing
  24099. */
  24100. Camera.UseAlternateWebVRRendering = false;
  24101. __decorate([
  24102. BABYLON.serializeAsVector3()
  24103. ], Camera.prototype, "position", void 0);
  24104. __decorate([
  24105. BABYLON.serializeAsVector3()
  24106. ], Camera.prototype, "upVector", void 0);
  24107. __decorate([
  24108. BABYLON.serialize()
  24109. ], Camera.prototype, "orthoLeft", void 0);
  24110. __decorate([
  24111. BABYLON.serialize()
  24112. ], Camera.prototype, "orthoRight", void 0);
  24113. __decorate([
  24114. BABYLON.serialize()
  24115. ], Camera.prototype, "orthoBottom", void 0);
  24116. __decorate([
  24117. BABYLON.serialize()
  24118. ], Camera.prototype, "orthoTop", void 0);
  24119. __decorate([
  24120. BABYLON.serialize()
  24121. ], Camera.prototype, "fov", void 0);
  24122. __decorate([
  24123. BABYLON.serialize()
  24124. ], Camera.prototype, "minZ", void 0);
  24125. __decorate([
  24126. BABYLON.serialize()
  24127. ], Camera.prototype, "maxZ", void 0);
  24128. __decorate([
  24129. BABYLON.serialize()
  24130. ], Camera.prototype, "inertia", void 0);
  24131. __decorate([
  24132. BABYLON.serialize()
  24133. ], Camera.prototype, "mode", void 0);
  24134. __decorate([
  24135. BABYLON.serialize()
  24136. ], Camera.prototype, "layerMask", void 0);
  24137. __decorate([
  24138. BABYLON.serialize()
  24139. ], Camera.prototype, "fovMode", void 0);
  24140. __decorate([
  24141. BABYLON.serialize()
  24142. ], Camera.prototype, "cameraRigMode", void 0);
  24143. __decorate([
  24144. BABYLON.serialize()
  24145. ], Camera.prototype, "interaxialDistance", void 0);
  24146. __decorate([
  24147. BABYLON.serialize()
  24148. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  24149. return Camera;
  24150. }(BABYLON.Node));
  24151. BABYLON.Camera = Camera;
  24152. })(BABYLON || (BABYLON = {}));
  24153. //# sourceMappingURL=babylon.camera.js.map
  24154. var BABYLON;
  24155. (function (BABYLON) {
  24156. /**
  24157. * This is the manager responsible of all the rendering for meshes sprites and particles.
  24158. * It is enable to manage the different groups as well as the different necessary sort functions.
  24159. * This should not be used directly aside of the few static configurations
  24160. */
  24161. var RenderingManager = /** @class */ (function () {
  24162. /**
  24163. * Instantiates a new rendering group for a particular scene
  24164. * @param scene Defines the scene the groups belongs to
  24165. */
  24166. function RenderingManager(scene) {
  24167. /**
  24168. * @hidden
  24169. */
  24170. this._useSceneAutoClearSetup = false;
  24171. this._renderingGroups = new Array();
  24172. this._autoClearDepthStencil = {};
  24173. this._customOpaqueSortCompareFn = {};
  24174. this._customAlphaTestSortCompareFn = {};
  24175. this._customTransparentSortCompareFn = {};
  24176. this._renderingGroupInfo = new BABYLON.RenderingGroupInfo();
  24177. this._scene = scene;
  24178. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  24179. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  24180. }
  24181. }
  24182. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  24183. if (depth === void 0) { depth = true; }
  24184. if (stencil === void 0) { stencil = true; }
  24185. if (this._depthStencilBufferAlreadyCleaned) {
  24186. return;
  24187. }
  24188. this._scene.getEngine().clear(null, false, depth, stencil);
  24189. this._depthStencilBufferAlreadyCleaned = true;
  24190. };
  24191. /**
  24192. * Renders the entire managed groups. This is used by the scene or the different rennder targets.
  24193. * @hidden
  24194. */
  24195. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  24196. // Update the observable context (not null as it only goes away on dispose)
  24197. var info = this._renderingGroupInfo;
  24198. info.scene = this._scene;
  24199. info.camera = this._scene.activeCamera;
  24200. // Dispatch sprites
  24201. if (this._scene.spriteManagers && renderSprites) {
  24202. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  24203. var manager = this._scene.spriteManagers[index];
  24204. this.dispatchSprites(manager);
  24205. }
  24206. }
  24207. // Render
  24208. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  24209. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  24210. var renderingGroup = this._renderingGroups[index];
  24211. if (!renderingGroup)
  24212. continue;
  24213. var renderingGroupMask = Math.pow(2, index);
  24214. info.renderingGroupId = index;
  24215. // Before Observable
  24216. this._scene.onBeforeRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  24217. // Clear depth/stencil if needed
  24218. if (RenderingManager.AUTOCLEAR) {
  24219. var autoClear = this._useSceneAutoClearSetup ?
  24220. this._scene.getAutoClearDepthStencilSetup(index) :
  24221. this._autoClearDepthStencil[index];
  24222. if (autoClear && autoClear.autoClear) {
  24223. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  24224. }
  24225. }
  24226. // Render
  24227. for (var _i = 0, _a = this._scene._beforeRenderingGroupDrawStage; _i < _a.length; _i++) {
  24228. var step = _a[_i];
  24229. step.action(index);
  24230. }
  24231. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  24232. for (var _b = 0, _c = this._scene._afterRenderingGroupDrawStage; _b < _c.length; _b++) {
  24233. var step = _c[_b];
  24234. step.action(index);
  24235. }
  24236. // After Observable
  24237. this._scene.onAfterRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  24238. }
  24239. };
  24240. /**
  24241. * Resets the different information of the group to prepare a new frame
  24242. * @hidden
  24243. */
  24244. RenderingManager.prototype.reset = function () {
  24245. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  24246. var renderingGroup = this._renderingGroups[index];
  24247. if (renderingGroup) {
  24248. renderingGroup.prepare();
  24249. }
  24250. }
  24251. };
  24252. /**
  24253. * Dispose and release the group and its associated resources.
  24254. * @hidden
  24255. */
  24256. RenderingManager.prototype.dispose = function () {
  24257. this.freeRenderingGroups();
  24258. this._renderingGroups.length = 0;
  24259. this._renderingGroupInfo = null;
  24260. };
  24261. /**
  24262. * Clear the info related to rendering groups preventing retention points during dispose.
  24263. */
  24264. RenderingManager.prototype.freeRenderingGroups = function () {
  24265. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  24266. var renderingGroup = this._renderingGroups[index];
  24267. if (renderingGroup) {
  24268. renderingGroup.dispose();
  24269. }
  24270. }
  24271. };
  24272. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  24273. if (this._renderingGroups[renderingGroupId] === undefined) {
  24274. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  24275. }
  24276. };
  24277. /**
  24278. * Add a sprite manager to the rendering manager in order to render it this frame.
  24279. * @param spriteManager Define the sprite manager to render
  24280. */
  24281. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  24282. var renderingGroupId = spriteManager.renderingGroupId || 0;
  24283. this._prepareRenderingGroup(renderingGroupId);
  24284. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  24285. };
  24286. /**
  24287. * Add a particle system to the rendering manager in order to render it this frame.
  24288. * @param particleSystem Define the particle system to render
  24289. */
  24290. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  24291. var renderingGroupId = particleSystem.renderingGroupId || 0;
  24292. this._prepareRenderingGroup(renderingGroupId);
  24293. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  24294. };
  24295. /**
  24296. * Add a submesh to the manager in order to render it this frame
  24297. * @param subMesh The submesh to dispatch
  24298. * @param mesh Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  24299. * @param material Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  24300. */
  24301. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  24302. if (mesh === undefined) {
  24303. mesh = subMesh.getMesh();
  24304. }
  24305. var renderingGroupId = mesh.renderingGroupId || 0;
  24306. this._prepareRenderingGroup(renderingGroupId);
  24307. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  24308. };
  24309. /**
  24310. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  24311. * This allowed control for front to back rendering or reversly depending of the special needs.
  24312. *
  24313. * @param renderingGroupId The rendering group id corresponding to its index
  24314. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  24315. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  24316. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  24317. */
  24318. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  24319. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  24320. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  24321. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  24322. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  24323. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  24324. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  24325. if (this._renderingGroups[renderingGroupId]) {
  24326. var group = this._renderingGroups[renderingGroupId];
  24327. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  24328. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  24329. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  24330. }
  24331. };
  24332. /**
  24333. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  24334. *
  24335. * @param renderingGroupId The rendering group id corresponding to its index
  24336. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  24337. * @param depth Automatically clears depth between groups if true and autoClear is true.
  24338. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  24339. */
  24340. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  24341. if (depth === void 0) { depth = true; }
  24342. if (stencil === void 0) { stencil = true; }
  24343. this._autoClearDepthStencil[renderingGroupId] = {
  24344. autoClear: autoClearDepthStencil,
  24345. depth: depth,
  24346. stencil: stencil
  24347. };
  24348. };
  24349. /**
  24350. * Gets the current auto clear configuration for one rendering group of the rendering
  24351. * manager.
  24352. * @param index the rendering group index to get the information for
  24353. * @returns The auto clear setup for the requested rendering group
  24354. */
  24355. RenderingManager.prototype.getAutoClearDepthStencilSetup = function (index) {
  24356. return this._autoClearDepthStencil[index];
  24357. };
  24358. /**
  24359. * The max id used for rendering groups (not included)
  24360. */
  24361. RenderingManager.MAX_RENDERINGGROUPS = 4;
  24362. /**
  24363. * The min id used for rendering groups (included)
  24364. */
  24365. RenderingManager.MIN_RENDERINGGROUPS = 0;
  24366. /**
  24367. * Used to globally prevent autoclearing scenes.
  24368. */
  24369. RenderingManager.AUTOCLEAR = true;
  24370. return RenderingManager;
  24371. }());
  24372. BABYLON.RenderingManager = RenderingManager;
  24373. })(BABYLON || (BABYLON = {}));
  24374. //# sourceMappingURL=babylon.renderingManager.js.map
  24375. var BABYLON;
  24376. (function (BABYLON) {
  24377. /**
  24378. * This represents the object necessary to create a rendering group.
  24379. * This is exclusively used and created by the rendering manager.
  24380. * To modify the behavior, you use the available helpers in your scene or meshes.
  24381. * @hidden
  24382. */
  24383. var RenderingGroup = /** @class */ (function () {
  24384. /**
  24385. * Creates a new rendering group.
  24386. * @param index The rendering group index
  24387. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  24388. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  24389. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  24390. */
  24391. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  24392. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  24393. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  24394. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  24395. this.index = index;
  24396. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  24397. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  24398. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  24399. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  24400. this._particleSystems = new BABYLON.SmartArray(256);
  24401. this._spriteManagers = new BABYLON.SmartArray(256);
  24402. this._edgesRenderers = new BABYLON.SmartArray(16);
  24403. this._scene = scene;
  24404. this.opaqueSortCompareFn = opaqueSortCompareFn;
  24405. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  24406. this.transparentSortCompareFn = transparentSortCompareFn;
  24407. }
  24408. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  24409. /**
  24410. * Set the opaque sort comparison function.
  24411. * If null the sub meshes will be render in the order they were created
  24412. */
  24413. set: function (value) {
  24414. this._opaqueSortCompareFn = value;
  24415. if (value) {
  24416. this._renderOpaque = this.renderOpaqueSorted;
  24417. }
  24418. else {
  24419. this._renderOpaque = RenderingGroup.renderUnsorted;
  24420. }
  24421. },
  24422. enumerable: true,
  24423. configurable: true
  24424. });
  24425. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  24426. /**
  24427. * Set the alpha test sort comparison function.
  24428. * If null the sub meshes will be render in the order they were created
  24429. */
  24430. set: function (value) {
  24431. this._alphaTestSortCompareFn = value;
  24432. if (value) {
  24433. this._renderAlphaTest = this.renderAlphaTestSorted;
  24434. }
  24435. else {
  24436. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  24437. }
  24438. },
  24439. enumerable: true,
  24440. configurable: true
  24441. });
  24442. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  24443. /**
  24444. * Set the transparent sort comparison function.
  24445. * If null the sub meshes will be render in the order they were created
  24446. */
  24447. set: function (value) {
  24448. if (value) {
  24449. this._transparentSortCompareFn = value;
  24450. }
  24451. else {
  24452. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  24453. }
  24454. this._renderTransparent = this.renderTransparentSorted;
  24455. },
  24456. enumerable: true,
  24457. configurable: true
  24458. });
  24459. /**
  24460. * Render all the sub meshes contained in the group.
  24461. * @param customRenderFunction Used to override the default render behaviour of the group.
  24462. * @returns true if rendered some submeshes.
  24463. */
  24464. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  24465. if (customRenderFunction) {
  24466. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  24467. return;
  24468. }
  24469. var engine = this._scene.getEngine();
  24470. // Depth only
  24471. if (this._depthOnlySubMeshes.length !== 0) {
  24472. engine.setColorWrite(false);
  24473. this._renderAlphaTest(this._depthOnlySubMeshes);
  24474. engine.setColorWrite(true);
  24475. }
  24476. // Opaque
  24477. if (this._opaqueSubMeshes.length !== 0) {
  24478. this._renderOpaque(this._opaqueSubMeshes);
  24479. }
  24480. // Alpha test
  24481. if (this._alphaTestSubMeshes.length !== 0) {
  24482. this._renderAlphaTest(this._alphaTestSubMeshes);
  24483. }
  24484. var stencilState = engine.getStencilBuffer();
  24485. engine.setStencilBuffer(false);
  24486. // Sprites
  24487. if (renderSprites) {
  24488. this._renderSprites();
  24489. }
  24490. // Particles
  24491. if (renderParticles) {
  24492. this._renderParticles(activeMeshes);
  24493. }
  24494. if (this.onBeforeTransparentRendering) {
  24495. this.onBeforeTransparentRendering();
  24496. }
  24497. // Transparent
  24498. if (this._transparentSubMeshes.length !== 0) {
  24499. this._renderTransparent(this._transparentSubMeshes);
  24500. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  24501. }
  24502. // Set back stencil to false in case it changes before the edge renderer.
  24503. engine.setStencilBuffer(false);
  24504. // Edges
  24505. if (this._edgesRenderers.length) {
  24506. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  24507. this._edgesRenderers.data[edgesRendererIndex].render();
  24508. }
  24509. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  24510. }
  24511. // Restore Stencil state.
  24512. engine.setStencilBuffer(stencilState);
  24513. };
  24514. /**
  24515. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  24516. * @param subMeshes The submeshes to render
  24517. */
  24518. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  24519. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  24520. };
  24521. /**
  24522. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  24523. * @param subMeshes The submeshes to render
  24524. */
  24525. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  24526. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  24527. };
  24528. /**
  24529. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  24530. * @param subMeshes The submeshes to render
  24531. */
  24532. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  24533. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  24534. };
  24535. /**
  24536. * Renders the submeshes in a specified order.
  24537. * @param subMeshes The submeshes to sort before render
  24538. * @param sortCompareFn The comparison function use to sort
  24539. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  24540. * @param transparent Specifies to activate blending if true
  24541. */
  24542. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  24543. var subIndex = 0;
  24544. var subMesh;
  24545. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  24546. for (; subIndex < subMeshes.length; subIndex++) {
  24547. subMesh = subMeshes.data[subIndex];
  24548. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  24549. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  24550. }
  24551. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  24552. if (sortCompareFn) {
  24553. sortedArray.sort(sortCompareFn);
  24554. }
  24555. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  24556. subMesh = sortedArray[subIndex];
  24557. if (transparent) {
  24558. var material = subMesh.getMaterial();
  24559. if (material && material.needDepthPrePass) {
  24560. var engine = material.getScene().getEngine();
  24561. engine.setColorWrite(false);
  24562. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  24563. subMesh.render(false);
  24564. engine.setColorWrite(true);
  24565. }
  24566. }
  24567. subMesh.render(transparent);
  24568. }
  24569. };
  24570. /**
  24571. * Renders the submeshes in the order they were dispatched (no sort applied).
  24572. * @param subMeshes The submeshes to render
  24573. */
  24574. RenderingGroup.renderUnsorted = function (subMeshes) {
  24575. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  24576. var submesh = subMeshes.data[subIndex];
  24577. submesh.render(false);
  24578. }
  24579. };
  24580. /**
  24581. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  24582. * are rendered back to front if in the same alpha index.
  24583. *
  24584. * @param a The first submesh
  24585. * @param b The second submesh
  24586. * @returns The result of the comparison
  24587. */
  24588. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  24589. // Alpha index first
  24590. if (a._alphaIndex > b._alphaIndex) {
  24591. return 1;
  24592. }
  24593. if (a._alphaIndex < b._alphaIndex) {
  24594. return -1;
  24595. }
  24596. // Then distance to camera
  24597. return RenderingGroup.backToFrontSortCompare(a, b);
  24598. };
  24599. /**
  24600. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  24601. * are rendered back to front.
  24602. *
  24603. * @param a The first submesh
  24604. * @param b The second submesh
  24605. * @returns The result of the comparison
  24606. */
  24607. RenderingGroup.backToFrontSortCompare = function (a, b) {
  24608. // Then distance to camera
  24609. if (a._distanceToCamera < b._distanceToCamera) {
  24610. return 1;
  24611. }
  24612. if (a._distanceToCamera > b._distanceToCamera) {
  24613. return -1;
  24614. }
  24615. return 0;
  24616. };
  24617. /**
  24618. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  24619. * are rendered front to back (prevent overdraw).
  24620. *
  24621. * @param a The first submesh
  24622. * @param b The second submesh
  24623. * @returns The result of the comparison
  24624. */
  24625. RenderingGroup.frontToBackSortCompare = function (a, b) {
  24626. // Then distance to camera
  24627. if (a._distanceToCamera < b._distanceToCamera) {
  24628. return -1;
  24629. }
  24630. if (a._distanceToCamera > b._distanceToCamera) {
  24631. return 1;
  24632. }
  24633. return 0;
  24634. };
  24635. /**
  24636. * Resets the different lists of submeshes to prepare a new frame.
  24637. */
  24638. RenderingGroup.prototype.prepare = function () {
  24639. this._opaqueSubMeshes.reset();
  24640. this._transparentSubMeshes.reset();
  24641. this._alphaTestSubMeshes.reset();
  24642. this._depthOnlySubMeshes.reset();
  24643. this._particleSystems.reset();
  24644. this._spriteManagers.reset();
  24645. this._edgesRenderers.reset();
  24646. };
  24647. RenderingGroup.prototype.dispose = function () {
  24648. this._opaqueSubMeshes.dispose();
  24649. this._transparentSubMeshes.dispose();
  24650. this._alphaTestSubMeshes.dispose();
  24651. this._depthOnlySubMeshes.dispose();
  24652. this._particleSystems.dispose();
  24653. this._spriteManagers.dispose();
  24654. this._edgesRenderers.dispose();
  24655. };
  24656. /**
  24657. * Inserts the submesh in its correct queue depending on its material.
  24658. * @param subMesh The submesh to dispatch
  24659. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  24660. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  24661. */
  24662. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  24663. // Get mesh and materials if not provided
  24664. if (mesh === undefined) {
  24665. mesh = subMesh.getMesh();
  24666. }
  24667. if (material === undefined) {
  24668. material = subMesh.getMaterial();
  24669. }
  24670. if (material === null || material === undefined) {
  24671. return;
  24672. }
  24673. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  24674. this._transparentSubMeshes.push(subMesh);
  24675. }
  24676. else if (material.needAlphaTesting()) { // Alpha test
  24677. if (material.needDepthPrePass) {
  24678. this._depthOnlySubMeshes.push(subMesh);
  24679. }
  24680. this._alphaTestSubMeshes.push(subMesh);
  24681. }
  24682. else {
  24683. if (material.needDepthPrePass) {
  24684. this._depthOnlySubMeshes.push(subMesh);
  24685. }
  24686. this._opaqueSubMeshes.push(subMesh); // Opaque
  24687. }
  24688. if (mesh._edgesRenderer && mesh._edgesRenderer.isEnabled) {
  24689. this._edgesRenderers.push(mesh._edgesRenderer);
  24690. }
  24691. };
  24692. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  24693. this._spriteManagers.push(spriteManager);
  24694. };
  24695. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  24696. this._particleSystems.push(particleSystem);
  24697. };
  24698. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  24699. if (this._particleSystems.length === 0) {
  24700. return;
  24701. }
  24702. // Particles
  24703. var activeCamera = this._scene.activeCamera;
  24704. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  24705. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  24706. var particleSystem = this._particleSystems.data[particleIndex];
  24707. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  24708. continue;
  24709. }
  24710. var emitter = particleSystem.emitter;
  24711. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  24712. this._scene._activeParticles.addCount(particleSystem.render(), false);
  24713. }
  24714. }
  24715. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  24716. };
  24717. RenderingGroup.prototype._renderSprites = function () {
  24718. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  24719. return;
  24720. }
  24721. // Sprites
  24722. var activeCamera = this._scene.activeCamera;
  24723. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  24724. for (var id = 0; id < this._spriteManagers.length; id++) {
  24725. var spriteManager = this._spriteManagers.data[id];
  24726. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  24727. spriteManager.render();
  24728. }
  24729. }
  24730. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  24731. };
  24732. return RenderingGroup;
  24733. }());
  24734. BABYLON.RenderingGroup = RenderingGroup;
  24735. })(BABYLON || (BABYLON = {}));
  24736. //# sourceMappingURL=babylon.renderingGroup.js.map
  24737. var BABYLON;
  24738. (function (BABYLON) {
  24739. /**
  24740. * Groups all the scene component constants in one place to ease maintenance.
  24741. * @hidden
  24742. */
  24743. var SceneComponentConstants = /** @class */ (function () {
  24744. function SceneComponentConstants() {
  24745. }
  24746. SceneComponentConstants.NAME_EFFECTLAYER = "EffectLayer";
  24747. SceneComponentConstants.NAME_LAYER = "Layer";
  24748. SceneComponentConstants.NAME_LENSFLARESYSTEM = "LensFlareSystem";
  24749. SceneComponentConstants.NAME_BOUNDINGBOXRENDERER = "BoundingBoxRenderer";
  24750. SceneComponentConstants.NAME_PARTICLESYSTEM = "ParticleSystem";
  24751. SceneComponentConstants.NAME_GAMEPAD = "Gamepad";
  24752. SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE = "SimplificationQueue";
  24753. SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER = "GeometryBufferRenderer";
  24754. SceneComponentConstants.NAME_DEPTHRENDERER = "DepthRenderer";
  24755. SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER = "PostProcessRenderPipelineManager";
  24756. SceneComponentConstants.NAME_SPRITE = "Sprite";
  24757. SceneComponentConstants.NAME_OUTLINERENDERER = "Outline";
  24758. SceneComponentConstants.NAME_PROCEDURALTEXTURE = "ProceduralTexture";
  24759. SceneComponentConstants.NAME_SHADOWGENERATOR = "ShadowGenerator";
  24760. SceneComponentConstants.NAME_OCTREE = "Octree";
  24761. SceneComponentConstants.NAME_PHYSICSENGINE = "PhysicsEngine";
  24762. SceneComponentConstants.NAME_AUDIO = "Audio";
  24763. SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER = 0;
  24764. SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  24765. SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER = 0;
  24766. SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  24767. SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER = 1;
  24768. SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER = 0;
  24769. SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER = 1;
  24770. SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE = 0;
  24771. SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE = 0;
  24772. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW = 0;
  24773. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER = 1;
  24774. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE = 0;
  24775. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD = 1;
  24776. SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE = 0;
  24777. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER = 0;
  24778. SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM = 1;
  24779. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW = 2;
  24780. SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER = 3;
  24781. SceneComponentConstants.STEP_AFTERRENDER_AUDIO = 0;
  24782. SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR = 0;
  24783. SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER = 1;
  24784. SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER = 2;
  24785. SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER = 3;
  24786. SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER = 0;
  24787. SceneComponentConstants.STEP_POINTERMOVE_SPRITE = 0;
  24788. SceneComponentConstants.STEP_POINTERDOWN_SPRITE = 0;
  24789. SceneComponentConstants.STEP_POINTERUP_SPRITE = 0;
  24790. return SceneComponentConstants;
  24791. }());
  24792. BABYLON.SceneComponentConstants = SceneComponentConstants;
  24793. /**
  24794. * Repressentation of a stage in the scene (Basically a list of ordered steps)
  24795. * @hidden
  24796. */
  24797. var Stage = /** @class */ (function (_super) {
  24798. __extends(Stage, _super);
  24799. /**
  24800. * Hide ctor from the rest of the world.
  24801. * @param items The items to add.
  24802. */
  24803. function Stage(items) {
  24804. return _super.apply(this, items) || this;
  24805. }
  24806. /**
  24807. * Creates a new Stage.
  24808. * @returns A new instance of a Stage
  24809. */
  24810. Stage.Create = function () {
  24811. return Object.create(Stage.prototype);
  24812. };
  24813. /**
  24814. * Registers a step in an ordered way in the targeted stage.
  24815. * @param index Defines the position to register the step in
  24816. * @param component Defines the component attached to the step
  24817. * @param action Defines the action to launch during the step
  24818. */
  24819. Stage.prototype.registerStep = function (index, component, action) {
  24820. var i = 0;
  24821. var maxIndex = Number.MAX_VALUE;
  24822. for (; i < this.length; i++) {
  24823. var step = this[i];
  24824. maxIndex = step.index;
  24825. if (index < maxIndex) {
  24826. break;
  24827. }
  24828. }
  24829. this.splice(i, 0, { index: index, component: component, action: action.bind(component) });
  24830. };
  24831. /**
  24832. * Clears all the steps from the stage.
  24833. */
  24834. Stage.prototype.clear = function () {
  24835. this.length = 0;
  24836. };
  24837. return Stage;
  24838. }(Array));
  24839. BABYLON.Stage = Stage;
  24840. })(BABYLON || (BABYLON = {}));
  24841. //# sourceMappingURL=babylon.sceneComponent.js.map
  24842. var BABYLON;
  24843. (function (BABYLON) {
  24844. /**
  24845. * Base class of the scene acting as a container for the different elements composing a scene.
  24846. * This class is dynamically extended by the different components of the scene increasing
  24847. * flexibility and reducing coupling
  24848. */
  24849. var AbstractScene = /** @class */ (function () {
  24850. function AbstractScene() {
  24851. /**
  24852. * Gets the list of root nodes (ie. nodes with no parent)
  24853. */
  24854. this.rootNodes = new Array();
  24855. /** All of the cameras added to this scene
  24856. * @see http://doc.babylonjs.com/babylon101/cameras
  24857. */
  24858. this.cameras = new Array();
  24859. /**
  24860. * All of the lights added to this scene
  24861. * @see http://doc.babylonjs.com/babylon101/lights
  24862. */
  24863. this.lights = new Array();
  24864. /**
  24865. * All of the (abstract) meshes added to this scene
  24866. */
  24867. this.meshes = new Array();
  24868. /**
  24869. * The list of skeletons added to the scene
  24870. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  24871. */
  24872. this.skeletons = new Array();
  24873. /**
  24874. * All of the particle systems added to this scene
  24875. * @see http://doc.babylonjs.com/babylon101/particles
  24876. */
  24877. this.particleSystems = new Array();
  24878. /**
  24879. * Gets a list of Animations associated with the scene
  24880. */
  24881. this.animations = [];
  24882. /**
  24883. * All of the animation groups added to this scene
  24884. * @see http://doc.babylonjs.com/how_to/group
  24885. */
  24886. this.animationGroups = new Array();
  24887. /**
  24888. * All of the multi-materials added to this scene
  24889. * @see http://doc.babylonjs.com/how_to/multi_materials
  24890. */
  24891. this.multiMaterials = new Array();
  24892. /**
  24893. * All of the materials added to this scene
  24894. * @see http://doc.babylonjs.com/babylon101/materials
  24895. */
  24896. this.materials = new Array();
  24897. /**
  24898. * The list of morph target managers added to the scene
  24899. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  24900. */
  24901. this.morphTargetManagers = new Array();
  24902. /**
  24903. * The list of geometries used in the scene.
  24904. */
  24905. this.geometries = new Array();
  24906. /**
  24907. * All of the tranform nodes added to this scene
  24908. * @see http://doc.babylonjs.com/how_to/transformnode
  24909. */
  24910. this.transformNodes = new Array();
  24911. /**
  24912. * ActionManagers available on the scene.
  24913. */
  24914. this.actionManagers = new Array();
  24915. /**
  24916. * Textures to keep.
  24917. */
  24918. this.textures = new Array();
  24919. }
  24920. /**
  24921. * Adds a parser in the list of available ones
  24922. * @param name Defines the name of the parser
  24923. * @param parser Defines the parser to add
  24924. */
  24925. AbstractScene.AddParser = function (name, parser) {
  24926. this._BabylonFileParsers[name] = parser;
  24927. };
  24928. /**
  24929. * Gets a general parser from the list of avaialble ones
  24930. * @param name Defines the name of the parser
  24931. * @returns the requested parser or null
  24932. */
  24933. AbstractScene.GetParser = function (name) {
  24934. if (this._BabylonFileParsers[name]) {
  24935. return this._BabylonFileParsers[name];
  24936. }
  24937. return null;
  24938. };
  24939. /**
  24940. * Adds n individual parser in the list of available ones
  24941. * @param name Defines the name of the parser
  24942. * @param parser Defines the parser to add
  24943. */
  24944. AbstractScene.AddIndividualParser = function (name, parser) {
  24945. this._IndividualBabylonFileParsers[name] = parser;
  24946. };
  24947. /**
  24948. * Gets an individual parser from the list of avaialble ones
  24949. * @param name Defines the name of the parser
  24950. * @returns the requested parser or null
  24951. */
  24952. AbstractScene.GetIndividualParser = function (name) {
  24953. if (this._IndividualBabylonFileParsers[name]) {
  24954. return this._IndividualBabylonFileParsers[name];
  24955. }
  24956. return null;
  24957. };
  24958. /**
  24959. * Parser json data and populate both a scene and its associated container object
  24960. * @param jsonData Defines the data to parse
  24961. * @param scene Defines the scene to parse the data for
  24962. * @param container Defines the container attached to the parsing sequence
  24963. * @param rootUrl Defines the root url of the data
  24964. */
  24965. AbstractScene.Parse = function (jsonData, scene, container, rootUrl) {
  24966. for (var parserName in this._BabylonFileParsers) {
  24967. if (this._BabylonFileParsers.hasOwnProperty(parserName)) {
  24968. this._BabylonFileParsers[parserName](jsonData, scene, container, rootUrl);
  24969. }
  24970. }
  24971. };
  24972. /**
  24973. * Stores the list of available parsers in the application.
  24974. */
  24975. AbstractScene._BabylonFileParsers = {};
  24976. /**
  24977. * Stores the list of available individual parsers in the application.
  24978. */
  24979. AbstractScene._IndividualBabylonFileParsers = {};
  24980. return AbstractScene;
  24981. }());
  24982. BABYLON.AbstractScene = AbstractScene;
  24983. })(BABYLON || (BABYLON = {}));
  24984. //# sourceMappingURL=babylon.abstractScene.js.map
  24985. var BABYLON;
  24986. (function (BABYLON) {
  24987. /** @hidden */
  24988. var ClickInfo = /** @class */ (function () {
  24989. function ClickInfo() {
  24990. this._singleClick = false;
  24991. this._doubleClick = false;
  24992. this._hasSwiped = false;
  24993. this._ignore = false;
  24994. }
  24995. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  24996. get: function () {
  24997. return this._singleClick;
  24998. },
  24999. set: function (b) {
  25000. this._singleClick = b;
  25001. },
  25002. enumerable: true,
  25003. configurable: true
  25004. });
  25005. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  25006. get: function () {
  25007. return this._doubleClick;
  25008. },
  25009. set: function (b) {
  25010. this._doubleClick = b;
  25011. },
  25012. enumerable: true,
  25013. configurable: true
  25014. });
  25015. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  25016. get: function () {
  25017. return this._hasSwiped;
  25018. },
  25019. set: function (b) {
  25020. this._hasSwiped = b;
  25021. },
  25022. enumerable: true,
  25023. configurable: true
  25024. });
  25025. Object.defineProperty(ClickInfo.prototype, "ignore", {
  25026. get: function () {
  25027. return this._ignore;
  25028. },
  25029. set: function (b) {
  25030. this._ignore = b;
  25031. },
  25032. enumerable: true,
  25033. configurable: true
  25034. });
  25035. return ClickInfo;
  25036. }());
  25037. /**
  25038. * This class is used by the onRenderingGroupObservable
  25039. */
  25040. var RenderingGroupInfo = /** @class */ (function () {
  25041. function RenderingGroupInfo() {
  25042. }
  25043. return RenderingGroupInfo;
  25044. }());
  25045. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  25046. /**
  25047. * Represents a scene to be rendered by the engine.
  25048. * @see http://doc.babylonjs.com/features/scene
  25049. */
  25050. var Scene = /** @class */ (function (_super) {
  25051. __extends(Scene, _super);
  25052. /**
  25053. * Creates a new Scene
  25054. * @param engine defines the engine to use to render this scene
  25055. */
  25056. function Scene(engine) {
  25057. var _this = _super.call(this) || this;
  25058. // Members
  25059. /**
  25060. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  25061. */
  25062. _this.autoClear = true;
  25063. /**
  25064. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  25065. */
  25066. _this.autoClearDepthAndStencil = true;
  25067. /**
  25068. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  25069. */
  25070. _this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  25071. /**
  25072. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  25073. */
  25074. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  25075. _this._forceWireframe = false;
  25076. _this._forcePointsCloud = false;
  25077. /**
  25078. * Gets or sets a boolean indicating if animations are enabled
  25079. */
  25080. _this.animationsEnabled = true;
  25081. _this._animationPropertiesOverride = null;
  25082. /**
  25083. * Gets or sets a boolean indicating if a constant deltatime has to be used
  25084. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  25085. */
  25086. _this.useConstantAnimationDeltaTime = false;
  25087. /**
  25088. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  25089. * Please note that it requires to run a ray cast through the scene on every frame
  25090. */
  25091. _this.constantlyUpdateMeshUnderPointer = false;
  25092. /**
  25093. * Defines the HTML cursor to use when hovering over interactive elements
  25094. */
  25095. _this.hoverCursor = "pointer";
  25096. /**
  25097. * Defines the HTML default cursor to use (empty by default)
  25098. */
  25099. _this.defaultCursor = "";
  25100. /**
  25101. * This is used to call preventDefault() on pointer down
  25102. * in order to block unwanted artifacts like system double clicks
  25103. */
  25104. _this.preventDefaultOnPointerDown = true;
  25105. // Metadata
  25106. /**
  25107. * Gets or sets user defined metadata
  25108. */
  25109. _this.metadata = null;
  25110. /**
  25111. * Use this array to add regular expressions used to disable offline support for specific urls
  25112. */
  25113. _this.disableOfflineSupportExceptionRules = new Array();
  25114. /**
  25115. * An event triggered when the scene is disposed.
  25116. */
  25117. _this.onDisposeObservable = new BABYLON.Observable();
  25118. _this._onDisposeObserver = null;
  25119. /**
  25120. * An event triggered before rendering the scene (right after animations and physics)
  25121. */
  25122. _this.onBeforeRenderObservable = new BABYLON.Observable();
  25123. _this._onBeforeRenderObserver = null;
  25124. /**
  25125. * An event triggered after rendering the scene
  25126. */
  25127. _this.onAfterRenderObservable = new BABYLON.Observable();
  25128. _this._onAfterRenderObserver = null;
  25129. /**
  25130. * An event triggered before animating the scene
  25131. */
  25132. _this.onBeforeAnimationsObservable = new BABYLON.Observable();
  25133. /**
  25134. * An event triggered after animations processing
  25135. */
  25136. _this.onAfterAnimationsObservable = new BABYLON.Observable();
  25137. /**
  25138. * An event triggered before draw calls are ready to be sent
  25139. */
  25140. _this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  25141. /**
  25142. * An event triggered after draw calls have been sent
  25143. */
  25144. _this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  25145. /**
  25146. * An event triggered when the scene is ready
  25147. */
  25148. _this.onReadyObservable = new BABYLON.Observable();
  25149. /**
  25150. * An event triggered before rendering a camera
  25151. */
  25152. _this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  25153. _this._onBeforeCameraRenderObserver = null;
  25154. /**
  25155. * An event triggered after rendering a camera
  25156. */
  25157. _this.onAfterCameraRenderObservable = new BABYLON.Observable();
  25158. _this._onAfterCameraRenderObserver = null;
  25159. /**
  25160. * An event triggered when active meshes evaluation is about to start
  25161. */
  25162. _this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  25163. /**
  25164. * An event triggered when active meshes evaluation is done
  25165. */
  25166. _this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  25167. /**
  25168. * An event triggered when particles rendering is about to start
  25169. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  25170. */
  25171. _this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  25172. /**
  25173. * An event triggered when particles rendering is done
  25174. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  25175. */
  25176. _this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  25177. /**
  25178. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  25179. */
  25180. _this.onDataLoadedObservable = new BABYLON.Observable();
  25181. /**
  25182. * An event triggered when a camera is created
  25183. */
  25184. _this.onNewCameraAddedObservable = new BABYLON.Observable();
  25185. /**
  25186. * An event triggered when a camera is removed
  25187. */
  25188. _this.onCameraRemovedObservable = new BABYLON.Observable();
  25189. /**
  25190. * An event triggered when a light is created
  25191. */
  25192. _this.onNewLightAddedObservable = new BABYLON.Observable();
  25193. /**
  25194. * An event triggered when a light is removed
  25195. */
  25196. _this.onLightRemovedObservable = new BABYLON.Observable();
  25197. /**
  25198. * An event triggered when a geometry is created
  25199. */
  25200. _this.onNewGeometryAddedObservable = new BABYLON.Observable();
  25201. /**
  25202. * An event triggered when a geometry is removed
  25203. */
  25204. _this.onGeometryRemovedObservable = new BABYLON.Observable();
  25205. /**
  25206. * An event triggered when a transform node is created
  25207. */
  25208. _this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  25209. /**
  25210. * An event triggered when a transform node is removed
  25211. */
  25212. _this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  25213. /**
  25214. * An event triggered when a mesh is created
  25215. */
  25216. _this.onNewMeshAddedObservable = new BABYLON.Observable();
  25217. /**
  25218. * An event triggered when a mesh is removed
  25219. */
  25220. _this.onMeshRemovedObservable = new BABYLON.Observable();
  25221. /**
  25222. * An event triggered when a material is created
  25223. */
  25224. _this.onNewMaterialAddedObservable = new BABYLON.Observable();
  25225. /**
  25226. * An event triggered when a material is removed
  25227. */
  25228. _this.onMaterialRemovedObservable = new BABYLON.Observable();
  25229. /**
  25230. * An event triggered when a texture is created
  25231. */
  25232. _this.onNewTextureAddedObservable = new BABYLON.Observable();
  25233. /**
  25234. * An event triggered when a texture is removed
  25235. */
  25236. _this.onTextureRemovedObservable = new BABYLON.Observable();
  25237. /**
  25238. * An event triggered when render targets are about to be rendered
  25239. * Can happen multiple times per frame.
  25240. */
  25241. _this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  25242. /**
  25243. * An event triggered when render targets were rendered.
  25244. * Can happen multiple times per frame.
  25245. */
  25246. _this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  25247. /**
  25248. * An event triggered before calculating deterministic simulation step
  25249. */
  25250. _this.onBeforeStepObservable = new BABYLON.Observable();
  25251. /**
  25252. * An event triggered after calculating deterministic simulation step
  25253. */
  25254. _this.onAfterStepObservable = new BABYLON.Observable();
  25255. /**
  25256. * This Observable will be triggered before rendering each renderingGroup of each rendered camera.
  25257. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  25258. * 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)
  25259. */
  25260. _this.onBeforeRenderingGroupObservable = new BABYLON.Observable();
  25261. /**
  25262. * This Observable will be triggered after rendering each renderingGroup of each rendered camera.
  25263. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  25264. * 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)
  25265. */
  25266. _this.onAfterRenderingGroupObservable = new BABYLON.Observable();
  25267. /**
  25268. * This Observable will when a mesh has been imported into the scene.
  25269. */
  25270. _this.onMeshImportedObservable = new BABYLON.Observable();
  25271. // Animations
  25272. _this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  25273. /**
  25274. * 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).
  25275. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  25276. */
  25277. _this.onPrePointerObservable = new BABYLON.Observable();
  25278. /**
  25279. * Observable event triggered each time an input event is received from the rendering canvas
  25280. */
  25281. _this.onPointerObservable = new BABYLON.Observable();
  25282. _this._meshPickProceed = false;
  25283. _this._currentPickResult = null;
  25284. _this._previousPickResult = null;
  25285. _this._totalPointersPressed = 0;
  25286. _this._doubleClickOccured = false;
  25287. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  25288. _this.cameraToUseForPointers = null;
  25289. _this._pointerX = 0;
  25290. _this._pointerY = 0;
  25291. _this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  25292. _this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  25293. _this._startingPointerTime = 0;
  25294. _this._previousStartingPointerTime = 0;
  25295. _this._pointerCaptures = {};
  25296. // Deterministic lockstep
  25297. _this._timeAccumulator = 0;
  25298. _this._currentStepId = 0;
  25299. _this._currentInternalStep = 0;
  25300. // Keyboard
  25301. /**
  25302. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  25303. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  25304. */
  25305. _this.onPreKeyboardObservable = new BABYLON.Observable();
  25306. /**
  25307. * Observable event triggered each time an keyboard event is received from the hosting window
  25308. */
  25309. _this.onKeyboardObservable = new BABYLON.Observable();
  25310. // Coordinates system
  25311. _this._useRightHandedSystem = false;
  25312. // Fog
  25313. _this._fogEnabled = true;
  25314. _this._fogMode = Scene.FOGMODE_NONE;
  25315. /**
  25316. * Gets or sets the fog color to use
  25317. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25318. * (Default is Color3(0.2, 0.2, 0.3))
  25319. */
  25320. _this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  25321. /**
  25322. * Gets or sets the fog density to use
  25323. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25324. * (Default is 0.1)
  25325. */
  25326. _this.fogDensity = 0.1;
  25327. /**
  25328. * Gets or sets the fog start distance to use
  25329. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25330. * (Default is 0)
  25331. */
  25332. _this.fogStart = 0;
  25333. /**
  25334. * Gets or sets the fog end distance to use
  25335. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25336. * (Default is 1000)
  25337. */
  25338. _this.fogEnd = 1000.0;
  25339. // Lights
  25340. _this._shadowsEnabled = true;
  25341. _this._lightsEnabled = true;
  25342. /** All of the active cameras added to this scene. */
  25343. _this.activeCameras = new Array();
  25344. // Textures
  25345. _this._texturesEnabled = true;
  25346. // Particles
  25347. /**
  25348. * Gets or sets a boolean indicating if particles are enabled on this scene
  25349. */
  25350. _this.particlesEnabled = true;
  25351. // Sprites
  25352. /**
  25353. * Gets or sets a boolean indicating if sprites are enabled on this scene
  25354. */
  25355. _this.spritesEnabled = true;
  25356. // Skeletons
  25357. _this._skeletonsEnabled = true;
  25358. // Lens flares
  25359. /**
  25360. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  25361. */
  25362. _this.lensFlaresEnabled = true;
  25363. // Collisions
  25364. /**
  25365. * Gets or sets a boolean indicating if collisions are enabled on this scene
  25366. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  25367. */
  25368. _this.collisionsEnabled = true;
  25369. /**
  25370. * Defines the gravity applied to this scene (used only for collisions)
  25371. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  25372. */
  25373. _this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  25374. // Postprocesses
  25375. /**
  25376. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  25377. */
  25378. _this.postProcessesEnabled = true;
  25379. /**
  25380. * The list of postprocesses added to the scene
  25381. */
  25382. _this.postProcesses = new Array();
  25383. // Customs render targets
  25384. /**
  25385. * Gets or sets a boolean indicating if render targets are enabled on this scene
  25386. */
  25387. _this.renderTargetsEnabled = true;
  25388. /**
  25389. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  25390. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  25391. */
  25392. _this.dumpNextRenderTargets = false;
  25393. /**
  25394. * The list of user defined render targets added to the scene
  25395. */
  25396. _this.customRenderTargets = new Array();
  25397. /**
  25398. * Gets the list of meshes imported to the scene through SceneLoader
  25399. */
  25400. _this.importedMeshesFiles = new Array();
  25401. // Probes
  25402. /**
  25403. * Gets or sets a boolean indicating if probes are enabled on this scene
  25404. */
  25405. _this.probesEnabled = true;
  25406. _this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  25407. // Procedural textures
  25408. /**
  25409. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  25410. */
  25411. _this.proceduralTexturesEnabled = true;
  25412. // Performance counters
  25413. _this._totalVertices = new BABYLON.PerfCounter();
  25414. /** @hidden */
  25415. _this._activeIndices = new BABYLON.PerfCounter();
  25416. /** @hidden */
  25417. _this._activeParticles = new BABYLON.PerfCounter();
  25418. /** @hidden */
  25419. _this._activeBones = new BABYLON.PerfCounter();
  25420. _this._animationTime = 0;
  25421. /**
  25422. * Gets or sets a general scale for animation speed
  25423. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  25424. */
  25425. _this.animationTimeScale = 1;
  25426. _this._renderId = 0;
  25427. _this._frameId = 0;
  25428. _this._executeWhenReadyTimeoutId = -1;
  25429. _this._intermediateRendering = false;
  25430. _this._viewUpdateFlag = -1;
  25431. _this._projectionUpdateFlag = -1;
  25432. _this._alternateViewUpdateFlag = -1;
  25433. _this._alternateProjectionUpdateFlag = -1;
  25434. /** @hidden */
  25435. _this._toBeDisposed = new Array(256);
  25436. _this._activeRequests = new Array();
  25437. _this._pendingData = new Array();
  25438. _this._isDisposed = false;
  25439. /**
  25440. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  25441. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  25442. */
  25443. _this.dispatchAllSubMeshesOfActiveMeshes = false;
  25444. _this._activeMeshes = new BABYLON.SmartArray(256);
  25445. _this._processedMaterials = new BABYLON.SmartArray(256);
  25446. _this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  25447. /** @hidden */
  25448. _this._activeParticleSystems = new BABYLON.SmartArray(256);
  25449. _this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  25450. _this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  25451. /** @hidden */
  25452. _this._activeAnimatables = new Array();
  25453. _this._transformMatrix = BABYLON.Matrix.Zero();
  25454. _this._useAlternateCameraConfiguration = false;
  25455. _this._alternateRendering = false;
  25456. /**
  25457. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  25458. * This is useful if there are more lights that the maximum simulteanous authorized
  25459. */
  25460. _this.requireLightSorting = false;
  25461. /**
  25462. * @hidden
  25463. * Backing store of defined scene components.
  25464. */
  25465. _this._components = [];
  25466. /**
  25467. * @hidden
  25468. * Backing store of defined scene components.
  25469. */
  25470. _this._serializableComponents = [];
  25471. /**
  25472. * List of components to register on the next registration step.
  25473. */
  25474. _this._transientComponents = [];
  25475. /**
  25476. * @hidden
  25477. * Defines the actions happening before camera updates.
  25478. */
  25479. _this._beforeCameraUpdateStage = BABYLON.Stage.Create();
  25480. /**
  25481. * @hidden
  25482. * Defines the actions happening before clear the canvas.
  25483. */
  25484. _this._beforeClearStage = BABYLON.Stage.Create();
  25485. /**
  25486. * @hidden
  25487. * Defines the actions when collecting render targets for the frame.
  25488. */
  25489. _this._gatherRenderTargetsStage = BABYLON.Stage.Create();
  25490. /**
  25491. * @hidden
  25492. * Defines the actions happening for one camera in the frame.
  25493. */
  25494. _this._gatherActiveCameraRenderTargetsStage = BABYLON.Stage.Create();
  25495. /**
  25496. * @hidden
  25497. * Defines the actions happening during the per mesh ready checks.
  25498. */
  25499. _this._isReadyForMeshStage = BABYLON.Stage.Create();
  25500. /**
  25501. * @hidden
  25502. * Defines the actions happening before evaluate active mesh checks.
  25503. */
  25504. _this._beforeEvaluateActiveMeshStage = BABYLON.Stage.Create();
  25505. /**
  25506. * @hidden
  25507. * Defines the actions happening during the evaluate sub mesh checks.
  25508. */
  25509. _this._evaluateSubMeshStage = BABYLON.Stage.Create();
  25510. /**
  25511. * @hidden
  25512. * Defines the actions happening during the active mesh stage.
  25513. */
  25514. _this._activeMeshStage = BABYLON.Stage.Create();
  25515. /**
  25516. * @hidden
  25517. * Defines the actions happening during the per camera render target step.
  25518. */
  25519. _this._cameraDrawRenderTargetStage = BABYLON.Stage.Create();
  25520. /**
  25521. * @hidden
  25522. * Defines the actions happening just before the active camera is drawing.
  25523. */
  25524. _this._beforeCameraDrawStage = BABYLON.Stage.Create();
  25525. /**
  25526. * @hidden
  25527. * Defines the actions happening just before a rendering group is drawing.
  25528. */
  25529. _this._beforeRenderingGroupDrawStage = BABYLON.Stage.Create();
  25530. /**
  25531. * @hidden
  25532. * Defines the actions happening just before a mesh is drawing.
  25533. */
  25534. _this._beforeRenderingMeshStage = BABYLON.Stage.Create();
  25535. /**
  25536. * @hidden
  25537. * Defines the actions happening just after a mesh has been drawn.
  25538. */
  25539. _this._afterRenderingMeshStage = BABYLON.Stage.Create();
  25540. /**
  25541. * @hidden
  25542. * Defines the actions happening just after a rendering group has been drawn.
  25543. */
  25544. _this._afterRenderingGroupDrawStage = BABYLON.Stage.Create();
  25545. /**
  25546. * @hidden
  25547. * Defines the actions happening just after the active camera has been drawn.
  25548. */
  25549. _this._afterCameraDrawStage = BABYLON.Stage.Create();
  25550. /**
  25551. * @hidden
  25552. * Defines the actions happening just after rendering all cameras and computing intersections.
  25553. */
  25554. _this._afterRenderStage = BABYLON.Stage.Create();
  25555. /**
  25556. * @hidden
  25557. * Defines the actions happening when a pointer move event happens.
  25558. */
  25559. _this._pointerMoveStage = BABYLON.Stage.Create();
  25560. /**
  25561. * @hidden
  25562. * Defines the actions happening when a pointer down event happens.
  25563. */
  25564. _this._pointerDownStage = BABYLON.Stage.Create();
  25565. /**
  25566. * @hidden
  25567. * Defines the actions happening when a pointer up event happens.
  25568. */
  25569. _this._pointerUpStage = BABYLON.Stage.Create();
  25570. _this._defaultMeshCandidates = {
  25571. data: [],
  25572. length: 0
  25573. };
  25574. _this._defaultSubMeshCandidates = {
  25575. data: [],
  25576. length: 0
  25577. };
  25578. _this._activeMeshesFrozen = false;
  25579. /** @hidden */
  25580. _this._allowPostProcessClearColor = true;
  25581. /**
  25582. * User updatable function that will return a deterministic frame time when engine is in deterministic lock step mode
  25583. */
  25584. _this.getDeterministicFrameTime = function () {
  25585. return 1000.0 / 60.0; // frame time in ms
  25586. };
  25587. _this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  25588. _this._blockMaterialDirtyMechanism = false;
  25589. _this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  25590. _this._engine.scenes.push(_this);
  25591. _this._uid = null;
  25592. _this._renderingManager = new BABYLON.RenderingManager(_this);
  25593. if (BABYLON.PostProcessManager) {
  25594. _this.postProcessManager = new BABYLON.PostProcessManager(_this);
  25595. }
  25596. if (BABYLON.Tools.IsWindowObjectExist()) {
  25597. _this.attachControl();
  25598. }
  25599. //collision coordinator initialization. For now legacy per default.
  25600. _this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  25601. // Uniform Buffer
  25602. _this._createUbo();
  25603. // Default Image processing definition
  25604. if (BABYLON.ImageProcessingConfiguration) {
  25605. _this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  25606. }
  25607. _this.setDefaultCandidateProviders();
  25608. return _this;
  25609. }
  25610. Object.defineProperty(Scene.prototype, "environmentTexture", {
  25611. /**
  25612. * Texture used in all pbr material as the reflection texture.
  25613. * As in the majority of the scene they are the same (exception for multi room and so on),
  25614. * this is easier to reference from here than from all the materials.
  25615. */
  25616. get: function () {
  25617. return this._environmentTexture;
  25618. },
  25619. /**
  25620. * Texture used in all pbr material as the reflection texture.
  25621. * As in the majority of the scene they are the same (exception for multi room and so on),
  25622. * this is easier to set here than in all the materials.
  25623. */
  25624. set: function (value) {
  25625. if (this._environmentTexture === value) {
  25626. return;
  25627. }
  25628. this._environmentTexture = value;
  25629. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25630. },
  25631. enumerable: true,
  25632. configurable: true
  25633. });
  25634. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  25635. /**
  25636. * Default image processing configuration used either in the rendering
  25637. * Forward main pass or through the imageProcessingPostProcess if present.
  25638. * As in the majority of the scene they are the same (exception for multi camera),
  25639. * this is easier to reference from here than from all the materials and post process.
  25640. *
  25641. * No setter as we it is a shared configuration, you can set the values instead.
  25642. */
  25643. get: function () {
  25644. return this._imageProcessingConfiguration;
  25645. },
  25646. enumerable: true,
  25647. configurable: true
  25648. });
  25649. Object.defineProperty(Scene.prototype, "forceWireframe", {
  25650. get: function () {
  25651. return this._forceWireframe;
  25652. },
  25653. /**
  25654. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  25655. */
  25656. set: function (value) {
  25657. if (this._forceWireframe === value) {
  25658. return;
  25659. }
  25660. this._forceWireframe = value;
  25661. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25662. },
  25663. enumerable: true,
  25664. configurable: true
  25665. });
  25666. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  25667. get: function () {
  25668. return this._forcePointsCloud;
  25669. },
  25670. /**
  25671. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  25672. */
  25673. set: function (value) {
  25674. if (this._forcePointsCloud === value) {
  25675. return;
  25676. }
  25677. this._forcePointsCloud = value;
  25678. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25679. },
  25680. enumerable: true,
  25681. configurable: true
  25682. });
  25683. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  25684. /**
  25685. * Gets or sets the animation properties override
  25686. */
  25687. get: function () {
  25688. return this._animationPropertiesOverride;
  25689. },
  25690. set: function (value) {
  25691. this._animationPropertiesOverride = value;
  25692. },
  25693. enumerable: true,
  25694. configurable: true
  25695. });
  25696. Object.defineProperty(Scene.prototype, "onDispose", {
  25697. /** Sets a function to be executed when this scene is disposed. */
  25698. set: function (callback) {
  25699. if (this._onDisposeObserver) {
  25700. this.onDisposeObservable.remove(this._onDisposeObserver);
  25701. }
  25702. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  25703. },
  25704. enumerable: true,
  25705. configurable: true
  25706. });
  25707. Object.defineProperty(Scene.prototype, "beforeRender", {
  25708. /** Sets a function to be executed before rendering this scene */
  25709. set: function (callback) {
  25710. if (this._onBeforeRenderObserver) {
  25711. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  25712. }
  25713. if (callback) {
  25714. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  25715. }
  25716. },
  25717. enumerable: true,
  25718. configurable: true
  25719. });
  25720. Object.defineProperty(Scene.prototype, "afterRender", {
  25721. /** Sets a function to be executed after rendering this scene */
  25722. set: function (callback) {
  25723. if (this._onAfterRenderObserver) {
  25724. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  25725. }
  25726. if (callback) {
  25727. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  25728. }
  25729. },
  25730. enumerable: true,
  25731. configurable: true
  25732. });
  25733. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  25734. /** Sets a function to be executed before rendering a camera*/
  25735. set: function (callback) {
  25736. if (this._onBeforeCameraRenderObserver) {
  25737. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  25738. }
  25739. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  25740. },
  25741. enumerable: true,
  25742. configurable: true
  25743. });
  25744. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  25745. /** Sets a function to be executed after rendering a camera*/
  25746. set: function (callback) {
  25747. if (this._onAfterCameraRenderObserver) {
  25748. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  25749. }
  25750. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  25751. },
  25752. enumerable: true,
  25753. configurable: true
  25754. });
  25755. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  25756. /**
  25757. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  25758. */
  25759. get: function () {
  25760. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  25761. },
  25762. enumerable: true,
  25763. configurable: true
  25764. });
  25765. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  25766. get: function () {
  25767. return this._useRightHandedSystem;
  25768. },
  25769. /**
  25770. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  25771. */
  25772. set: function (value) {
  25773. if (this._useRightHandedSystem === value) {
  25774. return;
  25775. }
  25776. this._useRightHandedSystem = value;
  25777. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25778. },
  25779. enumerable: true,
  25780. configurable: true
  25781. });
  25782. /**
  25783. * Sets the step Id used by deterministic lock step
  25784. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  25785. * @param newStepId defines the step Id
  25786. */
  25787. Scene.prototype.setStepId = function (newStepId) {
  25788. this._currentStepId = newStepId;
  25789. };
  25790. ;
  25791. /**
  25792. * Gets the step Id used by deterministic lock step
  25793. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  25794. * @returns the step Id
  25795. */
  25796. Scene.prototype.getStepId = function () {
  25797. return this._currentStepId;
  25798. };
  25799. ;
  25800. /**
  25801. * Gets the internal step used by deterministic lock step
  25802. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  25803. * @returns the internal step
  25804. */
  25805. Scene.prototype.getInternalStep = function () {
  25806. return this._currentInternalStep;
  25807. };
  25808. ;
  25809. Object.defineProperty(Scene.prototype, "fogEnabled", {
  25810. get: function () {
  25811. return this._fogEnabled;
  25812. },
  25813. /**
  25814. * Gets or sets a boolean indicating if fog is enabled on this scene
  25815. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25816. * (Default is true)
  25817. */
  25818. set: function (value) {
  25819. if (this._fogEnabled === value) {
  25820. return;
  25821. }
  25822. this._fogEnabled = value;
  25823. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25824. },
  25825. enumerable: true,
  25826. configurable: true
  25827. });
  25828. Object.defineProperty(Scene.prototype, "fogMode", {
  25829. get: function () {
  25830. return this._fogMode;
  25831. },
  25832. /**
  25833. * Gets or sets the fog mode to use
  25834. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25835. * | mode | value |
  25836. * | --- | --- |
  25837. * | FOGMODE_NONE | 0 |
  25838. * | FOGMODE_EXP | 1 |
  25839. * | FOGMODE_EXP2 | 2 |
  25840. * | FOGMODE_LINEAR | 3 |
  25841. */
  25842. set: function (value) {
  25843. if (this._fogMode === value) {
  25844. return;
  25845. }
  25846. this._fogMode = value;
  25847. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25848. },
  25849. enumerable: true,
  25850. configurable: true
  25851. });
  25852. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  25853. get: function () {
  25854. return this._shadowsEnabled;
  25855. },
  25856. /**
  25857. * Gets or sets a boolean indicating if shadows are enabled on this scene
  25858. */
  25859. set: function (value) {
  25860. if (this._shadowsEnabled === value) {
  25861. return;
  25862. }
  25863. this._shadowsEnabled = value;
  25864. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  25865. },
  25866. enumerable: true,
  25867. configurable: true
  25868. });
  25869. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  25870. get: function () {
  25871. return this._lightsEnabled;
  25872. },
  25873. /**
  25874. * Gets or sets a boolean indicating if lights are enabled on this scene
  25875. */
  25876. set: function (value) {
  25877. if (this._lightsEnabled === value) {
  25878. return;
  25879. }
  25880. this._lightsEnabled = value;
  25881. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  25882. },
  25883. enumerable: true,
  25884. configurable: true
  25885. });
  25886. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  25887. /** The default material used on meshes when no material is affected */
  25888. get: function () {
  25889. if (!this._defaultMaterial) {
  25890. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  25891. }
  25892. return this._defaultMaterial;
  25893. },
  25894. /** The default material used on meshes when no material is affected */
  25895. set: function (value) {
  25896. this._defaultMaterial = value;
  25897. },
  25898. enumerable: true,
  25899. configurable: true
  25900. });
  25901. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  25902. get: function () {
  25903. return this._texturesEnabled;
  25904. },
  25905. /**
  25906. * Gets or sets a boolean indicating if textures are enabled on this scene
  25907. */
  25908. set: function (value) {
  25909. if (this._texturesEnabled === value) {
  25910. return;
  25911. }
  25912. this._texturesEnabled = value;
  25913. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25914. },
  25915. enumerable: true,
  25916. configurable: true
  25917. });
  25918. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  25919. get: function () {
  25920. return this._skeletonsEnabled;
  25921. },
  25922. /**
  25923. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  25924. */
  25925. set: function (value) {
  25926. if (this._skeletonsEnabled === value) {
  25927. return;
  25928. }
  25929. this._skeletonsEnabled = value;
  25930. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  25931. },
  25932. enumerable: true,
  25933. configurable: true
  25934. });
  25935. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  25936. /** @hidden */
  25937. get: function () {
  25938. return this._alternateRendering;
  25939. },
  25940. enumerable: true,
  25941. configurable: true
  25942. });
  25943. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  25944. /**
  25945. * Gets the list of frustum planes (built from the active camera)
  25946. */
  25947. get: function () {
  25948. return this._frustumPlanes;
  25949. },
  25950. enumerable: true,
  25951. configurable: true
  25952. });
  25953. /**
  25954. * Registers the transient components if needed.
  25955. */
  25956. Scene.prototype._registerTransientComponents = function () {
  25957. // Register components that have been associated lately to the scene.
  25958. if (this._transientComponents.length > 0) {
  25959. for (var _i = 0, _a = this._transientComponents; _i < _a.length; _i++) {
  25960. var component = _a[_i];
  25961. component.register();
  25962. }
  25963. this._transientComponents = [];
  25964. }
  25965. };
  25966. /**
  25967. * @hidden
  25968. * Add a component to the scene.
  25969. * Note that the ccomponent could be registered on th next frame if this is called after
  25970. * the register component stage.
  25971. * @param component Defines the component to add to the scene
  25972. */
  25973. Scene.prototype._addComponent = function (component) {
  25974. this._components.push(component);
  25975. this._transientComponents.push(component);
  25976. var serializableComponent = component;
  25977. if (serializableComponent.addFromContainer) {
  25978. this._serializableComponents.push(serializableComponent);
  25979. }
  25980. };
  25981. /**
  25982. * @hidden
  25983. * Gets a component from the scene.
  25984. * @param name defines the name of the component to retrieve
  25985. * @returns the component or null if not present
  25986. */
  25987. Scene.prototype._getComponent = function (name) {
  25988. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  25989. var component = _a[_i];
  25990. if (component.name === name) {
  25991. return component;
  25992. }
  25993. }
  25994. return null;
  25995. };
  25996. /**
  25997. * @hidden
  25998. */
  25999. Scene.prototype._getDefaultMeshCandidates = function () {
  26000. this._defaultMeshCandidates.data = this.meshes;
  26001. this._defaultMeshCandidates.length = this.meshes.length;
  26002. return this._defaultMeshCandidates;
  26003. };
  26004. /**
  26005. * @hidden
  26006. */
  26007. Scene.prototype._getDefaultSubMeshCandidates = function (mesh) {
  26008. this._defaultSubMeshCandidates.data = mesh.subMeshes;
  26009. this._defaultSubMeshCandidates.length = mesh.subMeshes.length;
  26010. return this._defaultSubMeshCandidates;
  26011. };
  26012. /**
  26013. * Sets the default candidate providers for the scene.
  26014. * This sets the getActiveMeshCandidates, getActiveSubMeshCandidates, getIntersectingSubMeshCandidates
  26015. * and getCollidingSubMeshCandidates to their default function
  26016. */
  26017. Scene.prototype.setDefaultCandidateProviders = function () {
  26018. this.getActiveMeshCandidates = this._getDefaultMeshCandidates.bind(this);
  26019. this.getActiveSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  26020. this.getIntersectingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  26021. this.getCollidingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  26022. };
  26023. Object.defineProperty(Scene.prototype, "workerCollisions", {
  26024. /**
  26025. * Gets a boolean indicating if collisions are processed on a web worker
  26026. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  26027. */
  26028. get: function () {
  26029. return this._workerCollisions;
  26030. },
  26031. set: function (enabled) {
  26032. if (!BABYLON.CollisionCoordinatorLegacy) {
  26033. return;
  26034. }
  26035. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  26036. this._workerCollisions = enabled;
  26037. if (this.collisionCoordinator) {
  26038. this.collisionCoordinator.destroy();
  26039. }
  26040. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  26041. this.collisionCoordinator.init(this);
  26042. },
  26043. enumerable: true,
  26044. configurable: true
  26045. });
  26046. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  26047. /**
  26048. * Gets the mesh that is currently under the pointer
  26049. */
  26050. get: function () {
  26051. return this._pointerOverMesh;
  26052. },
  26053. enumerable: true,
  26054. configurable: true
  26055. });
  26056. Object.defineProperty(Scene.prototype, "pointerX", {
  26057. /**
  26058. * Gets the current on-screen X position of the pointer
  26059. */
  26060. get: function () {
  26061. return this._pointerX;
  26062. },
  26063. enumerable: true,
  26064. configurable: true
  26065. });
  26066. Object.defineProperty(Scene.prototype, "pointerY", {
  26067. /**
  26068. * Gets the current on-screen Y position of the pointer
  26069. */
  26070. get: function () {
  26071. return this._pointerY;
  26072. },
  26073. enumerable: true,
  26074. configurable: true
  26075. });
  26076. /**
  26077. * Gets the cached material (ie. the latest rendered one)
  26078. * @returns the cached material
  26079. */
  26080. Scene.prototype.getCachedMaterial = function () {
  26081. return this._cachedMaterial;
  26082. };
  26083. /**
  26084. * Gets the cached effect (ie. the latest rendered one)
  26085. * @returns the cached effect
  26086. */
  26087. Scene.prototype.getCachedEffect = function () {
  26088. return this._cachedEffect;
  26089. };
  26090. /**
  26091. * Gets the cached visibility state (ie. the latest rendered one)
  26092. * @returns the cached visibility state
  26093. */
  26094. Scene.prototype.getCachedVisibility = function () {
  26095. return this._cachedVisibility;
  26096. };
  26097. /**
  26098. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  26099. * @param material defines the current material
  26100. * @param effect defines the current effect
  26101. * @param visibility defines the current visibility state
  26102. * @returns true if one parameter is not cached
  26103. */
  26104. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  26105. if (visibility === void 0) { visibility = 1; }
  26106. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  26107. };
  26108. /**
  26109. * Gets the engine associated with the scene
  26110. * @returns an Engine
  26111. */
  26112. Scene.prototype.getEngine = function () {
  26113. return this._engine;
  26114. };
  26115. /**
  26116. * Gets the total number of vertices rendered per frame
  26117. * @returns the total number of vertices rendered per frame
  26118. */
  26119. Scene.prototype.getTotalVertices = function () {
  26120. return this._totalVertices.current;
  26121. };
  26122. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  26123. /**
  26124. * Gets the performance counter for total vertices
  26125. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  26126. */
  26127. get: function () {
  26128. return this._totalVertices;
  26129. },
  26130. enumerable: true,
  26131. configurable: true
  26132. });
  26133. /**
  26134. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  26135. * @returns the total number of active indices rendered per frame
  26136. */
  26137. Scene.prototype.getActiveIndices = function () {
  26138. return this._activeIndices.current;
  26139. };
  26140. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  26141. /**
  26142. * Gets the performance counter for active indices
  26143. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  26144. */
  26145. get: function () {
  26146. return this._activeIndices;
  26147. },
  26148. enumerable: true,
  26149. configurable: true
  26150. });
  26151. /**
  26152. * Gets the total number of active particles rendered per frame
  26153. * @returns the total number of active particles rendered per frame
  26154. */
  26155. Scene.prototype.getActiveParticles = function () {
  26156. return this._activeParticles.current;
  26157. };
  26158. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  26159. /**
  26160. * Gets the performance counter for active particles
  26161. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  26162. */
  26163. get: function () {
  26164. return this._activeParticles;
  26165. },
  26166. enumerable: true,
  26167. configurable: true
  26168. });
  26169. /**
  26170. * Gets the total number of active bones rendered per frame
  26171. * @returns the total number of active bones rendered per frame
  26172. */
  26173. Scene.prototype.getActiveBones = function () {
  26174. return this._activeBones.current;
  26175. };
  26176. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  26177. /**
  26178. * Gets the performance counter for active bones
  26179. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  26180. */
  26181. get: function () {
  26182. return this._activeBones;
  26183. },
  26184. enumerable: true,
  26185. configurable: true
  26186. });
  26187. /** @hidden */
  26188. Scene.prototype.getInterFramePerfCounter = function () {
  26189. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  26190. return 0;
  26191. };
  26192. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  26193. /** @hidden */
  26194. get: function () {
  26195. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  26196. return null;
  26197. },
  26198. enumerable: true,
  26199. configurable: true
  26200. });
  26201. /** @hidden */
  26202. Scene.prototype.getLastFrameDuration = function () {
  26203. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  26204. return 0;
  26205. };
  26206. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  26207. /** @hidden */
  26208. get: function () {
  26209. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  26210. return null;
  26211. },
  26212. enumerable: true,
  26213. configurable: true
  26214. });
  26215. /** @hidden */
  26216. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  26217. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  26218. return 0;
  26219. };
  26220. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  26221. /** @hidden */
  26222. get: function () {
  26223. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  26224. return null;
  26225. },
  26226. enumerable: true,
  26227. configurable: true
  26228. });
  26229. /**
  26230. * Gets the array of active meshes
  26231. * @returns an array of AbstractMesh
  26232. */
  26233. Scene.prototype.getActiveMeshes = function () {
  26234. return this._activeMeshes;
  26235. };
  26236. /** @hidden */
  26237. Scene.prototype.getRenderTargetsDuration = function () {
  26238. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  26239. return 0;
  26240. };
  26241. /** @hidden */
  26242. Scene.prototype.getRenderDuration = function () {
  26243. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  26244. return 0;
  26245. };
  26246. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  26247. /** @hidden */
  26248. get: function () {
  26249. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  26250. return null;
  26251. },
  26252. enumerable: true,
  26253. configurable: true
  26254. });
  26255. /** @hidden */
  26256. Scene.prototype.getParticlesDuration = function () {
  26257. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  26258. return 0;
  26259. };
  26260. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  26261. /** @hidden */
  26262. get: function () {
  26263. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  26264. return null;
  26265. },
  26266. enumerable: true,
  26267. configurable: true
  26268. });
  26269. /** @hidden */
  26270. Scene.prototype.getSpritesDuration = function () {
  26271. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  26272. return 0;
  26273. };
  26274. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  26275. /** @hidden */
  26276. get: function () {
  26277. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  26278. return null;
  26279. },
  26280. enumerable: true,
  26281. configurable: true
  26282. });
  26283. /**
  26284. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  26285. * @returns a number
  26286. */
  26287. Scene.prototype.getAnimationRatio = function () {
  26288. return this._animationRatio !== undefined ? this._animationRatio : 1;
  26289. };
  26290. /**
  26291. * Gets an unique Id for the current render phase
  26292. * @returns a number
  26293. */
  26294. Scene.prototype.getRenderId = function () {
  26295. return this._renderId;
  26296. };
  26297. /**
  26298. * Gets an unique Id for the current frame
  26299. * @returns a number
  26300. */
  26301. Scene.prototype.getFrameId = function () {
  26302. return this._frameId;
  26303. };
  26304. /** Call this function if you want to manually increment the render Id*/
  26305. Scene.prototype.incrementRenderId = function () {
  26306. this._renderId++;
  26307. };
  26308. Scene.prototype._updatePointerPosition = function (evt) {
  26309. var canvasRect = this._engine.getRenderingCanvasClientRect();
  26310. if (!canvasRect) {
  26311. return;
  26312. }
  26313. this._pointerX = evt.clientX - canvasRect.left;
  26314. this._pointerY = evt.clientY - canvasRect.top;
  26315. this._unTranslatedPointerX = this._pointerX;
  26316. this._unTranslatedPointerY = this._pointerY;
  26317. };
  26318. Scene.prototype._createUbo = function () {
  26319. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  26320. this._sceneUbo.addUniform("viewProjection", 16);
  26321. this._sceneUbo.addUniform("view", 16);
  26322. };
  26323. Scene.prototype._createAlternateUbo = function () {
  26324. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  26325. this._alternateSceneUbo.addUniform("viewProjection", 16);
  26326. this._alternateSceneUbo.addUniform("view", 16);
  26327. };
  26328. // Pointers handling
  26329. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  26330. if (pointerInfo.pickInfo) {
  26331. if (!pointerInfo.pickInfo.ray) {
  26332. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  26333. }
  26334. }
  26335. };
  26336. /**
  26337. * Use this method to simulate a pointer move on a mesh
  26338. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  26339. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  26340. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  26341. * @returns the current scene
  26342. */
  26343. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  26344. var evt = new PointerEvent("pointermove", pointerEventInit);
  26345. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  26346. return this;
  26347. }
  26348. return this._processPointerMove(pickResult, evt);
  26349. };
  26350. Scene.prototype._processPointerMove = function (pickResult, evt) {
  26351. var canvas = this._engine.getRenderingCanvas();
  26352. if (!canvas) {
  26353. return this;
  26354. }
  26355. // Restore pointer
  26356. canvas.style.cursor = this.defaultCursor;
  26357. var isMeshPicked = (pickResult && pickResult.hit && pickResult.pickedMesh) ? true : false;
  26358. if (isMeshPicked) {
  26359. this.setPointerOverMesh(pickResult.pickedMesh);
  26360. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  26361. if (this._pointerOverMesh.actionManager.hoverCursor) {
  26362. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  26363. }
  26364. else {
  26365. canvas.style.cursor = this.hoverCursor;
  26366. }
  26367. }
  26368. }
  26369. else {
  26370. this.setPointerOverMesh(null);
  26371. }
  26372. for (var _i = 0, _a = this._pointerMoveStage; _i < _a.length; _i++) {
  26373. var step = _a[_i];
  26374. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, isMeshPicked, canvas);
  26375. }
  26376. if (pickResult) {
  26377. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  26378. if (this.onPointerMove) {
  26379. this.onPointerMove(evt, pickResult, type);
  26380. }
  26381. if (this.onPointerObservable.hasObservers()) {
  26382. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  26383. this._setRayOnPointerInfo(pi);
  26384. this.onPointerObservable.notifyObservers(pi, type);
  26385. }
  26386. }
  26387. return this;
  26388. };
  26389. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  26390. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  26391. if (pickResult) {
  26392. pi.ray = pickResult.ray;
  26393. }
  26394. this.onPrePointerObservable.notifyObservers(pi, type);
  26395. if (pi.skipOnPointerObservable) {
  26396. return true;
  26397. }
  26398. else {
  26399. return false;
  26400. }
  26401. };
  26402. /**
  26403. * Use this method to simulate a pointer down on a mesh
  26404. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  26405. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  26406. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  26407. * @returns the current scene
  26408. */
  26409. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  26410. var evt = new PointerEvent("pointerdown", pointerEventInit);
  26411. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  26412. return this;
  26413. }
  26414. return this._processPointerDown(pickResult, evt);
  26415. };
  26416. Scene.prototype._processPointerDown = function (pickResult, evt) {
  26417. var _this = this;
  26418. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  26419. this._pickedDownMesh = pickResult.pickedMesh;
  26420. var actionManager = pickResult.pickedMesh.actionManager;
  26421. if (actionManager) {
  26422. if (actionManager.hasPickTriggers) {
  26423. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26424. switch (evt.button) {
  26425. case 0:
  26426. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26427. break;
  26428. case 1:
  26429. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26430. break;
  26431. case 2:
  26432. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26433. break;
  26434. }
  26435. }
  26436. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  26437. window.setTimeout(function () {
  26438. 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);
  26439. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  26440. if (_this._totalPointersPressed !== 0 &&
  26441. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  26442. !_this._isPointerSwiping()) {
  26443. _this._startingPointerTime = 0;
  26444. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26445. }
  26446. }
  26447. }, Scene.LongPressDelay);
  26448. }
  26449. }
  26450. }
  26451. else {
  26452. for (var _i = 0, _a = this._pointerDownStage; _i < _a.length; _i++) {
  26453. var step = _a[_i];
  26454. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
  26455. }
  26456. }
  26457. if (pickResult) {
  26458. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  26459. if (this.onPointerDown) {
  26460. this.onPointerDown(evt, pickResult, type);
  26461. }
  26462. if (this.onPointerObservable.hasObservers()) {
  26463. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  26464. this._setRayOnPointerInfo(pi);
  26465. this.onPointerObservable.notifyObservers(pi, type);
  26466. }
  26467. }
  26468. return this;
  26469. };
  26470. /**
  26471. * Use this method to simulate a pointer up on a mesh
  26472. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  26473. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  26474. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  26475. * @returns the current scene
  26476. */
  26477. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  26478. var evt = new PointerEvent("pointerup", pointerEventInit);
  26479. var clickInfo = new ClickInfo();
  26480. clickInfo.singleClick = true;
  26481. clickInfo.ignore = true;
  26482. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  26483. return this;
  26484. }
  26485. return this._processPointerUp(pickResult, evt, clickInfo);
  26486. };
  26487. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  26488. if (pickResult && pickResult && pickResult.pickedMesh) {
  26489. this._pickedUpMesh = pickResult.pickedMesh;
  26490. if (this._pickedDownMesh === this._pickedUpMesh) {
  26491. if (this.onPointerPick) {
  26492. this.onPointerPick(evt, pickResult);
  26493. }
  26494. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  26495. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  26496. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  26497. this._setRayOnPointerInfo(pi);
  26498. this.onPointerObservable.notifyObservers(pi, type_1);
  26499. }
  26500. }
  26501. if (pickResult.pickedMesh.actionManager) {
  26502. if (clickInfo.ignore) {
  26503. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26504. }
  26505. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  26506. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26507. }
  26508. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  26509. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26510. }
  26511. }
  26512. }
  26513. else {
  26514. if (!clickInfo.ignore) {
  26515. for (var _i = 0, _a = this._pointerUpStage; _i < _a.length; _i++) {
  26516. var step = _a[_i];
  26517. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
  26518. }
  26519. }
  26520. }
  26521. if (this._pickedDownMesh &&
  26522. this._pickedDownMesh.actionManager &&
  26523. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  26524. this._pickedDownMesh !== this._pickedUpMesh) {
  26525. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  26526. }
  26527. var type = BABYLON.PointerEventTypes.POINTERUP;
  26528. if (this.onPointerObservable.hasObservers()) {
  26529. if (!clickInfo.ignore) {
  26530. if (!clickInfo.hasSwiped) {
  26531. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  26532. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  26533. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  26534. this._setRayOnPointerInfo(pi);
  26535. this.onPointerObservable.notifyObservers(pi, type_2);
  26536. }
  26537. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  26538. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  26539. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  26540. this._setRayOnPointerInfo(pi);
  26541. this.onPointerObservable.notifyObservers(pi, type_3);
  26542. }
  26543. }
  26544. }
  26545. else {
  26546. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  26547. this._setRayOnPointerInfo(pi);
  26548. this.onPointerObservable.notifyObservers(pi, type);
  26549. }
  26550. }
  26551. if (this.onPointerUp) {
  26552. this.onPointerUp(evt, pickResult, type);
  26553. }
  26554. return this;
  26555. };
  26556. /**
  26557. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  26558. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  26559. * @returns true if the pointer was captured
  26560. */
  26561. Scene.prototype.isPointerCaptured = function (pointerId) {
  26562. if (pointerId === void 0) { pointerId = 0; }
  26563. return this._pointerCaptures[pointerId];
  26564. };
  26565. /** @hidden */
  26566. Scene.prototype._isPointerSwiping = function () {
  26567. return Math.abs(this._startingPointerPosition.x - this._pointerX) > Scene.DragMovementThreshold ||
  26568. Math.abs(this._startingPointerPosition.y - this._pointerY) > Scene.DragMovementThreshold;
  26569. };
  26570. /**
  26571. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  26572. * @param attachUp defines if you want to attach events to pointerup
  26573. * @param attachDown defines if you want to attach events to pointerdown
  26574. * @param attachMove defines if you want to attach events to pointermove
  26575. */
  26576. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  26577. var _this = this;
  26578. if (attachUp === void 0) { attachUp = true; }
  26579. if (attachDown === void 0) { attachDown = true; }
  26580. if (attachMove === void 0) { attachMove = true; }
  26581. this._initActionManager = function (act, clickInfo) {
  26582. if (!_this._meshPickProceed) {
  26583. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  26584. _this._currentPickResult = pickResult;
  26585. if (pickResult) {
  26586. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  26587. }
  26588. _this._meshPickProceed = true;
  26589. }
  26590. return act;
  26591. };
  26592. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  26593. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  26594. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  26595. btn !== _this._previousButtonPressed) {
  26596. _this._doubleClickOccured = false;
  26597. clickInfo.singleClick = true;
  26598. clickInfo.ignore = false;
  26599. cb(clickInfo, _this._currentPickResult);
  26600. }
  26601. };
  26602. this._initClickEvent = function (obs1, obs2, evt, cb) {
  26603. var clickInfo = new ClickInfo();
  26604. _this._currentPickResult = null;
  26605. var act = null;
  26606. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  26607. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  26608. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  26609. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  26610. act = _this._initActionManager(act, clickInfo);
  26611. if (act)
  26612. checkPicking = act.hasPickTriggers;
  26613. }
  26614. if (checkPicking) {
  26615. var btn = evt.button;
  26616. clickInfo.hasSwiped = _this._isPointerSwiping();
  26617. if (!clickInfo.hasSwiped) {
  26618. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  26619. if (!checkSingleClickImmediately) {
  26620. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  26621. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  26622. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  26623. act = _this._initActionManager(act, clickInfo);
  26624. if (act)
  26625. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  26626. }
  26627. }
  26628. if (checkSingleClickImmediately) {
  26629. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  26630. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  26631. btn !== _this._previousButtonPressed) {
  26632. clickInfo.singleClick = true;
  26633. cb(clickInfo, _this._currentPickResult);
  26634. }
  26635. }
  26636. // at least one double click is required to be check and exclusive double click is enabled
  26637. else {
  26638. // wait that no double click has been raised during the double click delay
  26639. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  26640. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  26641. }
  26642. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  26643. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  26644. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  26645. act = _this._initActionManager(act, clickInfo);
  26646. if (act)
  26647. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  26648. }
  26649. if (checkDoubleClick) {
  26650. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  26651. if (btn === _this._previousButtonPressed &&
  26652. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  26653. !_this._doubleClickOccured) {
  26654. // pointer has not moved for 2 clicks, it's a double click
  26655. if (!clickInfo.hasSwiped &&
  26656. !_this._isPointerSwiping()) {
  26657. _this._previousStartingPointerTime = 0;
  26658. _this._doubleClickOccured = true;
  26659. clickInfo.doubleClick = true;
  26660. clickInfo.ignore = false;
  26661. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  26662. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  26663. }
  26664. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  26665. cb(clickInfo, _this._currentPickResult);
  26666. }
  26667. // if the two successive clicks are too far, it's just two simple clicks
  26668. else {
  26669. _this._doubleClickOccured = false;
  26670. _this._previousStartingPointerTime = _this._startingPointerTime;
  26671. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  26672. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  26673. _this._previousButtonPressed = btn;
  26674. if (Scene.ExclusiveDoubleClickMode) {
  26675. if (_this._previousDelayedSimpleClickTimeout) {
  26676. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  26677. }
  26678. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  26679. cb(clickInfo, _this._previousPickResult);
  26680. }
  26681. else {
  26682. cb(clickInfo, _this._currentPickResult);
  26683. }
  26684. }
  26685. }
  26686. // just the first click of the double has been raised
  26687. else {
  26688. _this._doubleClickOccured = false;
  26689. _this._previousStartingPointerTime = _this._startingPointerTime;
  26690. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  26691. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  26692. _this._previousButtonPressed = btn;
  26693. }
  26694. }
  26695. }
  26696. }
  26697. clickInfo.ignore = true;
  26698. cb(clickInfo, _this._currentPickResult);
  26699. };
  26700. this._onPointerMove = function (evt) {
  26701. _this._updatePointerPosition(evt);
  26702. // PreObservable support
  26703. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  26704. return;
  26705. }
  26706. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  26707. return;
  26708. }
  26709. if (!_this.pointerMovePredicate) {
  26710. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  26711. }
  26712. // Meshes
  26713. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  26714. _this._processPointerMove(pickResult, evt);
  26715. };
  26716. this._onPointerDown = function (evt) {
  26717. _this._totalPointersPressed++;
  26718. _this._pickedDownMesh = null;
  26719. _this._meshPickProceed = false;
  26720. _this._updatePointerPosition(evt);
  26721. if (_this.preventDefaultOnPointerDown && canvas) {
  26722. evt.preventDefault();
  26723. canvas.focus();
  26724. }
  26725. // PreObservable support
  26726. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  26727. return;
  26728. }
  26729. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  26730. return;
  26731. }
  26732. _this._pointerCaptures[evt.pointerId] = true;
  26733. _this._startingPointerPosition.x = _this._pointerX;
  26734. _this._startingPointerPosition.y = _this._pointerY;
  26735. _this._startingPointerTime = Date.now();
  26736. if (!_this.pointerDownPredicate) {
  26737. _this.pointerDownPredicate = function (mesh) {
  26738. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  26739. };
  26740. }
  26741. // Meshes
  26742. _this._pickedDownMesh = null;
  26743. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  26744. _this._processPointerDown(pickResult, evt);
  26745. };
  26746. this._onPointerUp = function (evt) {
  26747. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  26748. return; // So we need to test it the pointer down was pressed before.
  26749. }
  26750. _this._totalPointersPressed--;
  26751. _this._pickedUpMesh = null;
  26752. _this._meshPickProceed = false;
  26753. _this._updatePointerPosition(evt);
  26754. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  26755. // PreObservable support
  26756. if (_this.onPrePointerObservable.hasObservers()) {
  26757. if (!clickInfo.ignore) {
  26758. if (!clickInfo.hasSwiped) {
  26759. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  26760. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  26761. return;
  26762. }
  26763. }
  26764. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  26765. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  26766. return;
  26767. }
  26768. }
  26769. }
  26770. }
  26771. else {
  26772. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  26773. return;
  26774. }
  26775. }
  26776. }
  26777. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  26778. return;
  26779. }
  26780. _this._pointerCaptures[evt.pointerId] = false;
  26781. if (!_this.pointerUpPredicate) {
  26782. _this.pointerUpPredicate = function (mesh) {
  26783. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  26784. };
  26785. }
  26786. // Meshes
  26787. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  26788. _this._initActionManager(null, clickInfo);
  26789. }
  26790. if (!pickResult) {
  26791. pickResult = _this._currentPickResult;
  26792. }
  26793. _this._processPointerUp(pickResult, evt, clickInfo);
  26794. _this._previousPickResult = _this._currentPickResult;
  26795. });
  26796. };
  26797. this._onKeyDown = function (evt) {
  26798. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  26799. if (_this.onPreKeyboardObservable.hasObservers()) {
  26800. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  26801. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  26802. if (pi.skipOnPointerObservable) {
  26803. return;
  26804. }
  26805. }
  26806. if (_this.onKeyboardObservable.hasObservers()) {
  26807. var pi = new BABYLON.KeyboardInfo(type, evt);
  26808. _this.onKeyboardObservable.notifyObservers(pi, type);
  26809. }
  26810. if (_this.actionManager) {
  26811. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  26812. }
  26813. };
  26814. this._onKeyUp = function (evt) {
  26815. var type = BABYLON.KeyboardEventTypes.KEYUP;
  26816. if (_this.onPreKeyboardObservable.hasObservers()) {
  26817. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  26818. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  26819. if (pi.skipOnPointerObservable) {
  26820. return;
  26821. }
  26822. }
  26823. if (_this.onKeyboardObservable.hasObservers()) {
  26824. var pi = new BABYLON.KeyboardInfo(type, evt);
  26825. _this.onKeyboardObservable.notifyObservers(pi, type);
  26826. }
  26827. if (_this.actionManager) {
  26828. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  26829. }
  26830. };
  26831. var engine = this.getEngine();
  26832. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  26833. if (!canvas) {
  26834. return;
  26835. }
  26836. canvas.addEventListener("keydown", _this._onKeyDown, false);
  26837. canvas.addEventListener("keyup", _this._onKeyUp, false);
  26838. });
  26839. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  26840. if (!canvas) {
  26841. return;
  26842. }
  26843. canvas.removeEventListener("keydown", _this._onKeyDown);
  26844. canvas.removeEventListener("keyup", _this._onKeyUp);
  26845. });
  26846. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  26847. var canvas = this._engine.getRenderingCanvas();
  26848. if (!canvas) {
  26849. return;
  26850. }
  26851. if (attachMove) {
  26852. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  26853. // Wheel
  26854. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  26855. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  26856. }
  26857. if (attachDown) {
  26858. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  26859. }
  26860. if (attachUp) {
  26861. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  26862. }
  26863. canvas.tabIndex = 1;
  26864. };
  26865. /** Detaches all event handlers*/
  26866. Scene.prototype.detachControl = function () {
  26867. var engine = this.getEngine();
  26868. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  26869. var canvas = engine.getRenderingCanvas();
  26870. if (!canvas) {
  26871. return;
  26872. }
  26873. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  26874. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  26875. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  26876. if (this._onCanvasBlurObserver) {
  26877. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  26878. }
  26879. if (this._onCanvasFocusObserver) {
  26880. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  26881. }
  26882. // Wheel
  26883. canvas.removeEventListener('mousewheel', this._onPointerMove);
  26884. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  26885. // Keyboard
  26886. canvas.removeEventListener("keydown", this._onKeyDown);
  26887. canvas.removeEventListener("keyup", this._onKeyUp);
  26888. // Observables
  26889. this.onKeyboardObservable.clear();
  26890. this.onPreKeyboardObservable.clear();
  26891. this.onPointerObservable.clear();
  26892. this.onPrePointerObservable.clear();
  26893. };
  26894. /**
  26895. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  26896. * Delay loaded resources are not taking in account
  26897. * @return true if all required resources are ready
  26898. */
  26899. Scene.prototype.isReady = function () {
  26900. if (this._isDisposed) {
  26901. return false;
  26902. }
  26903. if (this._pendingData.length > 0) {
  26904. return false;
  26905. }
  26906. var index;
  26907. var engine = this.getEngine();
  26908. // Geometries
  26909. for (index = 0; index < this.geometries.length; index++) {
  26910. var geometry = this.geometries[index];
  26911. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  26912. return false;
  26913. }
  26914. }
  26915. // Meshes
  26916. for (index = 0; index < this.meshes.length; index++) {
  26917. var mesh = this.meshes[index];
  26918. if (!mesh.isEnabled()) {
  26919. continue;
  26920. }
  26921. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  26922. continue;
  26923. }
  26924. if (!mesh.isReady(true)) {
  26925. return false;
  26926. }
  26927. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  26928. // Is Ready For Mesh
  26929. for (var _i = 0, _a = this._isReadyForMeshStage; _i < _a.length; _i++) {
  26930. var step = _a[_i];
  26931. if (!step.action(mesh, hardwareInstancedRendering)) {
  26932. return false;
  26933. }
  26934. }
  26935. }
  26936. // Post-processes
  26937. if (this.activeCameras && this.activeCameras.length > 0) {
  26938. for (var _b = 0, _c = this.activeCameras; _b < _c.length; _b++) {
  26939. var camera = _c[_b];
  26940. if (!camera.isReady(true)) {
  26941. return false;
  26942. }
  26943. }
  26944. }
  26945. else if (this.activeCamera) {
  26946. if (!this.activeCamera.isReady(true)) {
  26947. return false;
  26948. }
  26949. }
  26950. // Particles
  26951. for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
  26952. var particleSystem = _e[_d];
  26953. if (!particleSystem.isReady()) {
  26954. return false;
  26955. }
  26956. }
  26957. return true;
  26958. };
  26959. /** Resets all cached information relative to material (including effect and visibility) */
  26960. Scene.prototype.resetCachedMaterial = function () {
  26961. this._cachedMaterial = null;
  26962. this._cachedEffect = null;
  26963. this._cachedVisibility = null;
  26964. };
  26965. /**
  26966. * Registers a function to be called before every frame render
  26967. * @param func defines the function to register
  26968. */
  26969. Scene.prototype.registerBeforeRender = function (func) {
  26970. this.onBeforeRenderObservable.add(func);
  26971. };
  26972. /**
  26973. * Unregisters a function called before every frame render
  26974. * @param func defines the function to unregister
  26975. */
  26976. Scene.prototype.unregisterBeforeRender = function (func) {
  26977. this.onBeforeRenderObservable.removeCallback(func);
  26978. };
  26979. /**
  26980. * Registers a function to be called after every frame render
  26981. * @param func defines the function to register
  26982. */
  26983. Scene.prototype.registerAfterRender = function (func) {
  26984. this.onAfterRenderObservable.add(func);
  26985. };
  26986. /**
  26987. * Unregisters a function called after every frame render
  26988. * @param func defines the function to unregister
  26989. */
  26990. Scene.prototype.unregisterAfterRender = function (func) {
  26991. this.onAfterRenderObservable.removeCallback(func);
  26992. };
  26993. Scene.prototype._executeOnceBeforeRender = function (func) {
  26994. var _this = this;
  26995. var execFunc = function () {
  26996. func();
  26997. setTimeout(function () {
  26998. _this.unregisterBeforeRender(execFunc);
  26999. });
  27000. };
  27001. this.registerBeforeRender(execFunc);
  27002. };
  27003. /**
  27004. * The provided function will run before render once and will be disposed afterwards.
  27005. * A timeout delay can be provided so that the function will be executed in N ms.
  27006. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  27007. * @param func The function to be executed.
  27008. * @param timeout optional delay in ms
  27009. */
  27010. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  27011. var _this = this;
  27012. if (timeout !== undefined) {
  27013. setTimeout(function () {
  27014. _this._executeOnceBeforeRender(func);
  27015. }, timeout);
  27016. }
  27017. else {
  27018. this._executeOnceBeforeRender(func);
  27019. }
  27020. };
  27021. /** @hidden */
  27022. Scene.prototype._addPendingData = function (data) {
  27023. this._pendingData.push(data);
  27024. };
  27025. /** @hidden */
  27026. Scene.prototype._removePendingData = function (data) {
  27027. var wasLoading = this.isLoading;
  27028. var index = this._pendingData.indexOf(data);
  27029. if (index !== -1) {
  27030. this._pendingData.splice(index, 1);
  27031. }
  27032. if (wasLoading && !this.isLoading) {
  27033. this.onDataLoadedObservable.notifyObservers(this);
  27034. }
  27035. };
  27036. /**
  27037. * Returns the number of items waiting to be loaded
  27038. * @returns the number of items waiting to be loaded
  27039. */
  27040. Scene.prototype.getWaitingItemsCount = function () {
  27041. return this._pendingData.length;
  27042. };
  27043. Object.defineProperty(Scene.prototype, "isLoading", {
  27044. /**
  27045. * Returns a boolean indicating if the scene is still loading data
  27046. */
  27047. get: function () {
  27048. return this._pendingData.length > 0;
  27049. },
  27050. enumerable: true,
  27051. configurable: true
  27052. });
  27053. /**
  27054. * Registers a function to be executed when the scene is ready
  27055. * @param {Function} func - the function to be executed
  27056. */
  27057. Scene.prototype.executeWhenReady = function (func) {
  27058. var _this = this;
  27059. this.onReadyObservable.add(func);
  27060. if (this._executeWhenReadyTimeoutId !== -1) {
  27061. return;
  27062. }
  27063. this._executeWhenReadyTimeoutId = setTimeout(function () {
  27064. _this._checkIsReady();
  27065. }, 150);
  27066. };
  27067. /**
  27068. * Returns a promise that resolves when the scene is ready
  27069. * @returns A promise that resolves when the scene is ready
  27070. */
  27071. Scene.prototype.whenReadyAsync = function () {
  27072. var _this = this;
  27073. return new Promise(function (resolve) {
  27074. _this.executeWhenReady(function () {
  27075. resolve();
  27076. });
  27077. });
  27078. };
  27079. /** @hidden */
  27080. Scene.prototype._checkIsReady = function () {
  27081. var _this = this;
  27082. this._registerTransientComponents();
  27083. if (this.isReady()) {
  27084. this.onReadyObservable.notifyObservers(this);
  27085. this.onReadyObservable.clear();
  27086. this._executeWhenReadyTimeoutId = -1;
  27087. return;
  27088. }
  27089. this._executeWhenReadyTimeoutId = setTimeout(function () {
  27090. _this._checkIsReady();
  27091. }, 150);
  27092. };
  27093. // Animations
  27094. /**
  27095. * Will start the animation sequence of a given target
  27096. * @param target defines the target
  27097. * @param from defines from which frame should animation start
  27098. * @param to defines until which frame should animation run.
  27099. * @param weight defines the weight to apply to the animation (1.0 by default)
  27100. * @param loop defines if the animation loops
  27101. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  27102. * @param onAnimationEnd defines the function to be executed when the animation ends
  27103. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  27104. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  27105. * @returns the animatable object created for this animation
  27106. */
  27107. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable, targetMask) {
  27108. if (weight === void 0) { weight = 1.0; }
  27109. if (speedRatio === void 0) { speedRatio = 1.0; }
  27110. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false, targetMask);
  27111. returnedAnimatable.weight = weight;
  27112. return returnedAnimatable;
  27113. };
  27114. /**
  27115. * Will start the animation sequence of a given target
  27116. * @param target defines the target
  27117. * @param from defines from which frame should animation start
  27118. * @param to defines until which frame should animation run.
  27119. * @param loop defines if the animation loops
  27120. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  27121. * @param onAnimationEnd defines the function to be executed when the animation ends
  27122. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  27123. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  27124. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  27125. * @returns the animatable object created for this animation
  27126. */
  27127. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask) {
  27128. if (speedRatio === void 0) { speedRatio = 1.0; }
  27129. if (stopCurrent === void 0) { stopCurrent = true; }
  27130. if (from > to && speedRatio > 0) {
  27131. speedRatio *= -1;
  27132. }
  27133. if (stopCurrent) {
  27134. this.stopAnimation(target, undefined, targetMask);
  27135. }
  27136. if (!animatable) {
  27137. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  27138. }
  27139. var shouldRunTargetAnimations = targetMask ? targetMask(target) : true;
  27140. // Local animations
  27141. if (target.animations && shouldRunTargetAnimations) {
  27142. animatable.appendAnimations(target, target.animations);
  27143. }
  27144. // Children animations
  27145. if (target.getAnimatables) {
  27146. var animatables = target.getAnimatables();
  27147. for (var index = 0; index < animatables.length; index++) {
  27148. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask);
  27149. }
  27150. }
  27151. animatable.reset();
  27152. return animatable;
  27153. };
  27154. /**
  27155. * Begin a new animation on a given node
  27156. * @param target defines the target where the animation will take place
  27157. * @param animations defines the list of animations to start
  27158. * @param from defines the initial value
  27159. * @param to defines the final value
  27160. * @param loop defines if you want animation to loop (off by default)
  27161. * @param speedRatio defines the speed ratio to apply to all animations
  27162. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  27163. * @returns the list of created animatables
  27164. */
  27165. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  27166. if (speedRatio === undefined) {
  27167. speedRatio = 1.0;
  27168. }
  27169. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  27170. return animatable;
  27171. };
  27172. /**
  27173. * Begin a new animation on a given node and its hierarchy
  27174. * @param target defines the root node where the animation will take place
  27175. * @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.
  27176. * @param animations defines the list of animations to start
  27177. * @param from defines the initial value
  27178. * @param to defines the final value
  27179. * @param loop defines if you want animation to loop (off by default)
  27180. * @param speedRatio defines the speed ratio to apply to all animations
  27181. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  27182. * @returns the list of animatables created for all nodes
  27183. */
  27184. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  27185. var children = target.getDescendants(directDescendantsOnly);
  27186. var result = [];
  27187. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  27188. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  27189. var child = children_1[_i];
  27190. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  27191. }
  27192. return result;
  27193. };
  27194. /**
  27195. * Gets the animatable associated with a specific target
  27196. * @param target defines the target of the animatable
  27197. * @returns the required animatable if found
  27198. */
  27199. Scene.prototype.getAnimatableByTarget = function (target) {
  27200. for (var index = 0; index < this._activeAnimatables.length; index++) {
  27201. if (this._activeAnimatables[index].target === target) {
  27202. return this._activeAnimatables[index];
  27203. }
  27204. }
  27205. return null;
  27206. };
  27207. /**
  27208. * Gets all animatables associated with a given target
  27209. * @param target defines the target to look animatables for
  27210. * @returns an array of Animatables
  27211. */
  27212. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  27213. var result = [];
  27214. for (var index = 0; index < this._activeAnimatables.length; index++) {
  27215. if (this._activeAnimatables[index].target === target) {
  27216. result.push(this._activeAnimatables[index]);
  27217. }
  27218. }
  27219. return result;
  27220. };
  27221. Object.defineProperty(Scene.prototype, "animatables", {
  27222. /**
  27223. * Gets all animatable attached to the scene
  27224. */
  27225. get: function () {
  27226. return this._activeAnimatables;
  27227. },
  27228. enumerable: true,
  27229. configurable: true
  27230. });
  27231. /**
  27232. * Will stop the animation of the given target
  27233. * @param target - the target
  27234. * @param animationName - the name of the animation to stop (all animations will be stopped if both this and targetMask are empty)
  27235. * @param targetMask - a function that determines if the animation should be stopped based on its target (all animations will be stopped if both this and animationName are empty)
  27236. */
  27237. Scene.prototype.stopAnimation = function (target, animationName, targetMask) {
  27238. var animatables = this.getAllAnimatablesByTarget(target);
  27239. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  27240. var animatable = animatables_1[_i];
  27241. animatable.stop(animationName, targetMask);
  27242. }
  27243. };
  27244. /**
  27245. * Stops and removes all animations that have been applied to the scene
  27246. */
  27247. Scene.prototype.stopAllAnimations = function () {
  27248. if (this._activeAnimatables) {
  27249. for (var i = 0; i < this._activeAnimatables.length; i++) {
  27250. this._activeAnimatables[i].stop();
  27251. }
  27252. this._activeAnimatables = [];
  27253. }
  27254. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  27255. var group = _a[_i];
  27256. group.stop();
  27257. }
  27258. };
  27259. Scene.prototype._animate = function () {
  27260. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  27261. return;
  27262. }
  27263. // Getting time
  27264. var now = BABYLON.Tools.Now;
  27265. if (!this._animationTimeLast) {
  27266. if (this._pendingData.length > 0) {
  27267. return;
  27268. }
  27269. this._animationTimeLast = now;
  27270. }
  27271. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  27272. this._animationTime += deltaTime;
  27273. this._animationTimeLast = now;
  27274. for (var index = 0; index < this._activeAnimatables.length; index++) {
  27275. this._activeAnimatables[index]._animate(this._animationTime);
  27276. }
  27277. // Late animation bindings
  27278. this._processLateAnimationBindings();
  27279. };
  27280. /** @hidden */
  27281. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  27282. var target = runtimeAnimation.target;
  27283. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  27284. if (!target._lateAnimationHolders) {
  27285. target._lateAnimationHolders = {};
  27286. }
  27287. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  27288. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  27289. totalWeight: 0,
  27290. animations: [],
  27291. originalValue: originalValue
  27292. };
  27293. }
  27294. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  27295. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  27296. };
  27297. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  27298. var normalizer = 1.0;
  27299. var finalPosition = BABYLON.Tmp.Vector3[0];
  27300. var finalScaling = BABYLON.Tmp.Vector3[1];
  27301. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  27302. var startIndex = 0;
  27303. var originalAnimation = holder.animations[0];
  27304. var originalValue = holder.originalValue;
  27305. var scale = 1;
  27306. if (holder.totalWeight < 1.0) {
  27307. // We need to mix the original value in
  27308. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  27309. scale = 1.0 - holder.totalWeight;
  27310. }
  27311. else {
  27312. startIndex = 1;
  27313. // We need to normalize the weights
  27314. normalizer = holder.totalWeight;
  27315. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  27316. scale = originalAnimation.weight / normalizer;
  27317. if (scale == 1) {
  27318. return originalAnimation.currentValue;
  27319. }
  27320. }
  27321. finalScaling.scaleInPlace(scale);
  27322. finalPosition.scaleInPlace(scale);
  27323. finalQuaternion.scaleInPlace(scale);
  27324. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  27325. var runtimeAnimation = holder.animations[animIndex];
  27326. var scale = runtimeAnimation.weight / normalizer;
  27327. var currentPosition = BABYLON.Tmp.Vector3[2];
  27328. var currentScaling = BABYLON.Tmp.Vector3[3];
  27329. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  27330. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  27331. currentScaling.scaleAndAddToRef(scale, finalScaling);
  27332. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  27333. currentPosition.scaleAndAddToRef(scale, finalPosition);
  27334. }
  27335. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  27336. return originalAnimation._workValue;
  27337. };
  27338. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder, refQuaternion) {
  27339. var originalAnimation = holder.animations[0];
  27340. var originalValue = holder.originalValue;
  27341. if (holder.animations.length === 1) {
  27342. BABYLON.Quaternion.SlerpToRef(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight), refQuaternion);
  27343. return refQuaternion;
  27344. }
  27345. var normalizer = 1.0;
  27346. var quaternions;
  27347. var weights;
  27348. if (holder.totalWeight < 1.0) {
  27349. var scale = 1.0 - holder.totalWeight;
  27350. quaternions = [];
  27351. weights = [];
  27352. quaternions.push(originalValue);
  27353. weights.push(scale);
  27354. }
  27355. else {
  27356. if (holder.animations.length === 2) { // Slerp as soon as we can
  27357. BABYLON.Quaternion.SlerpToRef(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight, refQuaternion);
  27358. return refQuaternion;
  27359. }
  27360. quaternions = [];
  27361. weights = [];
  27362. normalizer = holder.totalWeight;
  27363. }
  27364. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  27365. var runtimeAnimation = holder.animations[animIndex];
  27366. quaternions.push(runtimeAnimation.currentValue);
  27367. weights.push(runtimeAnimation.weight / normalizer);
  27368. }
  27369. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  27370. var cumulativeAmount = 0;
  27371. var cumulativeQuaternion = null;
  27372. for (var index = 0; index < quaternions.length;) {
  27373. if (!cumulativeQuaternion) {
  27374. BABYLON.Quaternion.SlerpToRef(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]), refQuaternion);
  27375. cumulativeQuaternion = refQuaternion;
  27376. cumulativeAmount = weights[index] + weights[index + 1];
  27377. index += 2;
  27378. continue;
  27379. }
  27380. cumulativeAmount += weights[index];
  27381. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  27382. index++;
  27383. }
  27384. return cumulativeQuaternion;
  27385. };
  27386. Scene.prototype._processLateAnimationBindings = function () {
  27387. if (!this._registeredForLateAnimationBindings.length) {
  27388. return;
  27389. }
  27390. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  27391. var target = this._registeredForLateAnimationBindings.data[index];
  27392. for (var path in target._lateAnimationHolders) {
  27393. var holder = target._lateAnimationHolders[path];
  27394. var originalAnimation = holder.animations[0];
  27395. var originalValue = holder.originalValue;
  27396. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  27397. var finalValue = target[path];
  27398. if (matrixDecomposeMode) {
  27399. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  27400. }
  27401. else {
  27402. var quaternionMode = originalValue.w !== undefined;
  27403. if (quaternionMode) {
  27404. finalValue = this._processLateAnimationBindingsForQuaternions(holder, finalValue || BABYLON.Quaternion.Identity());
  27405. }
  27406. else {
  27407. var startIndex = 0;
  27408. var normalizer = 1.0;
  27409. if (holder.totalWeight < 1.0) {
  27410. // We need to mix the original value in
  27411. if (originalValue.scale) {
  27412. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  27413. }
  27414. else {
  27415. finalValue = originalValue * (1.0 - holder.totalWeight);
  27416. }
  27417. }
  27418. else {
  27419. // We need to normalize the weights
  27420. normalizer = holder.totalWeight;
  27421. var scale_1 = originalAnimation.weight / normalizer;
  27422. if (scale_1 !== 1) {
  27423. if (originalAnimation.currentValue.scale) {
  27424. finalValue = originalAnimation.currentValue.scale(scale_1);
  27425. }
  27426. else {
  27427. finalValue = originalAnimation.currentValue * scale_1;
  27428. }
  27429. }
  27430. else {
  27431. finalValue = originalAnimation.currentValue;
  27432. }
  27433. startIndex = 1;
  27434. }
  27435. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  27436. var runtimeAnimation = holder.animations[animIndex];
  27437. var scale = runtimeAnimation.weight / normalizer;
  27438. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  27439. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  27440. }
  27441. else {
  27442. finalValue += runtimeAnimation.currentValue * scale;
  27443. }
  27444. }
  27445. }
  27446. }
  27447. target[path] = finalValue;
  27448. }
  27449. target._lateAnimationHolders = {};
  27450. }
  27451. this._registeredForLateAnimationBindings.reset();
  27452. };
  27453. // Matrix
  27454. /** @hidden */
  27455. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  27456. this._useAlternateCameraConfiguration = active;
  27457. };
  27458. /**
  27459. * Gets the current view matrix
  27460. * @returns a Matrix
  27461. */
  27462. Scene.prototype.getViewMatrix = function () {
  27463. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  27464. };
  27465. /**
  27466. * Gets the current projection matrix
  27467. * @returns a Matrix
  27468. */
  27469. Scene.prototype.getProjectionMatrix = function () {
  27470. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  27471. };
  27472. /**
  27473. * Gets the current transform matrix
  27474. * @returns a Matrix made of View * Projection
  27475. */
  27476. Scene.prototype.getTransformMatrix = function () {
  27477. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  27478. };
  27479. /**
  27480. * Sets the current transform matrix
  27481. * @param view defines the View matrix to use
  27482. * @param projection defines the Projection matrix to use
  27483. */
  27484. Scene.prototype.setTransformMatrix = function (view, projection) {
  27485. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  27486. return;
  27487. }
  27488. this._viewUpdateFlag = view.updateFlag;
  27489. this._projectionUpdateFlag = projection.updateFlag;
  27490. this._viewMatrix = view;
  27491. this._projectionMatrix = projection;
  27492. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  27493. // Update frustum
  27494. if (!this._frustumPlanes) {
  27495. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  27496. }
  27497. else {
  27498. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  27499. }
  27500. if (this.activeCamera && this.activeCamera._alternateCamera) {
  27501. var otherCamera = this.activeCamera._alternateCamera;
  27502. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  27503. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  27504. }
  27505. if (this._sceneUbo.useUbo) {
  27506. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  27507. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  27508. this._sceneUbo.update();
  27509. }
  27510. };
  27511. /** @hidden */
  27512. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  27513. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  27514. return;
  27515. }
  27516. this._alternateViewUpdateFlag = view.updateFlag;
  27517. this._alternateProjectionUpdateFlag = projection.updateFlag;
  27518. this._alternateViewMatrix = view;
  27519. this._alternateProjectionMatrix = projection;
  27520. if (!this._alternateTransformMatrix) {
  27521. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  27522. }
  27523. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  27524. if (!this._alternateSceneUbo) {
  27525. this._createAlternateUbo();
  27526. }
  27527. if (this._alternateSceneUbo.useUbo) {
  27528. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  27529. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  27530. this._alternateSceneUbo.update();
  27531. }
  27532. };
  27533. /**
  27534. * Gets the uniform buffer used to store scene data
  27535. * @returns a UniformBuffer
  27536. */
  27537. Scene.prototype.getSceneUniformBuffer = function () {
  27538. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  27539. };
  27540. /**
  27541. * Gets an unique (relatively to the current scene) Id
  27542. * @returns an unique number for the scene
  27543. */
  27544. Scene.prototype.getUniqueId = function () {
  27545. var result = Scene._uniqueIdCounter;
  27546. Scene._uniqueIdCounter++;
  27547. return result;
  27548. };
  27549. /**
  27550. * Add a mesh to the list of scene's meshes
  27551. * @param newMesh defines the mesh to add
  27552. * @param recursive if all child meshes should also be added to the scene
  27553. */
  27554. Scene.prototype.addMesh = function (newMesh, recursive) {
  27555. var _this = this;
  27556. if (recursive === void 0) { recursive = false; }
  27557. this.meshes.push(newMesh);
  27558. //notify the collision coordinator
  27559. if (this.collisionCoordinator) {
  27560. this.collisionCoordinator.onMeshAdded(newMesh);
  27561. }
  27562. newMesh._resyncLightSources();
  27563. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  27564. if (recursive) {
  27565. newMesh.getChildMeshes().forEach(function (m) {
  27566. _this.addMesh(m);
  27567. });
  27568. }
  27569. };
  27570. /**
  27571. * Remove a mesh for the list of scene's meshes
  27572. * @param toRemove defines the mesh to remove
  27573. * @param recursive if all child meshes should also be removed from the scene
  27574. * @returns the index where the mesh was in the mesh list
  27575. */
  27576. Scene.prototype.removeMesh = function (toRemove, recursive) {
  27577. var _this = this;
  27578. if (recursive === void 0) { recursive = false; }
  27579. var index = this.meshes.indexOf(toRemove);
  27580. if (index !== -1) {
  27581. // Remove from the scene if mesh found
  27582. this.meshes.splice(index, 1);
  27583. }
  27584. this.onMeshRemovedObservable.notifyObservers(toRemove);
  27585. if (recursive) {
  27586. toRemove.getChildMeshes().forEach(function (m) {
  27587. _this.removeMesh(m);
  27588. });
  27589. }
  27590. return index;
  27591. };
  27592. /**
  27593. * Add a transform node to the list of scene's transform nodes
  27594. * @param newTransformNode defines the transform node to add
  27595. */
  27596. Scene.prototype.addTransformNode = function (newTransformNode) {
  27597. this.transformNodes.push(newTransformNode);
  27598. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  27599. };
  27600. /**
  27601. * Remove a transform node for the list of scene's transform nodes
  27602. * @param toRemove defines the transform node to remove
  27603. * @returns the index where the transform node was in the transform node list
  27604. */
  27605. Scene.prototype.removeTransformNode = function (toRemove) {
  27606. var index = this.transformNodes.indexOf(toRemove);
  27607. if (index !== -1) {
  27608. // Remove from the scene if found
  27609. this.transformNodes.splice(index, 1);
  27610. }
  27611. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  27612. return index;
  27613. };
  27614. /**
  27615. * Remove a skeleton for the list of scene's skeletons
  27616. * @param toRemove defines the skeleton to remove
  27617. * @returns the index where the skeleton was in the skeleton list
  27618. */
  27619. Scene.prototype.removeSkeleton = function (toRemove) {
  27620. var index = this.skeletons.indexOf(toRemove);
  27621. if (index !== -1) {
  27622. // Remove from the scene if found
  27623. this.skeletons.splice(index, 1);
  27624. }
  27625. return index;
  27626. };
  27627. /**
  27628. * Remove a morph target for the list of scene's morph targets
  27629. * @param toRemove defines the morph target to remove
  27630. * @returns the index where the morph target was in the morph target list
  27631. */
  27632. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  27633. var index = this.morphTargetManagers.indexOf(toRemove);
  27634. if (index !== -1) {
  27635. // Remove from the scene if found
  27636. this.morphTargetManagers.splice(index, 1);
  27637. }
  27638. return index;
  27639. };
  27640. /**
  27641. * Remove a light for the list of scene's lights
  27642. * @param toRemove defines the light to remove
  27643. * @returns the index where the light was in the light list
  27644. */
  27645. Scene.prototype.removeLight = function (toRemove) {
  27646. var index = this.lights.indexOf(toRemove);
  27647. if (index !== -1) {
  27648. // Remove from meshes
  27649. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  27650. var mesh = _a[_i];
  27651. mesh._removeLightSource(toRemove);
  27652. }
  27653. // Remove from the scene if mesh found
  27654. this.lights.splice(index, 1);
  27655. this.sortLightsByPriority();
  27656. }
  27657. this.onLightRemovedObservable.notifyObservers(toRemove);
  27658. return index;
  27659. };
  27660. /**
  27661. * Remove a camera for the list of scene's cameras
  27662. * @param toRemove defines the camera to remove
  27663. * @returns the index where the camera was in the camera list
  27664. */
  27665. Scene.prototype.removeCamera = function (toRemove) {
  27666. var index = this.cameras.indexOf(toRemove);
  27667. if (index !== -1) {
  27668. // Remove from the scene if mesh found
  27669. this.cameras.splice(index, 1);
  27670. }
  27671. // Remove from activeCameras
  27672. var index2 = this.activeCameras.indexOf(toRemove);
  27673. if (index2 !== -1) {
  27674. // Remove from the scene if mesh found
  27675. this.activeCameras.splice(index2, 1);
  27676. }
  27677. // Reset the activeCamera
  27678. if (this.activeCamera === toRemove) {
  27679. if (this.cameras.length > 0) {
  27680. this.activeCamera = this.cameras[0];
  27681. }
  27682. else {
  27683. this.activeCamera = null;
  27684. }
  27685. }
  27686. this.onCameraRemovedObservable.notifyObservers(toRemove);
  27687. return index;
  27688. };
  27689. /**
  27690. * Remove a particle system for the list of scene's particle systems
  27691. * @param toRemove defines the particle system to remove
  27692. * @returns the index where the particle system was in the particle system list
  27693. */
  27694. Scene.prototype.removeParticleSystem = function (toRemove) {
  27695. var index = this.particleSystems.indexOf(toRemove);
  27696. if (index !== -1) {
  27697. this.particleSystems.splice(index, 1);
  27698. }
  27699. return index;
  27700. };
  27701. /**
  27702. * Remove a animation for the list of scene's animations
  27703. * @param toRemove defines the animation to remove
  27704. * @returns the index where the animation was in the animation list
  27705. */
  27706. Scene.prototype.removeAnimation = function (toRemove) {
  27707. var index = this.animations.indexOf(toRemove);
  27708. if (index !== -1) {
  27709. this.animations.splice(index, 1);
  27710. }
  27711. return index;
  27712. };
  27713. /**
  27714. * Removes the given animation group from this scene.
  27715. * @param toRemove The animation group to remove
  27716. * @returns The index of the removed animation group
  27717. */
  27718. Scene.prototype.removeAnimationGroup = function (toRemove) {
  27719. var index = this.animationGroups.indexOf(toRemove);
  27720. if (index !== -1) {
  27721. this.animationGroups.splice(index, 1);
  27722. }
  27723. return index;
  27724. };
  27725. /**
  27726. * Removes the given multi-material from this scene.
  27727. * @param toRemove The multi-material to remove
  27728. * @returns The index of the removed multi-material
  27729. */
  27730. Scene.prototype.removeMultiMaterial = function (toRemove) {
  27731. var index = this.multiMaterials.indexOf(toRemove);
  27732. if (index !== -1) {
  27733. this.multiMaterials.splice(index, 1);
  27734. }
  27735. return index;
  27736. };
  27737. /**
  27738. * Removes the given material from this scene.
  27739. * @param toRemove The material to remove
  27740. * @returns The index of the removed material
  27741. */
  27742. Scene.prototype.removeMaterial = function (toRemove) {
  27743. var index = this.materials.indexOf(toRemove);
  27744. if (index !== -1) {
  27745. this.materials.splice(index, 1);
  27746. }
  27747. this.onMaterialRemovedObservable.notifyObservers(toRemove);
  27748. return index;
  27749. };
  27750. /**
  27751. * Removes the given action manager from this scene.
  27752. * @param toRemove The action manager to remove
  27753. * @returns The index of the removed action manager
  27754. */
  27755. Scene.prototype.removeActionManager = function (toRemove) {
  27756. var index = this.actionManagers.indexOf(toRemove);
  27757. if (index !== -1) {
  27758. this.actionManagers.splice(index, 1);
  27759. }
  27760. return index;
  27761. };
  27762. /**
  27763. * Removes the given texture from this scene.
  27764. * @param toRemove The texture to remove
  27765. * @returns The index of the removed texture
  27766. */
  27767. Scene.prototype.removeTexture = function (toRemove) {
  27768. var index = this.textures.indexOf(toRemove);
  27769. if (index !== -1) {
  27770. this.textures.splice(index, 1);
  27771. }
  27772. this.onTextureRemovedObservable.notifyObservers(toRemove);
  27773. return index;
  27774. };
  27775. /**
  27776. * Adds the given light to this scene
  27777. * @param newLight The light to add
  27778. */
  27779. Scene.prototype.addLight = function (newLight) {
  27780. this.lights.push(newLight);
  27781. this.sortLightsByPriority();
  27782. // Add light to all meshes (To support if the light is removed and then readded)
  27783. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  27784. var mesh = _a[_i];
  27785. if (mesh._lightSources.indexOf(newLight) === -1) {
  27786. mesh._lightSources.push(newLight);
  27787. mesh._resyncLightSources();
  27788. }
  27789. }
  27790. this.onNewLightAddedObservable.notifyObservers(newLight);
  27791. };
  27792. /**
  27793. * Sorts the list list based on light priorities
  27794. */
  27795. Scene.prototype.sortLightsByPriority = function () {
  27796. if (this.requireLightSorting) {
  27797. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  27798. }
  27799. };
  27800. /**
  27801. * Adds the given camera to this scene
  27802. * @param newCamera The camera to add
  27803. */
  27804. Scene.prototype.addCamera = function (newCamera) {
  27805. this.cameras.push(newCamera);
  27806. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  27807. };
  27808. /**
  27809. * Adds the given skeleton to this scene
  27810. * @param newSkeleton The skeleton to add
  27811. */
  27812. Scene.prototype.addSkeleton = function (newSkeleton) {
  27813. this.skeletons.push(newSkeleton);
  27814. };
  27815. /**
  27816. * Adds the given particle system to this scene
  27817. * @param newParticleSystem The particle system to add
  27818. */
  27819. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  27820. this.particleSystems.push(newParticleSystem);
  27821. };
  27822. /**
  27823. * Adds the given animation to this scene
  27824. * @param newAnimation The animation to add
  27825. */
  27826. Scene.prototype.addAnimation = function (newAnimation) {
  27827. this.animations.push(newAnimation);
  27828. };
  27829. /**
  27830. * Adds the given animation group to this scene.
  27831. * @param newAnimationGroup The animation group to add
  27832. */
  27833. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  27834. this.animationGroups.push(newAnimationGroup);
  27835. };
  27836. /**
  27837. * Adds the given multi-material to this scene
  27838. * @param newMultiMaterial The multi-material to add
  27839. */
  27840. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  27841. this.multiMaterials.push(newMultiMaterial);
  27842. };
  27843. /**
  27844. * Adds the given material to this scene
  27845. * @param newMaterial The material to add
  27846. */
  27847. Scene.prototype.addMaterial = function (newMaterial) {
  27848. this.materials.push(newMaterial);
  27849. this.onNewMaterialAddedObservable.notifyObservers(newMaterial);
  27850. };
  27851. /**
  27852. * Adds the given morph target to this scene
  27853. * @param newMorphTargetManager The morph target to add
  27854. */
  27855. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  27856. this.morphTargetManagers.push(newMorphTargetManager);
  27857. };
  27858. /**
  27859. * Adds the given geometry to this scene
  27860. * @param newGeometry The geometry to add
  27861. */
  27862. Scene.prototype.addGeometry = function (newGeometry) {
  27863. this.geometries.push(newGeometry);
  27864. };
  27865. /**
  27866. * Adds the given action manager to this scene
  27867. * @param newActionManager The action manager to add
  27868. */
  27869. Scene.prototype.addActionManager = function (newActionManager) {
  27870. this.actionManagers.push(newActionManager);
  27871. };
  27872. /**
  27873. * Adds the given texture to this scene.
  27874. * @param newTexture The texture to add
  27875. */
  27876. Scene.prototype.addTexture = function (newTexture) {
  27877. this.textures.push(newTexture);
  27878. this.onNewTextureAddedObservable.notifyObservers(newTexture);
  27879. };
  27880. /**
  27881. * Switch active camera
  27882. * @param newCamera defines the new active camera
  27883. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  27884. */
  27885. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  27886. if (attachControl === void 0) { attachControl = true; }
  27887. var canvas = this._engine.getRenderingCanvas();
  27888. if (!canvas) {
  27889. return;
  27890. }
  27891. if (this.activeCamera) {
  27892. this.activeCamera.detachControl(canvas);
  27893. }
  27894. this.activeCamera = newCamera;
  27895. if (attachControl) {
  27896. newCamera.attachControl(canvas);
  27897. }
  27898. };
  27899. /**
  27900. * sets the active camera of the scene using its ID
  27901. * @param id defines the camera's ID
  27902. * @return the new active camera or null if none found.
  27903. */
  27904. Scene.prototype.setActiveCameraByID = function (id) {
  27905. var camera = this.getCameraByID(id);
  27906. if (camera) {
  27907. this.activeCamera = camera;
  27908. return camera;
  27909. }
  27910. return null;
  27911. };
  27912. /**
  27913. * sets the active camera of the scene using its name
  27914. * @param name defines the camera's name
  27915. * @returns the new active camera or null if none found.
  27916. */
  27917. Scene.prototype.setActiveCameraByName = function (name) {
  27918. var camera = this.getCameraByName(name);
  27919. if (camera) {
  27920. this.activeCamera = camera;
  27921. return camera;
  27922. }
  27923. return null;
  27924. };
  27925. /**
  27926. * get an animation group using its name
  27927. * @param name defines the material's name
  27928. * @return the animation group or null if none found.
  27929. */
  27930. Scene.prototype.getAnimationGroupByName = function (name) {
  27931. for (var index = 0; index < this.animationGroups.length; index++) {
  27932. if (this.animationGroups[index].name === name) {
  27933. return this.animationGroups[index];
  27934. }
  27935. }
  27936. return null;
  27937. };
  27938. /**
  27939. * get a material using its id
  27940. * @param id defines the material's ID
  27941. * @return the material or null if none found.
  27942. */
  27943. Scene.prototype.getMaterialByID = function (id) {
  27944. for (var index = 0; index < this.materials.length; index++) {
  27945. if (this.materials[index].id === id) {
  27946. return this.materials[index];
  27947. }
  27948. }
  27949. return null;
  27950. };
  27951. /**
  27952. * Gets a material using its name
  27953. * @param name defines the material's name
  27954. * @return the material or null if none found.
  27955. */
  27956. Scene.prototype.getMaterialByName = function (name) {
  27957. for (var index = 0; index < this.materials.length; index++) {
  27958. if (this.materials[index].name === name) {
  27959. return this.materials[index];
  27960. }
  27961. }
  27962. return null;
  27963. };
  27964. /**
  27965. * Gets a camera using its id
  27966. * @param id defines the id to look for
  27967. * @returns the camera or null if not found
  27968. */
  27969. Scene.prototype.getCameraByID = function (id) {
  27970. for (var index = 0; index < this.cameras.length; index++) {
  27971. if (this.cameras[index].id === id) {
  27972. return this.cameras[index];
  27973. }
  27974. }
  27975. return null;
  27976. };
  27977. /**
  27978. * Gets a camera using its unique id
  27979. * @param uniqueId defines the unique id to look for
  27980. * @returns the camera or null if not found
  27981. */
  27982. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  27983. for (var index = 0; index < this.cameras.length; index++) {
  27984. if (this.cameras[index].uniqueId === uniqueId) {
  27985. return this.cameras[index];
  27986. }
  27987. }
  27988. return null;
  27989. };
  27990. /**
  27991. * Gets a camera using its name
  27992. * @param name defines the camera's name
  27993. * @return the camera or null if none found.
  27994. */
  27995. Scene.prototype.getCameraByName = function (name) {
  27996. for (var index = 0; index < this.cameras.length; index++) {
  27997. if (this.cameras[index].name === name) {
  27998. return this.cameras[index];
  27999. }
  28000. }
  28001. return null;
  28002. };
  28003. /**
  28004. * Gets a bone using its id
  28005. * @param id defines the bone's id
  28006. * @return the bone or null if not found
  28007. */
  28008. Scene.prototype.getBoneByID = function (id) {
  28009. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  28010. var skeleton = this.skeletons[skeletonIndex];
  28011. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  28012. if (skeleton.bones[boneIndex].id === id) {
  28013. return skeleton.bones[boneIndex];
  28014. }
  28015. }
  28016. }
  28017. return null;
  28018. };
  28019. /**
  28020. * Gets a bone using its id
  28021. * @param name defines the bone's name
  28022. * @return the bone or null if not found
  28023. */
  28024. Scene.prototype.getBoneByName = function (name) {
  28025. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  28026. var skeleton = this.skeletons[skeletonIndex];
  28027. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  28028. if (skeleton.bones[boneIndex].name === name) {
  28029. return skeleton.bones[boneIndex];
  28030. }
  28031. }
  28032. }
  28033. return null;
  28034. };
  28035. /**
  28036. * Gets a light node using its name
  28037. * @param name defines the the light's name
  28038. * @return the light or null if none found.
  28039. */
  28040. Scene.prototype.getLightByName = function (name) {
  28041. for (var index = 0; index < this.lights.length; index++) {
  28042. if (this.lights[index].name === name) {
  28043. return this.lights[index];
  28044. }
  28045. }
  28046. return null;
  28047. };
  28048. /**
  28049. * Gets a light node using its id
  28050. * @param id defines the light's id
  28051. * @return the light or null if none found.
  28052. */
  28053. Scene.prototype.getLightByID = function (id) {
  28054. for (var index = 0; index < this.lights.length; index++) {
  28055. if (this.lights[index].id === id) {
  28056. return this.lights[index];
  28057. }
  28058. }
  28059. return null;
  28060. };
  28061. /**
  28062. * Gets a light node using its scene-generated unique ID
  28063. * @param uniqueId defines the light's unique id
  28064. * @return the light or null if none found.
  28065. */
  28066. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  28067. for (var index = 0; index < this.lights.length; index++) {
  28068. if (this.lights[index].uniqueId === uniqueId) {
  28069. return this.lights[index];
  28070. }
  28071. }
  28072. return null;
  28073. };
  28074. /**
  28075. * Gets a particle system by id
  28076. * @param id defines the particle system id
  28077. * @return the corresponding system or null if none found
  28078. */
  28079. Scene.prototype.getParticleSystemByID = function (id) {
  28080. for (var index = 0; index < this.particleSystems.length; index++) {
  28081. if (this.particleSystems[index].id === id) {
  28082. return this.particleSystems[index];
  28083. }
  28084. }
  28085. return null;
  28086. };
  28087. /**
  28088. * Gets a geometry using its ID
  28089. * @param id defines the geometry's id
  28090. * @return the geometry or null if none found.
  28091. */
  28092. Scene.prototype.getGeometryByID = function (id) {
  28093. for (var index = 0; index < this.geometries.length; index++) {
  28094. if (this.geometries[index].id === id) {
  28095. return this.geometries[index];
  28096. }
  28097. }
  28098. return null;
  28099. };
  28100. /**
  28101. * Add a new geometry to this scene
  28102. * @param geometry defines the geometry to be added to the scene.
  28103. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  28104. * @return a boolean defining if the geometry was added or not
  28105. */
  28106. Scene.prototype.pushGeometry = function (geometry, force) {
  28107. if (!force && this.getGeometryByID(geometry.id)) {
  28108. return false;
  28109. }
  28110. this.geometries.push(geometry);
  28111. //notify the collision coordinator
  28112. if (this.collisionCoordinator) {
  28113. this.collisionCoordinator.onGeometryAdded(geometry);
  28114. }
  28115. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  28116. return true;
  28117. };
  28118. /**
  28119. * Removes an existing geometry
  28120. * @param geometry defines the geometry to be removed from the scene
  28121. * @return a boolean defining if the geometry was removed or not
  28122. */
  28123. Scene.prototype.removeGeometry = function (geometry) {
  28124. var index = this.geometries.indexOf(geometry);
  28125. if (index > -1) {
  28126. this.geometries.splice(index, 1);
  28127. //notify the collision coordinator
  28128. if (this.collisionCoordinator) {
  28129. this.collisionCoordinator.onGeometryDeleted(geometry);
  28130. }
  28131. this.onGeometryRemovedObservable.notifyObservers(geometry);
  28132. return true;
  28133. }
  28134. return false;
  28135. };
  28136. /**
  28137. * Gets the list of geometries attached to the scene
  28138. * @returns an array of Geometry
  28139. */
  28140. Scene.prototype.getGeometries = function () {
  28141. return this.geometries;
  28142. };
  28143. /**
  28144. * Gets the first added mesh found of a given ID
  28145. * @param id defines the id to search for
  28146. * @return the mesh found or null if not found at all
  28147. */
  28148. Scene.prototype.getMeshByID = function (id) {
  28149. for (var index = 0; index < this.meshes.length; index++) {
  28150. if (this.meshes[index].id === id) {
  28151. return this.meshes[index];
  28152. }
  28153. }
  28154. return null;
  28155. };
  28156. /**
  28157. * Gets a list of meshes using their id
  28158. * @param id defines the id to search for
  28159. * @returns a list of meshes
  28160. */
  28161. Scene.prototype.getMeshesByID = function (id) {
  28162. return this.meshes.filter(function (m) {
  28163. return m.id === id;
  28164. });
  28165. };
  28166. /**
  28167. * Gets the first added transform node found of a given ID
  28168. * @param id defines the id to search for
  28169. * @return the found transform node or null if not found at all.
  28170. */
  28171. Scene.prototype.getTransformNodeByID = function (id) {
  28172. for (var index = 0; index < this.transformNodes.length; index++) {
  28173. if (this.transformNodes[index].id === id) {
  28174. return this.transformNodes[index];
  28175. }
  28176. }
  28177. return null;
  28178. };
  28179. /**
  28180. * Gets a list of transform nodes using their id
  28181. * @param id defines the id to search for
  28182. * @returns a list of transform nodes
  28183. */
  28184. Scene.prototype.getTransformNodesByID = function (id) {
  28185. return this.transformNodes.filter(function (m) {
  28186. return m.id === id;
  28187. });
  28188. };
  28189. /**
  28190. * Gets a mesh with its auto-generated unique id
  28191. * @param uniqueId defines the unique id to search for
  28192. * @return the found mesh or null if not found at all.
  28193. */
  28194. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  28195. for (var index = 0; index < this.meshes.length; index++) {
  28196. if (this.meshes[index].uniqueId === uniqueId) {
  28197. return this.meshes[index];
  28198. }
  28199. }
  28200. return null;
  28201. };
  28202. /**
  28203. * Gets a the last added mesh using a given id
  28204. * @param id defines the id to search for
  28205. * @return the found mesh or null if not found at all.
  28206. */
  28207. Scene.prototype.getLastMeshByID = function (id) {
  28208. for (var index = this.meshes.length - 1; index >= 0; index--) {
  28209. if (this.meshes[index].id === id) {
  28210. return this.meshes[index];
  28211. }
  28212. }
  28213. return null;
  28214. };
  28215. /**
  28216. * Gets a the last added node (Mesh, Camera, Light) using a given id
  28217. * @param id defines the id to search for
  28218. * @return the found node or null if not found at all
  28219. */
  28220. Scene.prototype.getLastEntryByID = function (id) {
  28221. var index;
  28222. for (index = this.meshes.length - 1; index >= 0; index--) {
  28223. if (this.meshes[index].id === id) {
  28224. return this.meshes[index];
  28225. }
  28226. }
  28227. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  28228. if (this.transformNodes[index].id === id) {
  28229. return this.transformNodes[index];
  28230. }
  28231. }
  28232. for (index = this.cameras.length - 1; index >= 0; index--) {
  28233. if (this.cameras[index].id === id) {
  28234. return this.cameras[index];
  28235. }
  28236. }
  28237. for (index = this.lights.length - 1; index >= 0; index--) {
  28238. if (this.lights[index].id === id) {
  28239. return this.lights[index];
  28240. }
  28241. }
  28242. return null;
  28243. };
  28244. /**
  28245. * Gets a node (Mesh, Camera, Light) using a given id
  28246. * @param id defines the id to search for
  28247. * @return the found node or null if not found at all
  28248. */
  28249. Scene.prototype.getNodeByID = function (id) {
  28250. var mesh = this.getMeshByID(id);
  28251. if (mesh) {
  28252. return mesh;
  28253. }
  28254. var light = this.getLightByID(id);
  28255. if (light) {
  28256. return light;
  28257. }
  28258. var camera = this.getCameraByID(id);
  28259. if (camera) {
  28260. return camera;
  28261. }
  28262. var bone = this.getBoneByID(id);
  28263. return bone;
  28264. };
  28265. /**
  28266. * Gets a node (Mesh, Camera, Light) using a given name
  28267. * @param name defines the name to search for
  28268. * @return the found node or null if not found at all.
  28269. */
  28270. Scene.prototype.getNodeByName = function (name) {
  28271. var mesh = this.getMeshByName(name);
  28272. if (mesh) {
  28273. return mesh;
  28274. }
  28275. var light = this.getLightByName(name);
  28276. if (light) {
  28277. return light;
  28278. }
  28279. var camera = this.getCameraByName(name);
  28280. if (camera) {
  28281. return camera;
  28282. }
  28283. var bone = this.getBoneByName(name);
  28284. return bone;
  28285. };
  28286. /**
  28287. * Gets a mesh using a given name
  28288. * @param name defines the name to search for
  28289. * @return the found mesh or null if not found at all.
  28290. */
  28291. Scene.prototype.getMeshByName = function (name) {
  28292. for (var index = 0; index < this.meshes.length; index++) {
  28293. if (this.meshes[index].name === name) {
  28294. return this.meshes[index];
  28295. }
  28296. }
  28297. return null;
  28298. };
  28299. /**
  28300. * Gets a transform node using a given name
  28301. * @param name defines the name to search for
  28302. * @return the found transform node or null if not found at all.
  28303. */
  28304. Scene.prototype.getTransformNodeByName = function (name) {
  28305. for (var index = 0; index < this.transformNodes.length; index++) {
  28306. if (this.transformNodes[index].name === name) {
  28307. return this.transformNodes[index];
  28308. }
  28309. }
  28310. return null;
  28311. };
  28312. /**
  28313. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  28314. * @param id defines the id to search for
  28315. * @return the found skeleton or null if not found at all.
  28316. */
  28317. Scene.prototype.getLastSkeletonByID = function (id) {
  28318. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  28319. if (this.skeletons[index].id === id) {
  28320. return this.skeletons[index];
  28321. }
  28322. }
  28323. return null;
  28324. };
  28325. /**
  28326. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  28327. * @param id defines the id to search for
  28328. * @return the found skeleton or null if not found at all.
  28329. */
  28330. Scene.prototype.getSkeletonById = function (id) {
  28331. for (var index = 0; index < this.skeletons.length; index++) {
  28332. if (this.skeletons[index].id === id) {
  28333. return this.skeletons[index];
  28334. }
  28335. }
  28336. return null;
  28337. };
  28338. /**
  28339. * Gets a skeleton using a given name
  28340. * @param name defines the name to search for
  28341. * @return the found skeleton or null if not found at all.
  28342. */
  28343. Scene.prototype.getSkeletonByName = function (name) {
  28344. for (var index = 0; index < this.skeletons.length; index++) {
  28345. if (this.skeletons[index].name === name) {
  28346. return this.skeletons[index];
  28347. }
  28348. }
  28349. return null;
  28350. };
  28351. /**
  28352. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  28353. * @param id defines the id to search for
  28354. * @return the found morph target manager or null if not found at all.
  28355. */
  28356. Scene.prototype.getMorphTargetManagerById = function (id) {
  28357. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  28358. if (this.morphTargetManagers[index].uniqueId === id) {
  28359. return this.morphTargetManagers[index];
  28360. }
  28361. }
  28362. return null;
  28363. };
  28364. /**
  28365. * Gets a boolean indicating if the given mesh is active
  28366. * @param mesh defines the mesh to look for
  28367. * @returns true if the mesh is in the active list
  28368. */
  28369. Scene.prototype.isActiveMesh = function (mesh) {
  28370. return (this._activeMeshes.indexOf(mesh) !== -1);
  28371. };
  28372. Object.defineProperty(Scene.prototype, "uid", {
  28373. /**
  28374. * Return a unique id as a string which can serve as an identifier for the scene
  28375. */
  28376. get: function () {
  28377. if (!this._uid) {
  28378. this._uid = BABYLON.Tools.RandomId();
  28379. }
  28380. return this._uid;
  28381. },
  28382. enumerable: true,
  28383. configurable: true
  28384. });
  28385. /**
  28386. * Add an externaly attached data from its key.
  28387. * This method call will fail and return false, if such key already exists.
  28388. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  28389. * @param key the unique key that identifies the data
  28390. * @param data the data object to associate to the key for this Engine instance
  28391. * @return true if no such key were already present and the data was added successfully, false otherwise
  28392. */
  28393. Scene.prototype.addExternalData = function (key, data) {
  28394. if (!this._externalData) {
  28395. this._externalData = new BABYLON.StringDictionary();
  28396. }
  28397. return this._externalData.add(key, data);
  28398. };
  28399. /**
  28400. * Get an externaly attached data from its key
  28401. * @param key the unique key that identifies the data
  28402. * @return the associated data, if present (can be null), or undefined if not present
  28403. */
  28404. Scene.prototype.getExternalData = function (key) {
  28405. if (!this._externalData) {
  28406. return null;
  28407. }
  28408. return this._externalData.get(key);
  28409. };
  28410. /**
  28411. * Get an externaly attached data from its key, create it using a factory if it's not already present
  28412. * @param key the unique key that identifies the data
  28413. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  28414. * @return the associated data, can be null if the factory returned null.
  28415. */
  28416. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  28417. if (!this._externalData) {
  28418. this._externalData = new BABYLON.StringDictionary();
  28419. }
  28420. return this._externalData.getOrAddWithFactory(key, factory);
  28421. };
  28422. /**
  28423. * Remove an externaly attached data from the Engine instance
  28424. * @param key the unique key that identifies the data
  28425. * @return true if the data was successfully removed, false if it doesn't exist
  28426. */
  28427. Scene.prototype.removeExternalData = function (key) {
  28428. return this._externalData.remove(key);
  28429. };
  28430. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  28431. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  28432. for (var _i = 0, _a = this._evaluateSubMeshStage; _i < _a.length; _i++) {
  28433. var step = _a[_i];
  28434. step.action(mesh, subMesh);
  28435. }
  28436. var material = subMesh.getMaterial();
  28437. if (material !== null && material !== undefined) {
  28438. // Render targets
  28439. if (material.hasRenderTargetTextures && material.getRenderTargetTextures !== undefined) {
  28440. if (this._processedMaterials.indexOf(material) === -1) {
  28441. this._processedMaterials.push(material);
  28442. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  28443. }
  28444. }
  28445. // Dispatch
  28446. this._activeIndices.addCount(subMesh.indexCount, false);
  28447. this._renderingManager.dispatch(subMesh, mesh, material);
  28448. }
  28449. }
  28450. };
  28451. /**
  28452. * Clear the processed materials smart array preventing retention point in material dispose.
  28453. */
  28454. Scene.prototype.freeProcessedMaterials = function () {
  28455. this._processedMaterials.dispose();
  28456. };
  28457. /**
  28458. * Clear the active meshes smart array preventing retention point in mesh dispose.
  28459. */
  28460. Scene.prototype.freeActiveMeshes = function () {
  28461. this._activeMeshes.dispose();
  28462. if (this.activeCamera && this.activeCamera._activeMeshes) {
  28463. this.activeCamera._activeMeshes.dispose();
  28464. }
  28465. if (this.activeCameras) {
  28466. for (var i = 0; i < this.activeCameras.length; i++) {
  28467. var activeCamera = this.activeCameras[i];
  28468. if (activeCamera && activeCamera._activeMeshes) {
  28469. activeCamera._activeMeshes.dispose();
  28470. }
  28471. }
  28472. }
  28473. };
  28474. /**
  28475. * Clear the info related to rendering groups preventing retention points during dispose.
  28476. */
  28477. Scene.prototype.freeRenderingGroups = function () {
  28478. if (this._renderingManager) {
  28479. this._renderingManager.freeRenderingGroups();
  28480. }
  28481. if (this.textures) {
  28482. for (var i = 0; i < this.textures.length; i++) {
  28483. var texture = this.textures[i];
  28484. if (texture && texture.renderList) {
  28485. texture.freeRenderingGroups();
  28486. }
  28487. }
  28488. }
  28489. };
  28490. /** @hidden */
  28491. Scene.prototype._isInIntermediateRendering = function () {
  28492. return this._intermediateRendering;
  28493. };
  28494. /**
  28495. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  28496. * @returns the current scene
  28497. */
  28498. Scene.prototype.freezeActiveMeshes = function () {
  28499. if (!this.activeCamera) {
  28500. return this;
  28501. }
  28502. if (!this._frustumPlanes) {
  28503. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  28504. }
  28505. this._evaluateActiveMeshes();
  28506. this._activeMeshesFrozen = true;
  28507. return this;
  28508. };
  28509. /**
  28510. * Use this function to restart evaluating active meshes on every frame
  28511. * @returns the current scene
  28512. */
  28513. Scene.prototype.unfreezeActiveMeshes = function () {
  28514. this._activeMeshesFrozen = false;
  28515. return this;
  28516. };
  28517. Scene.prototype._evaluateActiveMeshes = function () {
  28518. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  28519. return;
  28520. }
  28521. if (!this.activeCamera) {
  28522. return;
  28523. }
  28524. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  28525. this.activeCamera._activeMeshes.reset();
  28526. this._activeMeshes.reset();
  28527. this._renderingManager.reset();
  28528. this._processedMaterials.reset();
  28529. this._activeParticleSystems.reset();
  28530. this._activeSkeletons.reset();
  28531. this._softwareSkinnedMeshes.reset();
  28532. for (var _i = 0, _a = this._beforeEvaluateActiveMeshStage; _i < _a.length; _i++) {
  28533. var step = _a[_i];
  28534. step.action();
  28535. }
  28536. // Determine mesh candidates
  28537. var meshes = this.getActiveMeshCandidates();
  28538. // Check each mesh
  28539. var len = meshes.length;
  28540. for (var i = 0; i < len; i++) {
  28541. var mesh = meshes.data[i];
  28542. if (mesh.isBlocked) {
  28543. continue;
  28544. }
  28545. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  28546. if (!mesh.isReady() || !mesh.isEnabled()) {
  28547. continue;
  28548. }
  28549. mesh.computeWorldMatrix();
  28550. // Intersections
  28551. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers2(BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger)) {
  28552. this._meshesForIntersections.pushNoDuplicate(mesh);
  28553. }
  28554. // Switch to current LOD
  28555. var meshLOD = mesh.getLOD(this.activeCamera);
  28556. if (meshLOD === undefined || meshLOD === null) {
  28557. continue;
  28558. }
  28559. mesh._preActivate();
  28560. if (mesh.isVisible && mesh.visibility > 0 && (mesh.alwaysSelectAsActiveMesh || ((mesh.layerMask & this.activeCamera.layerMask) !== 0 && mesh.isInFrustum(this._frustumPlanes)))) {
  28561. this._activeMeshes.push(mesh);
  28562. this.activeCamera._activeMeshes.push(mesh);
  28563. mesh._activate(this._renderId);
  28564. if (meshLOD !== mesh) {
  28565. meshLOD._activate(this._renderId);
  28566. }
  28567. this._activeMesh(mesh, meshLOD);
  28568. }
  28569. }
  28570. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  28571. // Particle systems
  28572. if (this.particlesEnabled) {
  28573. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  28574. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  28575. var particleSystem = this.particleSystems[particleIndex];
  28576. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  28577. continue;
  28578. }
  28579. var emitter = particleSystem.emitter;
  28580. if (!emitter.position || emitter.isEnabled()) {
  28581. this._activeParticleSystems.push(particleSystem);
  28582. particleSystem.animate();
  28583. this._renderingManager.dispatchParticles(particleSystem);
  28584. }
  28585. }
  28586. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  28587. }
  28588. };
  28589. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  28590. if (this._skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  28591. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  28592. mesh.skeleton.prepare();
  28593. }
  28594. if (!mesh.computeBonesUsingShaders) {
  28595. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  28596. }
  28597. }
  28598. for (var _i = 0, _a = this._activeMeshStage; _i < _a.length; _i++) {
  28599. var step = _a[_i];
  28600. step.action(sourceMesh, mesh);
  28601. }
  28602. if (mesh !== undefined && mesh !== null
  28603. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  28604. var subMeshes = this.getActiveSubMeshCandidates(mesh);
  28605. var len = subMeshes.length;
  28606. for (var i = 0; i < len; i++) {
  28607. var subMesh = subMeshes.data[i];
  28608. this._evaluateSubMesh(subMesh, mesh);
  28609. }
  28610. }
  28611. };
  28612. /**
  28613. * Update the transform matrix to update from the current active camera
  28614. * @param force defines a boolean used to force the update even if cache is up to date
  28615. */
  28616. Scene.prototype.updateTransformMatrix = function (force) {
  28617. if (!this.activeCamera) {
  28618. return;
  28619. }
  28620. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  28621. };
  28622. /**
  28623. * 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)
  28624. * @param alternateCamera defines the camera to use
  28625. */
  28626. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  28627. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  28628. };
  28629. Scene.prototype._renderForCamera = function (camera, rigParent) {
  28630. if (camera && camera._skipRendering) {
  28631. return;
  28632. }
  28633. var engine = this._engine;
  28634. this.activeCamera = camera;
  28635. if (!this.activeCamera)
  28636. throw new Error("Active camera not set");
  28637. // Viewport
  28638. engine.setViewport(this.activeCamera.viewport);
  28639. // Camera
  28640. this.resetCachedMaterial();
  28641. this._renderId++;
  28642. this.updateTransformMatrix();
  28643. if (camera._alternateCamera) {
  28644. this.updateAlternateTransformMatrix(camera._alternateCamera);
  28645. this._alternateRendering = true;
  28646. }
  28647. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  28648. // Meshes
  28649. this._evaluateActiveMeshes();
  28650. // Software skinning
  28651. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  28652. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  28653. mesh.applySkeleton(mesh.skeleton);
  28654. }
  28655. // Render targets
  28656. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  28657. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  28658. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  28659. }
  28660. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  28661. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  28662. }
  28663. // Collects render targets from external components.
  28664. for (var _i = 0, _a = this._gatherActiveCameraRenderTargetsStage; _i < _a.length; _i++) {
  28665. var step = _a[_i];
  28666. step.action(this._renderTargets);
  28667. }
  28668. if (this.renderTargetsEnabled) {
  28669. this._intermediateRendering = true;
  28670. if (this._renderTargets.length > 0) {
  28671. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  28672. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  28673. var renderTarget = this._renderTargets.data[renderIndex];
  28674. if (renderTarget._shouldRender()) {
  28675. this._renderId++;
  28676. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  28677. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  28678. }
  28679. }
  28680. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  28681. this._renderId++;
  28682. }
  28683. for (var _b = 0, _c = this._cameraDrawRenderTargetStage; _b < _c.length; _b++) {
  28684. var step = _c[_b];
  28685. step.action(this.activeCamera);
  28686. }
  28687. this._intermediateRendering = false;
  28688. engine.restoreDefaultFramebuffer(); // Restore back buffer if needed
  28689. }
  28690. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  28691. // Prepare Frame
  28692. if (this.postProcessManager) {
  28693. this.postProcessManager._prepareFrame();
  28694. }
  28695. // Before Camera Draw
  28696. for (var _d = 0, _e = this._beforeCameraDrawStage; _d < _e.length; _d++) {
  28697. var step = _e[_d];
  28698. step.action(this.activeCamera);
  28699. }
  28700. // Render
  28701. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  28702. this._renderingManager.render(null, null, true, true);
  28703. this.onAfterDrawPhaseObservable.notifyObservers(this);
  28704. // After Camera Draw
  28705. for (var _f = 0, _g = this._afterCameraDrawStage; _f < _g.length; _f++) {
  28706. var step = _g[_f];
  28707. step.action(this.activeCamera);
  28708. }
  28709. // Finalize frame
  28710. if (this.postProcessManager) {
  28711. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  28712. }
  28713. // Reset some special arrays
  28714. this._renderTargets.reset();
  28715. this._alternateRendering = false;
  28716. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  28717. };
  28718. Scene.prototype._processSubCameras = function (camera) {
  28719. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  28720. this._renderForCamera(camera);
  28721. return;
  28722. }
  28723. // rig cameras
  28724. for (var index = 0; index < camera._rigCameras.length; index++) {
  28725. this._renderForCamera(camera._rigCameras[index], camera);
  28726. }
  28727. this.activeCamera = camera;
  28728. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  28729. };
  28730. Scene.prototype._checkIntersections = function () {
  28731. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  28732. var sourceMesh = this._meshesForIntersections.data[index];
  28733. if (!sourceMesh.actionManager) {
  28734. continue;
  28735. }
  28736. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  28737. var action = sourceMesh.actionManager.actions[actionIndex];
  28738. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  28739. var parameters = action.getTriggerParameter();
  28740. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  28741. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  28742. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  28743. if (areIntersecting && currentIntersectionInProgress === -1) {
  28744. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  28745. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  28746. sourceMesh._intersectionsInProgress.push(otherMesh);
  28747. }
  28748. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  28749. sourceMesh._intersectionsInProgress.push(otherMesh);
  28750. }
  28751. }
  28752. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  28753. //They intersected, and now they don't.
  28754. //is this trigger an exit trigger? execute an event.
  28755. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  28756. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  28757. }
  28758. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  28759. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  28760. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  28761. return otherMesh === parameterMesh;
  28762. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  28763. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  28764. }
  28765. }
  28766. }
  28767. }
  28768. }
  28769. };
  28770. /** @hidden */
  28771. Scene.prototype._advancePhysicsEngineStep = function (step) {
  28772. // Do nothing. Code will be replaced if physics engine component is referenced
  28773. };
  28774. /**
  28775. * Render the scene
  28776. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  28777. */
  28778. Scene.prototype.render = function (updateCameras) {
  28779. if (updateCameras === void 0) { updateCameras = true; }
  28780. if (this.isDisposed) {
  28781. return;
  28782. }
  28783. this._frameId++;
  28784. // Register components that have been associated lately to the scene.
  28785. this._registerTransientComponents();
  28786. this._activeParticles.fetchNewFrame();
  28787. this._totalVertices.fetchNewFrame();
  28788. this._activeIndices.fetchNewFrame();
  28789. this._activeBones.fetchNewFrame();
  28790. this._meshesForIntersections.reset();
  28791. this.resetCachedMaterial();
  28792. this.onBeforeAnimationsObservable.notifyObservers(this);
  28793. // Actions
  28794. if (this.actionManager) {
  28795. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  28796. }
  28797. if (this._engine.isDeterministicLockStep()) {
  28798. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  28799. var defaultFPS = (60.0 / 1000.0);
  28800. var defaultFrameTime = this.getDeterministicFrameTime();
  28801. var stepsTaken = 0;
  28802. var maxSubSteps = this._engine.getLockstepMaxSteps();
  28803. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  28804. internalSteps = Math.min(internalSteps, maxSubSteps);
  28805. do {
  28806. this.onBeforeStepObservable.notifyObservers(this);
  28807. // Animations
  28808. this._animationRatio = defaultFrameTime * defaultFPS;
  28809. this._animate();
  28810. this.onAfterAnimationsObservable.notifyObservers(this);
  28811. // Physics
  28812. this._advancePhysicsEngineStep(defaultFrameTime);
  28813. this.onAfterStepObservable.notifyObservers(this);
  28814. this._currentStepId++;
  28815. stepsTaken++;
  28816. deltaTime -= defaultFrameTime;
  28817. } while (deltaTime > 0 && stepsTaken < internalSteps);
  28818. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  28819. }
  28820. else {
  28821. // Animations
  28822. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  28823. this._animationRatio = deltaTime * (60.0 / 1000.0);
  28824. this._animate();
  28825. this.onAfterAnimationsObservable.notifyObservers(this);
  28826. // Physics
  28827. this._advancePhysicsEngineStep(deltaTime);
  28828. }
  28829. // Before camera update steps
  28830. for (var _i = 0, _a = this._beforeCameraUpdateStage; _i < _a.length; _i++) {
  28831. var step = _a[_i];
  28832. step.action();
  28833. }
  28834. // Update Cameras
  28835. if (updateCameras) {
  28836. if (this.activeCameras.length > 0) {
  28837. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  28838. var camera = this.activeCameras[cameraIndex];
  28839. camera.update();
  28840. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  28841. // rig cameras
  28842. for (var index = 0; index < camera._rigCameras.length; index++) {
  28843. camera._rigCameras[index].update();
  28844. }
  28845. }
  28846. }
  28847. }
  28848. else if (this.activeCamera) {
  28849. this.activeCamera.update();
  28850. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  28851. // rig cameras
  28852. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  28853. this.activeCamera._rigCameras[index].update();
  28854. }
  28855. }
  28856. }
  28857. }
  28858. // Before render
  28859. this.onBeforeRenderObservable.notifyObservers(this);
  28860. // Customs render targets
  28861. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  28862. var engine = this.getEngine();
  28863. var currentActiveCamera = this.activeCamera;
  28864. if (this.renderTargetsEnabled) {
  28865. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  28866. this._intermediateRendering = true;
  28867. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  28868. var renderTarget = this.customRenderTargets[customIndex];
  28869. if (renderTarget._shouldRender()) {
  28870. this._renderId++;
  28871. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  28872. if (!this.activeCamera)
  28873. throw new Error("Active camera not set");
  28874. // Viewport
  28875. engine.setViewport(this.activeCamera.viewport);
  28876. // Camera
  28877. this.updateTransformMatrix();
  28878. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  28879. }
  28880. }
  28881. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  28882. this._intermediateRendering = false;
  28883. this._renderId++;
  28884. }
  28885. // Restore back buffer
  28886. if (this.customRenderTargets.length > 0) {
  28887. engine.restoreDefaultFramebuffer();
  28888. }
  28889. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  28890. this.activeCamera = currentActiveCamera;
  28891. for (var _b = 0, _c = this._beforeClearStage; _b < _c.length; _b++) {
  28892. var step = _c[_b];
  28893. step.action();
  28894. }
  28895. // Clear
  28896. if (this.autoClearDepthAndStencil || this.autoClear) {
  28897. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  28898. }
  28899. // Collects render targets from external components.
  28900. for (var _d = 0, _e = this._gatherRenderTargetsStage; _d < _e.length; _d++) {
  28901. var step = _e[_d];
  28902. step.action(this._renderTargets);
  28903. }
  28904. // Multi-cameras?
  28905. if (this.activeCameras.length > 0) {
  28906. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  28907. if (cameraIndex > 0) {
  28908. this._engine.clear(null, false, true, true);
  28909. }
  28910. this._processSubCameras(this.activeCameras[cameraIndex]);
  28911. }
  28912. }
  28913. else {
  28914. if (!this.activeCamera) {
  28915. throw new Error("No camera defined");
  28916. }
  28917. this._processSubCameras(this.activeCamera);
  28918. }
  28919. // Intersection checks
  28920. this._checkIntersections();
  28921. // Executes the after render stage actions.
  28922. for (var _f = 0, _g = this._afterRenderStage; _f < _g.length; _f++) {
  28923. var step = _g[_f];
  28924. step.action();
  28925. }
  28926. // After render
  28927. if (this.afterRender) {
  28928. this.afterRender();
  28929. }
  28930. this.onAfterRenderObservable.notifyObservers(this);
  28931. // Cleaning
  28932. if (this._toBeDisposed.length) {
  28933. for (var index = 0; index < this._toBeDisposed.length; index++) {
  28934. var data = this._toBeDisposed[index];
  28935. if (data) {
  28936. data.dispose();
  28937. }
  28938. }
  28939. this._toBeDisposed = [];
  28940. }
  28941. if (this.dumpNextRenderTargets) {
  28942. this.dumpNextRenderTargets = false;
  28943. }
  28944. this._activeBones.addCount(0, true);
  28945. this._activeIndices.addCount(0, true);
  28946. this._activeParticles.addCount(0, true);
  28947. };
  28948. /**
  28949. * Freeze all materials
  28950. * A frozen material will not be updatable but should be faster to render
  28951. */
  28952. Scene.prototype.freezeMaterials = function () {
  28953. for (var i = 0; i < this.materials.length; i++) {
  28954. this.materials[i].freeze();
  28955. }
  28956. };
  28957. /**
  28958. * Unfreeze all materials
  28959. * A frozen material will not be updatable but should be faster to render
  28960. */
  28961. Scene.prototype.unfreezeMaterials = function () {
  28962. for (var i = 0; i < this.materials.length; i++) {
  28963. this.materials[i].unfreeze();
  28964. }
  28965. };
  28966. /**
  28967. * Releases all held ressources
  28968. */
  28969. Scene.prototype.dispose = function () {
  28970. this.beforeRender = null;
  28971. this.afterRender = null;
  28972. this.skeletons = [];
  28973. this.morphTargetManagers = [];
  28974. this._transientComponents = [];
  28975. this._isReadyForMeshStage.clear();
  28976. this._beforeEvaluateActiveMeshStage.clear();
  28977. this._evaluateSubMeshStage.clear();
  28978. this._activeMeshStage.clear();
  28979. this._cameraDrawRenderTargetStage.clear();
  28980. this._beforeCameraDrawStage.clear();
  28981. this._beforeRenderingGroupDrawStage.clear();
  28982. this._beforeRenderingMeshStage.clear();
  28983. this._afterRenderingMeshStage.clear();
  28984. this._afterRenderingGroupDrawStage.clear();
  28985. this._afterCameraDrawStage.clear();
  28986. this._afterRenderStage.clear();
  28987. this._beforeCameraUpdateStage.clear();
  28988. this._beforeClearStage.clear();
  28989. this._gatherRenderTargetsStage.clear();
  28990. this._gatherActiveCameraRenderTargetsStage.clear();
  28991. this._pointerMoveStage.clear();
  28992. this._pointerDownStage.clear();
  28993. this._pointerUpStage.clear();
  28994. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  28995. var component = _a[_i];
  28996. component.dispose();
  28997. }
  28998. this.importedMeshesFiles = new Array();
  28999. this.stopAllAnimations();
  29000. this.resetCachedMaterial();
  29001. // Smart arrays
  29002. if (this.activeCamera) {
  29003. this.activeCamera._activeMeshes.dispose();
  29004. this.activeCamera = null;
  29005. }
  29006. this._activeMeshes.dispose();
  29007. this._renderingManager.dispose();
  29008. this._processedMaterials.dispose();
  29009. this._activeParticleSystems.dispose();
  29010. this._activeSkeletons.dispose();
  29011. this._softwareSkinnedMeshes.dispose();
  29012. this._renderTargets.dispose();
  29013. this._registeredForLateAnimationBindings.dispose();
  29014. this._meshesForIntersections.dispose();
  29015. this._toBeDisposed = [];
  29016. // Abort active requests
  29017. for (var _b = 0, _c = this._activeRequests; _b < _c.length; _b++) {
  29018. var request = _c[_b];
  29019. request.abort();
  29020. }
  29021. // Events
  29022. this.onDisposeObservable.notifyObservers(this);
  29023. this.onDisposeObservable.clear();
  29024. this.onBeforeRenderObservable.clear();
  29025. this.onAfterRenderObservable.clear();
  29026. this.onBeforeRenderTargetsRenderObservable.clear();
  29027. this.onAfterRenderTargetsRenderObservable.clear();
  29028. this.onAfterStepObservable.clear();
  29029. this.onBeforeStepObservable.clear();
  29030. this.onBeforeActiveMeshesEvaluationObservable.clear();
  29031. this.onAfterActiveMeshesEvaluationObservable.clear();
  29032. this.onBeforeParticlesRenderingObservable.clear();
  29033. this.onAfterParticlesRenderingObservable.clear();
  29034. this.onBeforeDrawPhaseObservable.clear();
  29035. this.onAfterDrawPhaseObservable.clear();
  29036. this.onBeforeAnimationsObservable.clear();
  29037. this.onAfterAnimationsObservable.clear();
  29038. this.onDataLoadedObservable.clear();
  29039. this.onBeforeRenderingGroupObservable.clear();
  29040. this.onAfterRenderingGroupObservable.clear();
  29041. this.onMeshImportedObservable.clear();
  29042. this.onBeforeCameraRenderObservable.clear();
  29043. this.onAfterCameraRenderObservable.clear();
  29044. this.onReadyObservable.clear();
  29045. this.onNewCameraAddedObservable.clear();
  29046. this.onCameraRemovedObservable.clear();
  29047. this.onNewLightAddedObservable.clear();
  29048. this.onLightRemovedObservable.clear();
  29049. this.onNewGeometryAddedObservable.clear();
  29050. this.onGeometryRemovedObservable.clear();
  29051. this.onNewTransformNodeAddedObservable.clear();
  29052. this.onTransformNodeRemovedObservable.clear();
  29053. this.onNewMeshAddedObservable.clear();
  29054. this.onMeshRemovedObservable.clear();
  29055. this.onNewMaterialAddedObservable.clear();
  29056. this.onMaterialRemovedObservable.clear();
  29057. this.onNewTextureAddedObservable.clear();
  29058. this.onTextureRemovedObservable.clear();
  29059. this.onPrePointerObservable.clear();
  29060. this.onPointerObservable.clear();
  29061. this.onPreKeyboardObservable.clear();
  29062. this.onKeyboardObservable.clear();
  29063. this.detachControl();
  29064. // Detach cameras
  29065. var canvas = this._engine.getRenderingCanvas();
  29066. if (canvas) {
  29067. var index;
  29068. for (index = 0; index < this.cameras.length; index++) {
  29069. this.cameras[index].detachControl(canvas);
  29070. }
  29071. }
  29072. // Release animation groups
  29073. while (this.animationGroups.length) {
  29074. this.animationGroups[0].dispose();
  29075. }
  29076. // Release lights
  29077. while (this.lights.length) {
  29078. this.lights[0].dispose();
  29079. }
  29080. // Release meshes
  29081. while (this.meshes.length) {
  29082. this.meshes[0].dispose(true);
  29083. }
  29084. while (this.transformNodes.length) {
  29085. this.removeTransformNode(this.transformNodes[0]);
  29086. }
  29087. // Release cameras
  29088. while (this.cameras.length) {
  29089. this.cameras[0].dispose();
  29090. }
  29091. // Release materials
  29092. if (this.defaultMaterial) {
  29093. this.defaultMaterial.dispose();
  29094. }
  29095. while (this.multiMaterials.length) {
  29096. this.multiMaterials[0].dispose();
  29097. }
  29098. while (this.materials.length) {
  29099. this.materials[0].dispose();
  29100. }
  29101. // Release particles
  29102. while (this.particleSystems.length) {
  29103. this.particleSystems[0].dispose();
  29104. }
  29105. // Release postProcesses
  29106. while (this.postProcesses.length) {
  29107. this.postProcesses[0].dispose();
  29108. }
  29109. // Release textures
  29110. while (this.textures.length) {
  29111. this.textures[0].dispose();
  29112. }
  29113. // Release UBO
  29114. this._sceneUbo.dispose();
  29115. if (this._alternateSceneUbo) {
  29116. this._alternateSceneUbo.dispose();
  29117. }
  29118. // Post-processes
  29119. this.postProcessManager.dispose();
  29120. // Remove from engine
  29121. index = this._engine.scenes.indexOf(this);
  29122. if (index > -1) {
  29123. this._engine.scenes.splice(index, 1);
  29124. }
  29125. this._engine.wipeCaches(true);
  29126. this._isDisposed = true;
  29127. };
  29128. Object.defineProperty(Scene.prototype, "isDisposed", {
  29129. /**
  29130. * Gets if the scene is already disposed
  29131. */
  29132. get: function () {
  29133. return this._isDisposed;
  29134. },
  29135. enumerable: true,
  29136. configurable: true
  29137. });
  29138. /**
  29139. * Call this function to reduce memory footprint of the scene.
  29140. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  29141. */
  29142. Scene.prototype.clearCachedVertexData = function () {
  29143. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  29144. var mesh = this.meshes[meshIndex];
  29145. var geometry = mesh.geometry;
  29146. if (geometry) {
  29147. geometry._indices = [];
  29148. for (var vbName in geometry._vertexBuffers) {
  29149. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  29150. continue;
  29151. }
  29152. geometry._vertexBuffers[vbName]._buffer._data = null;
  29153. }
  29154. }
  29155. }
  29156. };
  29157. /**
  29158. * This function will remove the local cached buffer data from texture.
  29159. * It will save memory but will prevent the texture from being rebuilt
  29160. */
  29161. Scene.prototype.cleanCachedTextureBuffer = function () {
  29162. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  29163. var baseTexture = _a[_i];
  29164. var buffer = baseTexture._buffer;
  29165. if (buffer) {
  29166. baseTexture._buffer = null;
  29167. }
  29168. }
  29169. };
  29170. /**
  29171. * Get the world extend vectors with an optional filter
  29172. *
  29173. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  29174. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  29175. */
  29176. Scene.prototype.getWorldExtends = function (filterPredicate) {
  29177. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  29178. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  29179. filterPredicate = filterPredicate || (function () { return true; });
  29180. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  29181. mesh.computeWorldMatrix(true);
  29182. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  29183. return;
  29184. }
  29185. var boundingInfo = mesh.getBoundingInfo();
  29186. var minBox = boundingInfo.boundingBox.minimumWorld;
  29187. var maxBox = boundingInfo.boundingBox.maximumWorld;
  29188. BABYLON.Tools.CheckExtends(minBox, min, max);
  29189. BABYLON.Tools.CheckExtends(maxBox, min, max);
  29190. });
  29191. return {
  29192. min: min,
  29193. max: max
  29194. };
  29195. };
  29196. // Picking
  29197. /**
  29198. * Creates a ray that can be used to pick in the scene
  29199. * @param x defines the x coordinate of the origin (on-screen)
  29200. * @param y defines the y coordinate of the origin (on-screen)
  29201. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  29202. * @param camera defines the camera to use for the picking
  29203. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  29204. * @returns a Ray
  29205. */
  29206. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  29207. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  29208. var result = BABYLON.Ray.Zero();
  29209. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  29210. return result;
  29211. };
  29212. /**
  29213. * Creates a ray that can be used to pick in the scene
  29214. * @param x defines the x coordinate of the origin (on-screen)
  29215. * @param y defines the y coordinate of the origin (on-screen)
  29216. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  29217. * @param result defines the ray where to store the picking ray
  29218. * @param camera defines the camera to use for the picking
  29219. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  29220. * @returns the current scene
  29221. */
  29222. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  29223. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  29224. var engine = this._engine;
  29225. if (!camera) {
  29226. if (!this.activeCamera)
  29227. throw new Error("Active camera not set");
  29228. camera = this.activeCamera;
  29229. }
  29230. var cameraViewport = camera.viewport;
  29231. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  29232. // Moving coordinates to local viewport world
  29233. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  29234. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  29235. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  29236. return this;
  29237. };
  29238. /**
  29239. * Creates a ray that can be used to pick in the scene
  29240. * @param x defines the x coordinate of the origin (on-screen)
  29241. * @param y defines the y coordinate of the origin (on-screen)
  29242. * @param camera defines the camera to use for the picking
  29243. * @returns a Ray
  29244. */
  29245. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  29246. var result = BABYLON.Ray.Zero();
  29247. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  29248. return result;
  29249. };
  29250. /**
  29251. * Creates a ray that can be used to pick in the scene
  29252. * @param x defines the x coordinate of the origin (on-screen)
  29253. * @param y defines the y coordinate of the origin (on-screen)
  29254. * @param result defines the ray where to store the picking ray
  29255. * @param camera defines the camera to use for the picking
  29256. * @returns the current scene
  29257. */
  29258. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  29259. if (!BABYLON.PickingInfo) {
  29260. return this;
  29261. }
  29262. var engine = this._engine;
  29263. if (!camera) {
  29264. if (!this.activeCamera)
  29265. throw new Error("Active camera not set");
  29266. camera = this.activeCamera;
  29267. }
  29268. var cameraViewport = camera.viewport;
  29269. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  29270. var identity = BABYLON.Matrix.Identity();
  29271. // Moving coordinates to local viewport world
  29272. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  29273. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  29274. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  29275. return this;
  29276. };
  29277. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  29278. if (!BABYLON.PickingInfo) {
  29279. return null;
  29280. }
  29281. var pickingInfo = null;
  29282. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  29283. var mesh = this.meshes[meshIndex];
  29284. if (predicate) {
  29285. if (!predicate(mesh)) {
  29286. continue;
  29287. }
  29288. }
  29289. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  29290. continue;
  29291. }
  29292. var world = mesh.getWorldMatrix();
  29293. var ray = rayFunction(world);
  29294. var result = mesh.intersects(ray, fastCheck);
  29295. if (!result || !result.hit)
  29296. continue;
  29297. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  29298. continue;
  29299. pickingInfo = result;
  29300. if (fastCheck) {
  29301. break;
  29302. }
  29303. }
  29304. return pickingInfo || new BABYLON.PickingInfo();
  29305. };
  29306. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  29307. if (!BABYLON.PickingInfo) {
  29308. return null;
  29309. }
  29310. var pickingInfos = new Array();
  29311. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  29312. var mesh = this.meshes[meshIndex];
  29313. if (predicate) {
  29314. if (!predicate(mesh)) {
  29315. continue;
  29316. }
  29317. }
  29318. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  29319. continue;
  29320. }
  29321. var world = mesh.getWorldMatrix();
  29322. var ray = rayFunction(world);
  29323. var result = mesh.intersects(ray, false);
  29324. if (!result || !result.hit)
  29325. continue;
  29326. pickingInfos.push(result);
  29327. }
  29328. return pickingInfos;
  29329. };
  29330. /** Launch a ray to try to pick a mesh in the scene
  29331. * @param x position on screen
  29332. * @param y position on screen
  29333. * @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
  29334. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  29335. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  29336. * @returns a PickingInfo
  29337. */
  29338. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  29339. var _this = this;
  29340. if (!BABYLON.PickingInfo) {
  29341. return null;
  29342. }
  29343. var result = this._internalPick(function (world) {
  29344. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  29345. return _this._tempPickingRay;
  29346. }, predicate, fastCheck);
  29347. if (result) {
  29348. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  29349. }
  29350. return result;
  29351. };
  29352. /** Use the given ray to pick a mesh in the scene
  29353. * @param ray The ray to use to pick meshes
  29354. * @param predicate Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must have isPickable set to true
  29355. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  29356. * @returns a PickingInfo
  29357. */
  29358. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  29359. var _this = this;
  29360. var result = this._internalPick(function (world) {
  29361. if (!_this._pickWithRayInverseMatrix) {
  29362. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  29363. }
  29364. world.invertToRef(_this._pickWithRayInverseMatrix);
  29365. if (!_this._cachedRayForTransform) {
  29366. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  29367. }
  29368. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  29369. return _this._cachedRayForTransform;
  29370. }, predicate, fastCheck);
  29371. if (result) {
  29372. result.ray = ray;
  29373. }
  29374. return result;
  29375. };
  29376. /**
  29377. * Launch a ray to try to pick a mesh in the scene
  29378. * @param x X position on screen
  29379. * @param y Y position on screen
  29380. * @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
  29381. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  29382. * @returns an array of PickingInfo
  29383. */
  29384. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  29385. var _this = this;
  29386. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  29387. };
  29388. /**
  29389. * Launch a ray to try to pick a mesh in the scene
  29390. * @param ray Ray to use
  29391. * @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
  29392. * @returns an array of PickingInfo
  29393. */
  29394. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  29395. var _this = this;
  29396. return this._internalMultiPick(function (world) {
  29397. if (!_this._pickWithRayInverseMatrix) {
  29398. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  29399. }
  29400. world.invertToRef(_this._pickWithRayInverseMatrix);
  29401. if (!_this._cachedRayForTransform) {
  29402. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  29403. }
  29404. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  29405. return _this._cachedRayForTransform;
  29406. }, predicate);
  29407. };
  29408. /**
  29409. * Force the value of meshUnderPointer
  29410. * @param mesh defines the mesh to use
  29411. */
  29412. Scene.prototype.setPointerOverMesh = function (mesh) {
  29413. if (this._pointerOverMesh === mesh) {
  29414. return;
  29415. }
  29416. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  29417. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  29418. }
  29419. this._pointerOverMesh = mesh;
  29420. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  29421. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  29422. }
  29423. };
  29424. /**
  29425. * Gets the mesh under the pointer
  29426. * @returns a Mesh or null if no mesh is under the pointer
  29427. */
  29428. Scene.prototype.getPointerOverMesh = function () {
  29429. return this._pointerOverMesh;
  29430. };
  29431. // Misc.
  29432. /** @hidden */
  29433. Scene.prototype._rebuildGeometries = function () {
  29434. for (var _i = 0, _a = this.geometries; _i < _a.length; _i++) {
  29435. var geometry = _a[_i];
  29436. geometry._rebuild();
  29437. }
  29438. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  29439. var mesh = _c[_b];
  29440. mesh._rebuild();
  29441. }
  29442. if (this.postProcessManager) {
  29443. this.postProcessManager._rebuild();
  29444. }
  29445. for (var _d = 0, _e = this._components; _d < _e.length; _d++) {
  29446. var component = _e[_d];
  29447. component.rebuild();
  29448. }
  29449. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  29450. var system = _g[_f];
  29451. system.rebuild();
  29452. }
  29453. };
  29454. /** @hidden */
  29455. Scene.prototype._rebuildTextures = function () {
  29456. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  29457. var texture = _a[_i];
  29458. texture._rebuild();
  29459. }
  29460. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29461. };
  29462. // Tags
  29463. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  29464. if (tagsQuery === undefined) {
  29465. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  29466. return list;
  29467. }
  29468. var listByTags = [];
  29469. forEach = forEach || (function (item) { return; });
  29470. for (var i in list) {
  29471. var item = list[i];
  29472. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  29473. listByTags.push(item);
  29474. forEach(item);
  29475. }
  29476. }
  29477. return listByTags;
  29478. };
  29479. /**
  29480. * Get a list of meshes by tags
  29481. * @param tagsQuery defines the tags query to use
  29482. * @param forEach defines a predicate used to filter results
  29483. * @returns an array of Mesh
  29484. */
  29485. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  29486. return this._getByTags(this.meshes, tagsQuery, forEach);
  29487. };
  29488. /**
  29489. * Get a list of cameras by tags
  29490. * @param tagsQuery defines the tags query to use
  29491. * @param forEach defines a predicate used to filter results
  29492. * @returns an array of Camera
  29493. */
  29494. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  29495. return this._getByTags(this.cameras, tagsQuery, forEach);
  29496. };
  29497. /**
  29498. * Get a list of lights by tags
  29499. * @param tagsQuery defines the tags query to use
  29500. * @param forEach defines a predicate used to filter results
  29501. * @returns an array of Light
  29502. */
  29503. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  29504. return this._getByTags(this.lights, tagsQuery, forEach);
  29505. };
  29506. /**
  29507. * Get a list of materials by tags
  29508. * @param tagsQuery defines the tags query to use
  29509. * @param forEach defines a predicate used to filter results
  29510. * @returns an array of Material
  29511. */
  29512. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  29513. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  29514. };
  29515. /**
  29516. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  29517. * This allowed control for front to back rendering or reversly depending of the special needs.
  29518. *
  29519. * @param renderingGroupId The rendering group id corresponding to its index
  29520. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  29521. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  29522. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  29523. */
  29524. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  29525. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  29526. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  29527. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  29528. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  29529. };
  29530. /**
  29531. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  29532. *
  29533. * @param renderingGroupId The rendering group id corresponding to its index
  29534. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  29535. * @param depth Automatically clears depth between groups if true and autoClear is true.
  29536. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  29537. */
  29538. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  29539. if (depth === void 0) { depth = true; }
  29540. if (stencil === void 0) { stencil = true; }
  29541. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  29542. };
  29543. /**
  29544. * Gets the current auto clear configuration for one rendering group of the rendering
  29545. * manager.
  29546. * @param index the rendering group index to get the information for
  29547. * @returns The auto clear setup for the requested rendering group
  29548. */
  29549. Scene.prototype.getAutoClearDepthStencilSetup = function (index) {
  29550. return this._renderingManager.getAutoClearDepthStencilSetup(index);
  29551. };
  29552. Object.defineProperty(Scene.prototype, "blockMaterialDirtyMechanism", {
  29553. /** Gets or sets a boolean blocking all the calls to markAllMaterialsAsDirty (ie. the materials won't be updated if they are out of sync) */
  29554. get: function () {
  29555. return this._blockMaterialDirtyMechanism;
  29556. },
  29557. set: function (value) {
  29558. if (this._blockMaterialDirtyMechanism === value) {
  29559. return;
  29560. }
  29561. this._blockMaterialDirtyMechanism = value;
  29562. if (!value) { // Do a complete update
  29563. this.markAllMaterialsAsDirty(BABYLON.Material.AllDirtyFlag);
  29564. }
  29565. },
  29566. enumerable: true,
  29567. configurable: true
  29568. });
  29569. /**
  29570. * Will flag all materials as dirty to trigger new shader compilation
  29571. * @param flag defines the flag used to specify which material part must be marked as dirty
  29572. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  29573. */
  29574. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  29575. if (this._blockMaterialDirtyMechanism) {
  29576. return;
  29577. }
  29578. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  29579. var material = _a[_i];
  29580. if (predicate && !predicate(material)) {
  29581. continue;
  29582. }
  29583. material.markAsDirty(flag);
  29584. }
  29585. };
  29586. /** @hidden */
  29587. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  29588. var _this = this;
  29589. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  29590. this._activeRequests.push(request);
  29591. request.onCompleteObservable.add(function (request) {
  29592. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  29593. });
  29594. return request;
  29595. };
  29596. /** @hidden */
  29597. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  29598. var _this = this;
  29599. return new Promise(function (resolve, reject) {
  29600. _this._loadFile(url, function (data) {
  29601. resolve(data);
  29602. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  29603. reject(exception);
  29604. });
  29605. });
  29606. };
  29607. // Statics
  29608. Scene._uniqueIdCounter = 0;
  29609. /** The fog is deactivated */
  29610. Scene.FOGMODE_NONE = 0;
  29611. /** The fog density is following an exponential function */
  29612. Scene.FOGMODE_EXP = 1;
  29613. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  29614. Scene.FOGMODE_EXP2 = 2;
  29615. /** The fog density is following a linear function. */
  29616. Scene.FOGMODE_LINEAR = 3;
  29617. /**
  29618. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  29619. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29620. */
  29621. Scene.MinDeltaTime = 1.0;
  29622. /**
  29623. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  29624. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29625. */
  29626. Scene.MaxDeltaTime = 1000.0;
  29627. /** The distance in pixel that you have to move to prevent some events */
  29628. Scene.DragMovementThreshold = 10; // in pixels
  29629. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  29630. Scene.LongPressDelay = 500; // in milliseconds
  29631. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  29632. Scene.DoubleClickDelay = 300; // in milliseconds
  29633. /** If you need to check double click without raising a single click at first click, enable this flag */
  29634. Scene.ExclusiveDoubleClickMode = false;
  29635. return Scene;
  29636. }(BABYLON.AbstractScene));
  29637. BABYLON.Scene = Scene;
  29638. })(BABYLON || (BABYLON = {}));
  29639. //# sourceMappingURL=babylon.scene.js.map
  29640. var BABYLON;
  29641. (function (BABYLON) {
  29642. /**
  29643. * Set of assets to keep when moving a scene into an asset container.
  29644. */
  29645. var KeepAssets = /** @class */ (function (_super) {
  29646. __extends(KeepAssets, _super);
  29647. function KeepAssets() {
  29648. return _super !== null && _super.apply(this, arguments) || this;
  29649. }
  29650. return KeepAssets;
  29651. }(BABYLON.AbstractScene));
  29652. BABYLON.KeepAssets = KeepAssets;
  29653. /**
  29654. * Container with a set of assets that can be added or removed from a scene.
  29655. */
  29656. var AssetContainer = /** @class */ (function (_super) {
  29657. __extends(AssetContainer, _super);
  29658. /**
  29659. * Instantiates an AssetContainer.
  29660. * @param scene The scene the AssetContainer belongs to.
  29661. */
  29662. function AssetContainer(scene) {
  29663. var _this = _super.call(this) || this;
  29664. _this.scene = scene;
  29665. return _this;
  29666. }
  29667. /**
  29668. * Adds all the assets from the container to the scene.
  29669. */
  29670. AssetContainer.prototype.addAllToScene = function () {
  29671. var _this = this;
  29672. this.cameras.forEach(function (o) {
  29673. _this.scene.addCamera(o);
  29674. });
  29675. this.lights.forEach(function (o) {
  29676. _this.scene.addLight(o);
  29677. });
  29678. this.meshes.forEach(function (o) {
  29679. _this.scene.addMesh(o);
  29680. });
  29681. this.skeletons.forEach(function (o) {
  29682. _this.scene.addSkeleton(o);
  29683. });
  29684. this.animations.forEach(function (o) {
  29685. _this.scene.addAnimation(o);
  29686. });
  29687. this.animationGroups.forEach(function (o) {
  29688. _this.scene.addAnimationGroup(o);
  29689. });
  29690. this.multiMaterials.forEach(function (o) {
  29691. _this.scene.addMultiMaterial(o);
  29692. });
  29693. this.materials.forEach(function (o) {
  29694. _this.scene.addMaterial(o);
  29695. });
  29696. this.morphTargetManagers.forEach(function (o) {
  29697. _this.scene.addMorphTargetManager(o);
  29698. });
  29699. this.geometries.forEach(function (o) {
  29700. _this.scene.addGeometry(o);
  29701. });
  29702. this.transformNodes.forEach(function (o) {
  29703. _this.scene.addTransformNode(o);
  29704. });
  29705. this.actionManagers.forEach(function (o) {
  29706. _this.scene.addActionManager(o);
  29707. });
  29708. this.textures.forEach(function (o) {
  29709. _this.scene.addTexture(o);
  29710. });
  29711. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  29712. var component = _a[_i];
  29713. component.addFromContainer(this.scene);
  29714. }
  29715. };
  29716. /**
  29717. * Removes all the assets in the container from the scene
  29718. */
  29719. AssetContainer.prototype.removeAllFromScene = function () {
  29720. var _this = this;
  29721. this.cameras.forEach(function (o) {
  29722. _this.scene.removeCamera(o);
  29723. });
  29724. this.lights.forEach(function (o) {
  29725. _this.scene.removeLight(o);
  29726. });
  29727. this.meshes.forEach(function (o) {
  29728. _this.scene.removeMesh(o);
  29729. });
  29730. this.skeletons.forEach(function (o) {
  29731. _this.scene.removeSkeleton(o);
  29732. });
  29733. this.animations.forEach(function (o) {
  29734. _this.scene.removeAnimation(o);
  29735. });
  29736. this.animationGroups.forEach(function (o) {
  29737. _this.scene.removeAnimationGroup(o);
  29738. });
  29739. this.multiMaterials.forEach(function (o) {
  29740. _this.scene.removeMultiMaterial(o);
  29741. });
  29742. this.materials.forEach(function (o) {
  29743. _this.scene.removeMaterial(o);
  29744. });
  29745. this.morphTargetManagers.forEach(function (o) {
  29746. _this.scene.removeMorphTargetManager(o);
  29747. });
  29748. this.geometries.forEach(function (o) {
  29749. _this.scene.removeGeometry(o);
  29750. });
  29751. this.transformNodes.forEach(function (o) {
  29752. _this.scene.removeTransformNode(o);
  29753. });
  29754. this.actionManagers.forEach(function (o) {
  29755. _this.scene.removeActionManager(o);
  29756. });
  29757. this.textures.forEach(function (o) {
  29758. _this.scene.removeTexture(o);
  29759. });
  29760. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  29761. var component = _a[_i];
  29762. component.removeFromContainer(this.scene);
  29763. }
  29764. };
  29765. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  29766. if (!sourceAssets) {
  29767. return;
  29768. }
  29769. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  29770. var asset = sourceAssets_1[_i];
  29771. var move = true;
  29772. if (keepAssets) {
  29773. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  29774. var keepAsset = keepAssets_1[_a];
  29775. if (asset === keepAsset) {
  29776. move = false;
  29777. break;
  29778. }
  29779. }
  29780. }
  29781. if (move) {
  29782. targetAssets.push(asset);
  29783. }
  29784. }
  29785. };
  29786. /**
  29787. * Removes all the assets contained in the scene and adds them to the container.
  29788. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  29789. */
  29790. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29791. if (keepAssets === undefined) {
  29792. keepAssets = new KeepAssets();
  29793. }
  29794. for (var key in this) {
  29795. if (this.hasOwnProperty(key)) {
  29796. this[key] = this[key] || [];
  29797. this._moveAssets(this.scene[key], this[key], keepAssets[key]);
  29798. }
  29799. }
  29800. this.removeAllFromScene();
  29801. };
  29802. /**
  29803. * 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.
  29804. * @returns the root mesh
  29805. */
  29806. AssetContainer.prototype.createRootMesh = function () {
  29807. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  29808. this.meshes.forEach(function (m) {
  29809. if (!m.parent) {
  29810. rootMesh.addChild(m);
  29811. }
  29812. });
  29813. this.meshes.unshift(rootMesh);
  29814. return rootMesh;
  29815. };
  29816. return AssetContainer;
  29817. }(BABYLON.AbstractScene));
  29818. BABYLON.AssetContainer = AssetContainer;
  29819. })(BABYLON || (BABYLON = {}));
  29820. //# sourceMappingURL=babylon.assetContainer.js.map
  29821. var BABYLON;
  29822. (function (BABYLON) {
  29823. /**
  29824. * Class used to store data that will be store in GPU memory
  29825. */
  29826. var Buffer = /** @class */ (function () {
  29827. /**
  29828. * Constructor
  29829. * @param engine the engine
  29830. * @param data the data to use for this buffer
  29831. * @param updatable whether the data is updatable
  29832. * @param stride the stride (optional)
  29833. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29834. * @param instanced whether the buffer is instanced (optional)
  29835. * @param useBytes set to true if the stride in in bytes (optional)
  29836. */
  29837. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29838. if (stride === void 0) { stride = 0; }
  29839. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29840. if (instanced === void 0) { instanced = false; }
  29841. if (useBytes === void 0) { useBytes = false; }
  29842. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29843. this._engine = engine.getScene().getEngine();
  29844. }
  29845. else {
  29846. this._engine = engine;
  29847. }
  29848. this._updatable = updatable;
  29849. this._instanced = instanced;
  29850. this._data = data;
  29851. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29852. if (!postponeInternalCreation) { // by default
  29853. this.create();
  29854. }
  29855. }
  29856. /**
  29857. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  29858. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29859. * @param offset defines offset in the buffer (0 by default)
  29860. * @param size defines the size in floats of attributes (position is 3 for instance)
  29861. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29862. * @param instanced defines if the vertex buffer contains indexed data
  29863. * @param useBytes defines if the offset and stride are in bytes
  29864. * @returns the new vertex buffer
  29865. */
  29866. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29867. if (useBytes === void 0) { useBytes = false; }
  29868. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29869. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29870. // a lot of these parameters are ignored as they are overriden by the buffer
  29871. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29872. };
  29873. // Properties
  29874. /**
  29875. * Gets a boolean indicating if the Buffer is updatable?
  29876. * @returns true if the buffer is updatable
  29877. */
  29878. Buffer.prototype.isUpdatable = function () {
  29879. return this._updatable;
  29880. };
  29881. /**
  29882. * Gets current buffer's data
  29883. * @returns a DataArray or null
  29884. */
  29885. Buffer.prototype.getData = function () {
  29886. return this._data;
  29887. };
  29888. /**
  29889. * Gets underlying native buffer
  29890. * @returns underlying native buffer
  29891. */
  29892. Buffer.prototype.getBuffer = function () {
  29893. return this._buffer;
  29894. };
  29895. /**
  29896. * Gets the stride in float32 units (i.e. byte stride / 4).
  29897. * May not be an integer if the byte stride is not divisible by 4.
  29898. * DEPRECATED. Use byteStride instead.
  29899. * @returns the stride in float32 units
  29900. */
  29901. Buffer.prototype.getStrideSize = function () {
  29902. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29903. };
  29904. // Methods
  29905. /**
  29906. * Store data into the buffer. If the buffer was already used it will be either recreated or updated depending on isUpdatable property
  29907. * @param data defines the data to store
  29908. */
  29909. Buffer.prototype.create = function (data) {
  29910. if (data === void 0) { data = null; }
  29911. if (!data && this._buffer) {
  29912. return; // nothing to do
  29913. }
  29914. data = data || this._data;
  29915. if (!data) {
  29916. return;
  29917. }
  29918. if (!this._buffer) { // create buffer
  29919. if (this._updatable) {
  29920. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29921. this._data = data;
  29922. }
  29923. else {
  29924. this._buffer = this._engine.createVertexBuffer(data);
  29925. }
  29926. }
  29927. else if (this._updatable) { // update buffer
  29928. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29929. this._data = data;
  29930. }
  29931. };
  29932. /** @hidden */
  29933. Buffer.prototype._rebuild = function () {
  29934. this._buffer = null;
  29935. this.create(this._data);
  29936. };
  29937. /**
  29938. * Update current buffer data
  29939. * @param data defines the data to store
  29940. */
  29941. Buffer.prototype.update = function (data) {
  29942. this.create(data);
  29943. };
  29944. /**
  29945. * Updates the data directly.
  29946. * @param data the new data
  29947. * @param offset the new offset
  29948. * @param vertexCount the vertex count (optional)
  29949. * @param useBytes set to true if the offset is in bytes
  29950. */
  29951. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29952. if (useBytes === void 0) { useBytes = false; }
  29953. if (!this._buffer) {
  29954. return;
  29955. }
  29956. if (this._updatable) { // update buffer
  29957. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29958. this._data = null;
  29959. }
  29960. };
  29961. /**
  29962. * Release all resources
  29963. */
  29964. Buffer.prototype.dispose = function () {
  29965. if (!this._buffer) {
  29966. return;
  29967. }
  29968. if (this._engine._releaseBuffer(this._buffer)) {
  29969. this._buffer = null;
  29970. }
  29971. };
  29972. return Buffer;
  29973. }());
  29974. BABYLON.Buffer = Buffer;
  29975. })(BABYLON || (BABYLON = {}));
  29976. //# sourceMappingURL=babylon.buffer.js.map
  29977. var BABYLON;
  29978. (function (BABYLON) {
  29979. /**
  29980. * Specialized buffer used to store vertex data
  29981. */
  29982. var VertexBuffer = /** @class */ (function () {
  29983. /**
  29984. * Constructor
  29985. * @param engine the engine
  29986. * @param data the data to use for this vertex buffer
  29987. * @param kind the vertex buffer kind
  29988. * @param updatable whether the data is updatable
  29989. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29990. * @param stride the stride (optional)
  29991. * @param instanced whether the buffer is instanced (optional)
  29992. * @param offset the offset of the data (optional)
  29993. * @param size the number of components (optional)
  29994. * @param type the type of the component (optional)
  29995. * @param normalized whether the data contains normalized data (optional)
  29996. * @param useBytes set to true if stride and offset are in bytes (optional)
  29997. */
  29998. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29999. if (normalized === void 0) { normalized = false; }
  30000. if (useBytes === void 0) { useBytes = false; }
  30001. if (data instanceof BABYLON.Buffer) {
  30002. this._buffer = data;
  30003. this._ownsBuffer = false;
  30004. }
  30005. else {
  30006. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  30007. this._ownsBuffer = true;
  30008. }
  30009. this._kind = kind;
  30010. if (type == undefined) {
  30011. var data_1 = this.getData();
  30012. this.type = VertexBuffer.FLOAT;
  30013. if (data_1 instanceof Int8Array)
  30014. this.type = VertexBuffer.BYTE;
  30015. else if (data_1 instanceof Uint8Array)
  30016. this.type = VertexBuffer.UNSIGNED_BYTE;
  30017. else if (data_1 instanceof Int16Array)
  30018. this.type = VertexBuffer.SHORT;
  30019. else if (data_1 instanceof Uint16Array)
  30020. this.type = VertexBuffer.UNSIGNED_SHORT;
  30021. else if (data_1 instanceof Int32Array)
  30022. this.type = VertexBuffer.INT;
  30023. else if (data_1 instanceof Uint32Array)
  30024. this.type = VertexBuffer.UNSIGNED_INT;
  30025. }
  30026. else {
  30027. this.type = type;
  30028. }
  30029. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  30030. if (useBytes) {
  30031. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  30032. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  30033. this.byteOffset = offset || 0;
  30034. }
  30035. else {
  30036. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  30037. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  30038. this.byteOffset = (offset || 0) * typeByteLength;
  30039. }
  30040. this.normalized = normalized;
  30041. this._instanced = instanced !== undefined ? instanced : false;
  30042. this._instanceDivisor = instanced ? 1 : 0;
  30043. }
  30044. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  30045. /**
  30046. * Gets or sets the instance divisor when in instanced mode
  30047. */
  30048. get: function () {
  30049. return this._instanceDivisor;
  30050. },
  30051. set: function (value) {
  30052. this._instanceDivisor = value;
  30053. if (value == 0) {
  30054. this._instanced = false;
  30055. }
  30056. else {
  30057. this._instanced = true;
  30058. }
  30059. },
  30060. enumerable: true,
  30061. configurable: true
  30062. });
  30063. /** @hidden */
  30064. VertexBuffer.prototype._rebuild = function () {
  30065. if (!this._buffer) {
  30066. return;
  30067. }
  30068. this._buffer._rebuild();
  30069. };
  30070. /**
  30071. * Returns the kind of the VertexBuffer (string)
  30072. * @returns a string
  30073. */
  30074. VertexBuffer.prototype.getKind = function () {
  30075. return this._kind;
  30076. };
  30077. // Properties
  30078. /**
  30079. * Gets a boolean indicating if the VertexBuffer is updatable?
  30080. * @returns true if the buffer is updatable
  30081. */
  30082. VertexBuffer.prototype.isUpdatable = function () {
  30083. return this._buffer.isUpdatable();
  30084. };
  30085. /**
  30086. * Gets current buffer's data
  30087. * @returns a DataArray or null
  30088. */
  30089. VertexBuffer.prototype.getData = function () {
  30090. return this._buffer.getData();
  30091. };
  30092. /**
  30093. * Gets underlying native buffer
  30094. * @returns underlying native buffer
  30095. */
  30096. VertexBuffer.prototype.getBuffer = function () {
  30097. return this._buffer.getBuffer();
  30098. };
  30099. /**
  30100. * Gets the stride in float32 units (i.e. byte stride / 4).
  30101. * May not be an integer if the byte stride is not divisible by 4.
  30102. * DEPRECATED. Use byteStride instead.
  30103. * @returns the stride in float32 units
  30104. */
  30105. VertexBuffer.prototype.getStrideSize = function () {
  30106. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  30107. };
  30108. /**
  30109. * Returns the offset as a multiple of the type byte length.
  30110. * DEPRECATED. Use byteOffset instead.
  30111. * @returns the offset in bytes
  30112. */
  30113. VertexBuffer.prototype.getOffset = function () {
  30114. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  30115. };
  30116. /**
  30117. * Returns the number of components per vertex attribute (integer)
  30118. * @returns the size in float
  30119. */
  30120. VertexBuffer.prototype.getSize = function () {
  30121. return this._size;
  30122. };
  30123. /**
  30124. * Gets a boolean indicating is the internal buffer of the VertexBuffer is instanced
  30125. * @returns true if this buffer is instanced
  30126. */
  30127. VertexBuffer.prototype.getIsInstanced = function () {
  30128. return this._instanced;
  30129. };
  30130. /**
  30131. * Returns the instancing divisor, zero for non-instanced (integer).
  30132. * @returns a number
  30133. */
  30134. VertexBuffer.prototype.getInstanceDivisor = function () {
  30135. return this._instanceDivisor;
  30136. };
  30137. // Methods
  30138. /**
  30139. * Store data into the buffer. If the buffer was already used it will be either recreated or updated depending on isUpdatable property
  30140. * @param data defines the data to store
  30141. */
  30142. VertexBuffer.prototype.create = function (data) {
  30143. this._buffer.create(data);
  30144. };
  30145. /**
  30146. * Updates the underlying buffer according to the passed numeric array or Float32Array.
  30147. * This function will create a new buffer if the current one is not updatable
  30148. * @param data defines the data to store
  30149. */
  30150. VertexBuffer.prototype.update = function (data) {
  30151. this._buffer.update(data);
  30152. };
  30153. /**
  30154. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  30155. * Returns the directly updated WebGLBuffer.
  30156. * @param data the new data
  30157. * @param offset the new offset
  30158. * @param useBytes set to true if the offset is in bytes
  30159. */
  30160. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  30161. if (useBytes === void 0) { useBytes = false; }
  30162. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  30163. };
  30164. /**
  30165. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  30166. */
  30167. VertexBuffer.prototype.dispose = function () {
  30168. if (this._ownsBuffer) {
  30169. this._buffer.dispose();
  30170. }
  30171. };
  30172. /**
  30173. * Enumerates each value of this vertex buffer as numbers.
  30174. * @param count the number of values to enumerate
  30175. * @param callback the callback function called for each value
  30176. */
  30177. VertexBuffer.prototype.forEach = function (count, callback) {
  30178. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  30179. };
  30180. /**
  30181. * Deduces the stride given a kind.
  30182. * @param kind The kind string to deduce
  30183. * @returns The deduced stride
  30184. */
  30185. VertexBuffer.DeduceStride = function (kind) {
  30186. switch (kind) {
  30187. case VertexBuffer.UVKind:
  30188. case VertexBuffer.UV2Kind:
  30189. case VertexBuffer.UV3Kind:
  30190. case VertexBuffer.UV4Kind:
  30191. case VertexBuffer.UV5Kind:
  30192. case VertexBuffer.UV6Kind:
  30193. return 2;
  30194. case VertexBuffer.NormalKind:
  30195. case VertexBuffer.PositionKind:
  30196. return 3;
  30197. case VertexBuffer.ColorKind:
  30198. case VertexBuffer.MatricesIndicesKind:
  30199. case VertexBuffer.MatricesIndicesExtraKind:
  30200. case VertexBuffer.MatricesWeightsKind:
  30201. case VertexBuffer.MatricesWeightsExtraKind:
  30202. case VertexBuffer.TangentKind:
  30203. return 4;
  30204. default:
  30205. throw new Error("Invalid kind '" + kind + "'");
  30206. }
  30207. };
  30208. /**
  30209. * Gets the byte length of the given type.
  30210. * @param type the type
  30211. * @returns the number of bytes
  30212. */
  30213. VertexBuffer.GetTypeByteLength = function (type) {
  30214. switch (type) {
  30215. case VertexBuffer.BYTE:
  30216. case VertexBuffer.UNSIGNED_BYTE:
  30217. return 1;
  30218. case VertexBuffer.SHORT:
  30219. case VertexBuffer.UNSIGNED_SHORT:
  30220. return 2;
  30221. case VertexBuffer.INT:
  30222. case VertexBuffer.FLOAT:
  30223. return 4;
  30224. default:
  30225. throw new Error("Invalid type '" + type + "'");
  30226. }
  30227. };
  30228. /**
  30229. * Enumerates each value of the given parameters as numbers.
  30230. * @param data the data to enumerate
  30231. * @param byteOffset the byte offset of the data
  30232. * @param byteStride the byte stride of the data
  30233. * @param componentCount the number of components per element
  30234. * @param componentType the type of the component
  30235. * @param count the total number of components
  30236. * @param normalized whether the data is normalized
  30237. * @param callback the callback function called for each value
  30238. */
  30239. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  30240. if (data instanceof Array) {
  30241. var offset = byteOffset / 4;
  30242. var stride = byteStride / 4;
  30243. for (var index = 0; index < count; index += componentCount) {
  30244. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  30245. callback(data[offset + componentIndex], index + componentIndex);
  30246. }
  30247. offset += stride;
  30248. }
  30249. }
  30250. else {
  30251. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  30252. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  30253. for (var index = 0; index < count; index += componentCount) {
  30254. var componentByteOffset = byteOffset;
  30255. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  30256. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  30257. callback(value, index + componentIndex);
  30258. componentByteOffset += componentByteLength;
  30259. }
  30260. byteOffset += byteStride;
  30261. }
  30262. }
  30263. };
  30264. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  30265. switch (type) {
  30266. case VertexBuffer.BYTE: {
  30267. var value = dataView.getInt8(byteOffset);
  30268. if (normalized) {
  30269. value = Math.max(value / 127, -1);
  30270. }
  30271. return value;
  30272. }
  30273. case VertexBuffer.UNSIGNED_BYTE: {
  30274. var value = dataView.getUint8(byteOffset);
  30275. if (normalized) {
  30276. value = value / 255;
  30277. }
  30278. return value;
  30279. }
  30280. case VertexBuffer.SHORT: {
  30281. var value = dataView.getInt16(byteOffset, true);
  30282. if (normalized) {
  30283. value = Math.max(value / 16383, -1);
  30284. }
  30285. return value;
  30286. }
  30287. case VertexBuffer.UNSIGNED_SHORT: {
  30288. var value = dataView.getUint16(byteOffset, true);
  30289. if (normalized) {
  30290. value = value / 65535;
  30291. }
  30292. return value;
  30293. }
  30294. case VertexBuffer.FLOAT: {
  30295. return dataView.getFloat32(byteOffset, true);
  30296. }
  30297. default: {
  30298. throw new Error("Invalid component type " + type);
  30299. }
  30300. }
  30301. };
  30302. /**
  30303. * The byte type.
  30304. */
  30305. VertexBuffer.BYTE = 5120;
  30306. /**
  30307. * The unsigned byte type.
  30308. */
  30309. VertexBuffer.UNSIGNED_BYTE = 5121;
  30310. /**
  30311. * The short type.
  30312. */
  30313. VertexBuffer.SHORT = 5122;
  30314. /**
  30315. * The unsigned short type.
  30316. */
  30317. VertexBuffer.UNSIGNED_SHORT = 5123;
  30318. /**
  30319. * The integer type.
  30320. */
  30321. VertexBuffer.INT = 5124;
  30322. /**
  30323. * The unsigned integer type.
  30324. */
  30325. VertexBuffer.UNSIGNED_INT = 5125;
  30326. /**
  30327. * The float type.
  30328. */
  30329. VertexBuffer.FLOAT = 5126;
  30330. // Enums
  30331. /**
  30332. * Positions
  30333. */
  30334. VertexBuffer.PositionKind = "position";
  30335. /**
  30336. * Normals
  30337. */
  30338. VertexBuffer.NormalKind = "normal";
  30339. /**
  30340. * Tangents
  30341. */
  30342. VertexBuffer.TangentKind = "tangent";
  30343. /**
  30344. * Texture coordinates
  30345. */
  30346. VertexBuffer.UVKind = "uv";
  30347. /**
  30348. * Texture coordinates 2
  30349. */
  30350. VertexBuffer.UV2Kind = "uv2";
  30351. /**
  30352. * Texture coordinates 3
  30353. */
  30354. VertexBuffer.UV3Kind = "uv3";
  30355. /**
  30356. * Texture coordinates 4
  30357. */
  30358. VertexBuffer.UV4Kind = "uv4";
  30359. /**
  30360. * Texture coordinates 5
  30361. */
  30362. VertexBuffer.UV5Kind = "uv5";
  30363. /**
  30364. * Texture coordinates 6
  30365. */
  30366. VertexBuffer.UV6Kind = "uv6";
  30367. /**
  30368. * Colors
  30369. */
  30370. VertexBuffer.ColorKind = "color";
  30371. /**
  30372. * Matrix indices (for bones)
  30373. */
  30374. VertexBuffer.MatricesIndicesKind = "matricesIndices";
  30375. /**
  30376. * Matrix weights (for bones)
  30377. */
  30378. VertexBuffer.MatricesWeightsKind = "matricesWeights";
  30379. /**
  30380. * Additional matrix indices (for bones)
  30381. */
  30382. VertexBuffer.MatricesIndicesExtraKind = "matricesIndicesExtra";
  30383. /**
  30384. * Additional matrix weights (for bones)
  30385. */
  30386. VertexBuffer.MatricesWeightsExtraKind = "matricesWeightsExtra";
  30387. return VertexBuffer;
  30388. }());
  30389. BABYLON.VertexBuffer = VertexBuffer;
  30390. })(BABYLON || (BABYLON = {}));
  30391. //# sourceMappingURL=babylon.vertexBuffer.js.map
  30392. //# sourceMappingURL=babylon.internalTextureLoader.js.map
  30393. var BABYLON;
  30394. (function (BABYLON) {
  30395. /**
  30396. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  30397. */
  30398. var DummyInternalTextureTracker = /** @class */ (function () {
  30399. function DummyInternalTextureTracker() {
  30400. /**
  30401. * Gets or set the previous tracker in the list
  30402. */
  30403. this.previous = null;
  30404. /**
  30405. * Gets or set the next tracker in the list
  30406. */
  30407. this.next = null;
  30408. }
  30409. return DummyInternalTextureTracker;
  30410. }());
  30411. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  30412. })(BABYLON || (BABYLON = {}));
  30413. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  30414. var BABYLON;
  30415. (function (BABYLON) {
  30416. /**
  30417. * Class used to store data associated with WebGL texture data for the engine
  30418. * This class should not be used directly
  30419. */
  30420. var InternalTexture = /** @class */ (function () {
  30421. /**
  30422. * Creates a new InternalTexture
  30423. * @param engine defines the engine to use
  30424. * @param dataSource defines the type of data that will be used
  30425. */
  30426. function InternalTexture(engine, dataSource) {
  30427. /**
  30428. * Observable called when the texture is loaded
  30429. */
  30430. this.onLoadedObservable = new BABYLON.Observable();
  30431. /**
  30432. * Gets or set the previous tracker in the list
  30433. */
  30434. this.previous = null;
  30435. /**
  30436. * Gets or set the next tracker in the list
  30437. */
  30438. this.next = null;
  30439. // Private
  30440. /** @hidden */
  30441. this._initialSlot = -1;
  30442. /** @hidden */
  30443. this._designatedSlot = -1;
  30444. /** @hidden */
  30445. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  30446. /** @hidden */
  30447. this._comparisonFunction = 0;
  30448. /** @hidden */
  30449. this._sphericalPolynomial = null;
  30450. /** @hidden */
  30451. this._lodGenerationScale = 0;
  30452. /** @hidden */
  30453. this._lodGenerationOffset = 0;
  30454. /** @hidden */
  30455. this._isRGBD = false;
  30456. /** @hidden */
  30457. this._references = 1;
  30458. this._engine = engine;
  30459. this._dataSource = dataSource;
  30460. this._webGLTexture = engine._createTexture();
  30461. }
  30462. /**
  30463. * Gets the Engine the texture belongs to.
  30464. * @returns The babylon engine
  30465. */
  30466. InternalTexture.prototype.getEngine = function () {
  30467. return this._engine;
  30468. };
  30469. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  30470. /**
  30471. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  30472. */
  30473. get: function () {
  30474. return this._dataSource;
  30475. },
  30476. enumerable: true,
  30477. configurable: true
  30478. });
  30479. /**
  30480. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  30481. */
  30482. InternalTexture.prototype.incrementReferences = function () {
  30483. this._references++;
  30484. };
  30485. /**
  30486. * Change the size of the texture (not the size of the content)
  30487. * @param width defines the new width
  30488. * @param height defines the new height
  30489. * @param depth defines the new depth (1 by default)
  30490. */
  30491. InternalTexture.prototype.updateSize = function (width, height, depth) {
  30492. if (depth === void 0) { depth = 1; }
  30493. this.width = width;
  30494. this.height = height;
  30495. this.depth = depth;
  30496. this.baseWidth = width;
  30497. this.baseHeight = height;
  30498. this.baseDepth = depth;
  30499. this._size = width * height * depth;
  30500. };
  30501. /** @hidden */
  30502. InternalTexture.prototype._rebuild = function () {
  30503. var _this = this;
  30504. var proxy;
  30505. this.isReady = false;
  30506. this._cachedCoordinatesMode = null;
  30507. this._cachedWrapU = null;
  30508. this._cachedWrapV = null;
  30509. this._cachedAnisotropicFilteringLevel = null;
  30510. switch (this._dataSource) {
  30511. case InternalTexture.DATASOURCE_TEMP:
  30512. return;
  30513. case InternalTexture.DATASOURCE_URL:
  30514. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  30515. _this.isReady = true;
  30516. }, null, this._buffer, undefined, this.format);
  30517. proxy._swapAndDie(this);
  30518. return;
  30519. case InternalTexture.DATASOURCE_RAW:
  30520. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30521. proxy._swapAndDie(this);
  30522. this.isReady = true;
  30523. return;
  30524. case InternalTexture.DATASOURCE_RAW3D:
  30525. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30526. proxy._swapAndDie(this);
  30527. this.isReady = true;
  30528. return;
  30529. case InternalTexture.DATASOURCE_DYNAMIC:
  30530. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  30531. proxy._swapAndDie(this);
  30532. // The engine will make sure to update content so no need to flag it as isReady = true
  30533. return;
  30534. case InternalTexture.DATASOURCE_RENDERTARGET:
  30535. var options = new BABYLON.RenderTargetCreationOptions();
  30536. options.generateDepthBuffer = this._generateDepthBuffer;
  30537. options.generateMipMaps = this.generateMipMaps;
  30538. options.generateStencilBuffer = this._generateStencilBuffer;
  30539. options.samplingMode = this.samplingMode;
  30540. options.type = this.type;
  30541. if (this.isCube) {
  30542. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  30543. }
  30544. else {
  30545. var size = {
  30546. width: this.width,
  30547. height: this.height
  30548. };
  30549. proxy = this._engine.createRenderTargetTexture(size, options);
  30550. }
  30551. proxy._swapAndDie(this);
  30552. this.isReady = true;
  30553. return;
  30554. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  30555. var depthTextureOptions = {
  30556. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  30557. comparisonFunction: this._comparisonFunction,
  30558. generateStencil: this._generateStencilBuffer,
  30559. isCube: this.isCube
  30560. };
  30561. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  30562. proxy._swapAndDie(this);
  30563. this.isReady = true;
  30564. return;
  30565. case InternalTexture.DATASOURCE_CUBE:
  30566. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  30567. _this.isReady = true;
  30568. }, null, this.format, this._extension);
  30569. proxy._swapAndDie(this);
  30570. return;
  30571. case InternalTexture.DATASOURCE_CUBERAW:
  30572. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30573. proxy._swapAndDie(this);
  30574. this.isReady = true;
  30575. return;
  30576. case InternalTexture.DATASOURCE_CUBERAW_RGBD:
  30577. proxy = this._engine.createRawCubeTexture(null, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30578. BABYLON.RawCubeTexture._UpdateRGBDAsync(proxy, this._bufferViewArrayArray, this._sphericalPolynomial, this._lodGenerationScale, this._lodGenerationOffset).then(function () {
  30579. _this.isReady = true;
  30580. });
  30581. proxy._swapAndDie(this);
  30582. return;
  30583. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  30584. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  30585. if (proxy) {
  30586. proxy._swapAndDie(_this);
  30587. }
  30588. _this.isReady = true;
  30589. }, null, this.format, this._extension);
  30590. proxy._sphericalPolynomial = this._sphericalPolynomial;
  30591. return;
  30592. }
  30593. };
  30594. /** @hidden */
  30595. InternalTexture.prototype._swapAndDie = function (target) {
  30596. target._webGLTexture = this._webGLTexture;
  30597. if (this._framebuffer) {
  30598. target._framebuffer = this._framebuffer;
  30599. }
  30600. if (this._depthStencilBuffer) {
  30601. target._depthStencilBuffer = this._depthStencilBuffer;
  30602. }
  30603. if (this._lodTextureHigh) {
  30604. if (target._lodTextureHigh) {
  30605. target._lodTextureHigh.dispose();
  30606. }
  30607. target._lodTextureHigh = this._lodTextureHigh;
  30608. }
  30609. if (this._lodTextureMid) {
  30610. if (target._lodTextureMid) {
  30611. target._lodTextureMid.dispose();
  30612. }
  30613. target._lodTextureMid = this._lodTextureMid;
  30614. }
  30615. if (this._lodTextureLow) {
  30616. if (target._lodTextureLow) {
  30617. target._lodTextureLow.dispose();
  30618. }
  30619. target._lodTextureLow = this._lodTextureLow;
  30620. }
  30621. var cache = this._engine.getLoadedTexturesCache();
  30622. var index = cache.indexOf(this);
  30623. if (index !== -1) {
  30624. cache.splice(index, 1);
  30625. }
  30626. };
  30627. /**
  30628. * Dispose the current allocated resources
  30629. */
  30630. InternalTexture.prototype.dispose = function () {
  30631. if (!this._webGLTexture) {
  30632. return;
  30633. }
  30634. this._references--;
  30635. if (this._references === 0) {
  30636. this._engine._releaseTexture(this);
  30637. this._webGLTexture = null;
  30638. this.previous = null;
  30639. this.next = null;
  30640. }
  30641. };
  30642. /**
  30643. * The source of the texture data is unknown
  30644. */
  30645. InternalTexture.DATASOURCE_UNKNOWN = 0;
  30646. /**
  30647. * Texture data comes from an URL
  30648. */
  30649. InternalTexture.DATASOURCE_URL = 1;
  30650. /**
  30651. * Texture data is only used for temporary storage
  30652. */
  30653. InternalTexture.DATASOURCE_TEMP = 2;
  30654. /**
  30655. * Texture data comes from raw data (ArrayBuffer)
  30656. */
  30657. InternalTexture.DATASOURCE_RAW = 3;
  30658. /**
  30659. * Texture content is dynamic (video or dynamic texture)
  30660. */
  30661. InternalTexture.DATASOURCE_DYNAMIC = 4;
  30662. /**
  30663. * Texture content is generated by rendering to it
  30664. */
  30665. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  30666. /**
  30667. * Texture content is part of a multi render target process
  30668. */
  30669. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  30670. /**
  30671. * Texture data comes from a cube data file
  30672. */
  30673. InternalTexture.DATASOURCE_CUBE = 7;
  30674. /**
  30675. * Texture data comes from a raw cube data
  30676. */
  30677. InternalTexture.DATASOURCE_CUBERAW = 8;
  30678. /**
  30679. * Texture data come from a prefiltered cube data file
  30680. */
  30681. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  30682. /**
  30683. * Texture content is raw 3D data
  30684. */
  30685. InternalTexture.DATASOURCE_RAW3D = 10;
  30686. /**
  30687. * Texture content is a depth texture
  30688. */
  30689. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  30690. /**
  30691. * Texture data comes from a raw cube data encoded with RGBD
  30692. */
  30693. InternalTexture.DATASOURCE_CUBERAW_RGBD = 12;
  30694. return InternalTexture;
  30695. }());
  30696. BABYLON.InternalTexture = InternalTexture;
  30697. })(BABYLON || (BABYLON = {}));
  30698. //# sourceMappingURL=babylon.internalTexture.js.map
  30699. var BABYLON;
  30700. (function (BABYLON) {
  30701. /**
  30702. * Base class of all the textures in babylon.
  30703. * It groups all the common properties the materials, post process, lights... might need
  30704. * in order to make a correct use of the texture.
  30705. */
  30706. var BaseTexture = /** @class */ (function () {
  30707. /**
  30708. * Instantiates a new BaseTexture.
  30709. * Base class of all the textures in babylon.
  30710. * It groups all the common properties the materials, post process, lights... might need
  30711. * in order to make a correct use of the texture.
  30712. * @param scene Define the scene the texture blongs to
  30713. */
  30714. function BaseTexture(scene) {
  30715. this._hasAlpha = false;
  30716. /**
  30717. * Defines if the alpha value should be determined via the rgb values.
  30718. * If true the luminance of the pixel might be used to find the corresponding alpha value.
  30719. */
  30720. this.getAlphaFromRGB = false;
  30721. /**
  30722. * Intensity or strength of the texture.
  30723. * It is commonly used by materials to fine tune the intensity of the texture
  30724. */
  30725. this.level = 1;
  30726. /**
  30727. * Define the UV chanel to use starting from 0 and defaulting to 0.
  30728. * This is part of the texture as textures usually maps to one uv set.
  30729. */
  30730. this.coordinatesIndex = 0;
  30731. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  30732. /**
  30733. * | Value | Type | Description |
  30734. * | ----- | ------------------ | ----------- |
  30735. * | 0 | CLAMP_ADDRESSMODE | |
  30736. * | 1 | WRAP_ADDRESSMODE | |
  30737. * | 2 | MIRROR_ADDRESSMODE | |
  30738. */
  30739. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30740. /**
  30741. * | Value | Type | Description |
  30742. * | ----- | ------------------ | ----------- |
  30743. * | 0 | CLAMP_ADDRESSMODE | |
  30744. * | 1 | WRAP_ADDRESSMODE | |
  30745. * | 2 | MIRROR_ADDRESSMODE | |
  30746. */
  30747. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30748. /**
  30749. * | Value | Type | Description |
  30750. * | ----- | ------------------ | ----------- |
  30751. * | 0 | CLAMP_ADDRESSMODE | |
  30752. * | 1 | WRAP_ADDRESSMODE | |
  30753. * | 2 | MIRROR_ADDRESSMODE | |
  30754. */
  30755. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  30756. /**
  30757. * With compliant hardware and browser (supporting anisotropic filtering)
  30758. * this defines the level of anisotropic filtering in the texture.
  30759. * The higher the better but the slower. This defaults to 4 as it seems to be the best tradeoff.
  30760. */
  30761. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  30762. /**
  30763. * Define if the texture is a cube texture or if false a 2d texture.
  30764. */
  30765. this.isCube = false;
  30766. /**
  30767. * Define if the texture is a 3d texture (webgl 2) or if false a 2d texture.
  30768. */
  30769. this.is3D = false;
  30770. /**
  30771. * Define if the texture contains data in gamma space (most of the png/jpg aside bump).
  30772. * HDR texture are usually stored in linear space.
  30773. * This only impacts the PBR and Background materials
  30774. */
  30775. this.gammaSpace = true;
  30776. /**
  30777. * Is Z inverted in the texture (useful in a cube texture).
  30778. */
  30779. this.invertZ = false;
  30780. /**
  30781. * @hidden
  30782. */
  30783. this.lodLevelInAlpha = false;
  30784. /**
  30785. * Define if the texture is a render target.
  30786. */
  30787. this.isRenderTarget = false;
  30788. /**
  30789. * Define the list of animation attached to the texture.
  30790. */
  30791. this.animations = new Array();
  30792. /**
  30793. * An event triggered when the texture is disposed.
  30794. */
  30795. this.onDisposeObservable = new BABYLON.Observable();
  30796. /**
  30797. * Define the current state of the loading sequence when in delayed load mode.
  30798. */
  30799. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30800. this._cachedSize = BABYLON.Size.Zero();
  30801. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30802. if (this._scene) {
  30803. this._scene.textures.push(this);
  30804. this._scene.onNewTextureAddedObservable.notifyObservers(this);
  30805. }
  30806. this._uid = null;
  30807. }
  30808. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  30809. get: function () {
  30810. return this._hasAlpha;
  30811. },
  30812. /**
  30813. * Define if the texture is having a usable alpha value (can be use for transparency or glossiness for instance).
  30814. */
  30815. set: function (value) {
  30816. if (this._hasAlpha === value) {
  30817. return;
  30818. }
  30819. this._hasAlpha = value;
  30820. if (this._scene) {
  30821. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  30822. }
  30823. },
  30824. enumerable: true,
  30825. configurable: true
  30826. });
  30827. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  30828. get: function () {
  30829. return this._coordinatesMode;
  30830. },
  30831. /**
  30832. * How a texture is mapped.
  30833. *
  30834. * | Value | Type | Description |
  30835. * | ----- | ----------------------------------- | ----------- |
  30836. * | 0 | EXPLICIT_MODE | |
  30837. * | 1 | SPHERICAL_MODE | |
  30838. * | 2 | PLANAR_MODE | |
  30839. * | 3 | CUBIC_MODE | |
  30840. * | 4 | PROJECTION_MODE | |
  30841. * | 5 | SKYBOX_MODE | |
  30842. * | 6 | INVCUBIC_MODE | |
  30843. * | 7 | EQUIRECTANGULAR_MODE | |
  30844. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30845. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30846. */
  30847. set: function (value) {
  30848. if (this._coordinatesMode === value) {
  30849. return;
  30850. }
  30851. this._coordinatesMode = value;
  30852. if (this._scene) {
  30853. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30854. }
  30855. },
  30856. enumerable: true,
  30857. configurable: true
  30858. });
  30859. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  30860. /**
  30861. * Gets whether or not the texture contains RGBD data.
  30862. */
  30863. get: function () {
  30864. return this._texture != null && this._texture._isRGBD;
  30865. },
  30866. enumerable: true,
  30867. configurable: true
  30868. });
  30869. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  30870. /**
  30871. * With prefiltered texture, defined the offset used during the prefiltering steps.
  30872. */
  30873. get: function () {
  30874. if (this._texture)
  30875. return this._texture._lodGenerationOffset;
  30876. return 0.0;
  30877. },
  30878. set: function (value) {
  30879. if (this._texture)
  30880. this._texture._lodGenerationOffset = value;
  30881. },
  30882. enumerable: true,
  30883. configurable: true
  30884. });
  30885. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  30886. /**
  30887. * With prefiltered texture, defined the scale used during the prefiltering steps.
  30888. */
  30889. get: function () {
  30890. if (this._texture)
  30891. return this._texture._lodGenerationScale;
  30892. return 0.0;
  30893. },
  30894. set: function (value) {
  30895. if (this._texture)
  30896. this._texture._lodGenerationScale = value;
  30897. },
  30898. enumerable: true,
  30899. configurable: true
  30900. });
  30901. Object.defineProperty(BaseTexture.prototype, "uid", {
  30902. /**
  30903. * Define the unique id of the texture in the scene.
  30904. */
  30905. get: function () {
  30906. if (!this._uid) {
  30907. this._uid = BABYLON.Tools.RandomId();
  30908. }
  30909. return this._uid;
  30910. },
  30911. enumerable: true,
  30912. configurable: true
  30913. });
  30914. /**
  30915. * Return a string representation of the texture.
  30916. * @returns the texture as a string
  30917. */
  30918. BaseTexture.prototype.toString = function () {
  30919. return this.name;
  30920. };
  30921. /**
  30922. * Get the class name of the texture.
  30923. * @returns "BaseTexture"
  30924. */
  30925. BaseTexture.prototype.getClassName = function () {
  30926. return "BaseTexture";
  30927. };
  30928. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30929. /**
  30930. * Callback triggered when the texture has been disposed.
  30931. * Kept for back compatibility, you can use the onDisposeObservable instead.
  30932. */
  30933. set: function (callback) {
  30934. if (this._onDisposeObserver) {
  30935. this.onDisposeObservable.remove(this._onDisposeObserver);
  30936. }
  30937. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30938. },
  30939. enumerable: true,
  30940. configurable: true
  30941. });
  30942. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30943. /**
  30944. * Define if the texture is preventinga material to render or not.
  30945. * If not and the texture is not ready, the engine will use a default black texture instead.
  30946. */
  30947. get: function () {
  30948. return true;
  30949. },
  30950. enumerable: true,
  30951. configurable: true
  30952. });
  30953. /**
  30954. * Get the scene the texture belongs to.
  30955. * @returns the scene or null if undefined
  30956. */
  30957. BaseTexture.prototype.getScene = function () {
  30958. return this._scene;
  30959. };
  30960. /**
  30961. * Get the texture transform matrix used to offset tile the texture for istance.
  30962. * @returns the transformation matrix
  30963. */
  30964. BaseTexture.prototype.getTextureMatrix = function () {
  30965. return BABYLON.Matrix.IdentityReadOnly;
  30966. };
  30967. /**
  30968. * Get the texture reflection matrix used to rotate/transform the reflection.
  30969. * @returns the reflection matrix
  30970. */
  30971. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30972. return BABYLON.Matrix.IdentityReadOnly;
  30973. };
  30974. /**
  30975. * Get the underlying lower level texture from Babylon.
  30976. * @returns the insternal texture
  30977. */
  30978. BaseTexture.prototype.getInternalTexture = function () {
  30979. return this._texture;
  30980. };
  30981. /**
  30982. * Get if the texture is ready to be consumed (either it is ready or it is not blocking)
  30983. * @returns true if ready or not blocking
  30984. */
  30985. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30986. return !this.isBlocking || this.isReady();
  30987. };
  30988. /**
  30989. * Get if the texture is ready to be used (downloaded, converted, mip mapped...).
  30990. * @returns true if fully ready
  30991. */
  30992. BaseTexture.prototype.isReady = function () {
  30993. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30994. this.delayLoad();
  30995. return false;
  30996. }
  30997. if (this._texture) {
  30998. return this._texture.isReady;
  30999. }
  31000. return false;
  31001. };
  31002. /**
  31003. * Get the size of the texture.
  31004. * @returns the texture size.
  31005. */
  31006. BaseTexture.prototype.getSize = function () {
  31007. if (this._texture) {
  31008. if (this._texture.width) {
  31009. this._cachedSize.width = this._texture.width;
  31010. this._cachedSize.height = this._texture.height;
  31011. return this._cachedSize;
  31012. }
  31013. if (this._texture._size) {
  31014. this._cachedSize.width = this._texture._size;
  31015. this._cachedSize.height = this._texture._size;
  31016. return this._cachedSize;
  31017. }
  31018. }
  31019. return this._cachedSize;
  31020. };
  31021. /**
  31022. * Get the base size of the texture.
  31023. * It can be different from the size if the texture has been resized for POT for instance
  31024. * @returns the base size
  31025. */
  31026. BaseTexture.prototype.getBaseSize = function () {
  31027. if (!this.isReady() || !this._texture)
  31028. return BABYLON.Size.Zero();
  31029. if (this._texture._size) {
  31030. return new BABYLON.Size(this._texture._size, this._texture._size);
  31031. }
  31032. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  31033. };
  31034. /**
  31035. * Scales the texture if is `canRescale()`
  31036. * @param ratio the resize factor we want to use to rescale
  31037. */
  31038. BaseTexture.prototype.scale = function (ratio) {
  31039. };
  31040. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  31041. /**
  31042. * Get if the texture can rescale.
  31043. */
  31044. get: function () {
  31045. return false;
  31046. },
  31047. enumerable: true,
  31048. configurable: true
  31049. });
  31050. /** @hidden */
  31051. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  31052. if (!this._scene) {
  31053. return null;
  31054. }
  31055. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  31056. for (var index = 0; index < texturesCache.length; index++) {
  31057. var texturesCacheEntry = texturesCache[index];
  31058. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  31059. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  31060. texturesCacheEntry.incrementReferences();
  31061. return texturesCacheEntry;
  31062. }
  31063. }
  31064. }
  31065. return null;
  31066. };
  31067. /** @hidden */
  31068. BaseTexture.prototype._rebuild = function () {
  31069. };
  31070. /**
  31071. * Triggers the load sequence in delayed load mode.
  31072. */
  31073. BaseTexture.prototype.delayLoad = function () {
  31074. };
  31075. /**
  31076. * Clones the texture.
  31077. * @returns the cloned texture
  31078. */
  31079. BaseTexture.prototype.clone = function () {
  31080. return null;
  31081. };
  31082. Object.defineProperty(BaseTexture.prototype, "textureType", {
  31083. /**
  31084. * Get the texture underlying type (INT, FLOAT...)
  31085. */
  31086. get: function () {
  31087. if (!this._texture) {
  31088. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  31089. }
  31090. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  31091. },
  31092. enumerable: true,
  31093. configurable: true
  31094. });
  31095. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  31096. /**
  31097. * Get the texture underlying format (RGB, RGBA...)
  31098. */
  31099. get: function () {
  31100. if (!this._texture) {
  31101. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  31102. }
  31103. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  31104. },
  31105. enumerable: true,
  31106. configurable: true
  31107. });
  31108. /**
  31109. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  31110. * This will returns an RGBA array buffer containing either in values (0-255) or
  31111. * float values (0-1) depending of the underlying buffer type.
  31112. * @param faceIndex defines the face of the texture to read (in case of cube texture)
  31113. * @param level defines the LOD level of the texture to read (in case of Mip Maps)
  31114. * @param buffer defines a user defined buffer to fill with data (can be null)
  31115. * @returns The Array buffer containing the pixels data.
  31116. */
  31117. BaseTexture.prototype.readPixels = function (faceIndex, level, buffer) {
  31118. if (faceIndex === void 0) { faceIndex = 0; }
  31119. if (level === void 0) { level = 0; }
  31120. if (buffer === void 0) { buffer = null; }
  31121. if (!this._texture) {
  31122. return null;
  31123. }
  31124. var size = this.getSize();
  31125. var width = size.width;
  31126. var height = size.height;
  31127. var scene = this.getScene();
  31128. if (!scene) {
  31129. return null;
  31130. }
  31131. var engine = scene.getEngine();
  31132. if (level != 0) {
  31133. width = width / Math.pow(2, level);
  31134. height = height / Math.pow(2, level);
  31135. width = Math.round(width);
  31136. height = Math.round(height);
  31137. }
  31138. if (this._texture.isCube) {
  31139. return engine._readTexturePixels(this._texture, width, height, faceIndex, level, buffer);
  31140. }
  31141. return engine._readTexturePixels(this._texture, width, height, -1, level, buffer);
  31142. };
  31143. /**
  31144. * Release and destroy the underlying lower level texture aka internalTexture.
  31145. */
  31146. BaseTexture.prototype.releaseInternalTexture = function () {
  31147. if (this._texture) {
  31148. this._texture.dispose();
  31149. this._texture = null;
  31150. }
  31151. };
  31152. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  31153. /**
  31154. * Get the polynomial representation of the texture data.
  31155. * This is mainly use as a fast way to recover IBL Diffuse irradiance data.
  31156. * @see https://learnopengl.com/PBR/IBL/Diffuse-irradiance
  31157. */
  31158. get: function () {
  31159. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  31160. return null;
  31161. }
  31162. if (!this._texture._sphericalPolynomial) {
  31163. this._texture._sphericalPolynomial =
  31164. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  31165. }
  31166. return this._texture._sphericalPolynomial;
  31167. },
  31168. set: function (value) {
  31169. if (this._texture) {
  31170. this._texture._sphericalPolynomial = value;
  31171. }
  31172. },
  31173. enumerable: true,
  31174. configurable: true
  31175. });
  31176. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  31177. /** @hidden */
  31178. get: function () {
  31179. if (this._texture) {
  31180. return this._texture._lodTextureHigh;
  31181. }
  31182. return null;
  31183. },
  31184. enumerable: true,
  31185. configurable: true
  31186. });
  31187. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  31188. /** @hidden */
  31189. get: function () {
  31190. if (this._texture) {
  31191. return this._texture._lodTextureMid;
  31192. }
  31193. return null;
  31194. },
  31195. enumerable: true,
  31196. configurable: true
  31197. });
  31198. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  31199. /** @hidden */
  31200. get: function () {
  31201. if (this._texture) {
  31202. return this._texture._lodTextureLow;
  31203. }
  31204. return null;
  31205. },
  31206. enumerable: true,
  31207. configurable: true
  31208. });
  31209. /**
  31210. * Dispose the texture and release its associated resources.
  31211. */
  31212. BaseTexture.prototype.dispose = function () {
  31213. if (!this._scene) {
  31214. return;
  31215. }
  31216. // Animations
  31217. this._scene.stopAnimation(this);
  31218. // Remove from scene
  31219. this._scene._removePendingData(this);
  31220. var index = this._scene.textures.indexOf(this);
  31221. if (index >= 0) {
  31222. this._scene.textures.splice(index, 1);
  31223. }
  31224. this._scene.onTextureRemovedObservable.notifyObservers(this);
  31225. if (this._texture === undefined) {
  31226. return;
  31227. }
  31228. // Release
  31229. this.releaseInternalTexture();
  31230. // Callback
  31231. this.onDisposeObservable.notifyObservers(this);
  31232. this.onDisposeObservable.clear();
  31233. };
  31234. /**
  31235. * Serialize the texture into a JSON representation that can be parsed later on.
  31236. * @returns the JSON representation of the texture
  31237. */
  31238. BaseTexture.prototype.serialize = function () {
  31239. if (!this.name) {
  31240. return null;
  31241. }
  31242. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  31243. // Animations
  31244. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  31245. return serializationObject;
  31246. };
  31247. /**
  31248. * Helper function to be called back once a list of texture contains only ready textures.
  31249. * @param textures Define the list of textures to wait for
  31250. * @param callback Define the callback triggered once the entire list will be ready
  31251. */
  31252. BaseTexture.WhenAllReady = function (textures, callback) {
  31253. var numRemaining = textures.length;
  31254. if (numRemaining === 0) {
  31255. callback();
  31256. return;
  31257. }
  31258. var _loop_1 = function () {
  31259. texture = textures[i];
  31260. if (texture.isReady()) {
  31261. if (--numRemaining === 0) {
  31262. callback();
  31263. }
  31264. }
  31265. else {
  31266. onLoadObservable = texture.onLoadObservable;
  31267. var onLoadCallback_1 = function () {
  31268. onLoadObservable.removeCallback(onLoadCallback_1);
  31269. if (--numRemaining === 0) {
  31270. callback();
  31271. }
  31272. };
  31273. onLoadObservable.add(onLoadCallback_1);
  31274. }
  31275. };
  31276. var texture, onLoadObservable;
  31277. for (var i = 0; i < textures.length; i++) {
  31278. _loop_1();
  31279. }
  31280. };
  31281. /**
  31282. * Default anisotropic filtering level for the application.
  31283. * It is set to 4 as a good tradeoff between perf and quality.
  31284. */
  31285. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  31286. __decorate([
  31287. BABYLON.serialize()
  31288. ], BaseTexture.prototype, "name", void 0);
  31289. __decorate([
  31290. BABYLON.serialize("hasAlpha")
  31291. ], BaseTexture.prototype, "_hasAlpha", void 0);
  31292. __decorate([
  31293. BABYLON.serialize()
  31294. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  31295. __decorate([
  31296. BABYLON.serialize()
  31297. ], BaseTexture.prototype, "level", void 0);
  31298. __decorate([
  31299. BABYLON.serialize()
  31300. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  31301. __decorate([
  31302. BABYLON.serialize("coordinatesMode")
  31303. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  31304. __decorate([
  31305. BABYLON.serialize()
  31306. ], BaseTexture.prototype, "wrapU", void 0);
  31307. __decorate([
  31308. BABYLON.serialize()
  31309. ], BaseTexture.prototype, "wrapV", void 0);
  31310. __decorate([
  31311. BABYLON.serialize()
  31312. ], BaseTexture.prototype, "wrapR", void 0);
  31313. __decorate([
  31314. BABYLON.serialize()
  31315. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  31316. __decorate([
  31317. BABYLON.serialize()
  31318. ], BaseTexture.prototype, "isCube", void 0);
  31319. __decorate([
  31320. BABYLON.serialize()
  31321. ], BaseTexture.prototype, "is3D", void 0);
  31322. __decorate([
  31323. BABYLON.serialize()
  31324. ], BaseTexture.prototype, "gammaSpace", void 0);
  31325. __decorate([
  31326. BABYLON.serialize()
  31327. ], BaseTexture.prototype, "invertZ", void 0);
  31328. __decorate([
  31329. BABYLON.serialize()
  31330. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  31331. __decorate([
  31332. BABYLON.serialize()
  31333. ], BaseTexture.prototype, "lodGenerationOffset", null);
  31334. __decorate([
  31335. BABYLON.serialize()
  31336. ], BaseTexture.prototype, "lodGenerationScale", null);
  31337. __decorate([
  31338. BABYLON.serialize()
  31339. ], BaseTexture.prototype, "isRenderTarget", void 0);
  31340. return BaseTexture;
  31341. }());
  31342. BABYLON.BaseTexture = BaseTexture;
  31343. })(BABYLON || (BABYLON = {}));
  31344. //# sourceMappingURL=babylon.baseTexture.js.map
  31345. var BABYLON;
  31346. (function (BABYLON) {
  31347. /**
  31348. * This represents a texture in babylon. It can be easily loaded from a network, base64 or html input.
  31349. * @see http://doc.babylonjs.com/babylon101/materials#texture
  31350. */
  31351. var Texture = /** @class */ (function (_super) {
  31352. __extends(Texture, _super);
  31353. /**
  31354. * Instantiates a new texture.
  31355. * This represents a texture in babylon. It can be easily loaded from a network, base64 or html input.
  31356. * @see http://doc.babylonjs.com/babylon101/materials#texture
  31357. * @param url define the url of the picture to load as a texture
  31358. * @param scene define the scene the texture will belong to
  31359. * @param noMipmap define if the texture will require mip maps or not
  31360. * @param invertY define if the texture needs to be inverted on the y axis during loading
  31361. * @param samplingMode define the sampling mode we want for the texture while fectching from it (Texture.NEAREST_SAMPLINGMODE...)
  31362. * @param onLoad define a callback triggered when the texture has been loaded
  31363. * @param onError define a callback triggered when an error occurred during the loading session
  31364. * @param buffer define the buffer to load the texture from in case the texture is loaded from a buffer representation
  31365. * @param deleteBuffer define if the buffer we are loading the texture from should be deleted after load
  31366. * @param format define the format of the texture we are trying to load (Engine.TEXTUREFORMAT_RGBA...)
  31367. */
  31368. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  31369. if (noMipmap === void 0) { noMipmap = false; }
  31370. if (invertY === void 0) { invertY = true; }
  31371. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31372. if (onLoad === void 0) { onLoad = null; }
  31373. if (onError === void 0) { onError = null; }
  31374. if (buffer === void 0) { buffer = null; }
  31375. if (deleteBuffer === void 0) { deleteBuffer = false; }
  31376. var _this = _super.call(this, scene) || this;
  31377. /**
  31378. * Define an offset on the texture to offset the u coordinates of the UVs
  31379. * @see http://doc.babylonjs.com/how_to/more_materials#offsetting
  31380. */
  31381. _this.uOffset = 0;
  31382. /**
  31383. * Define an offset on the texture to offset the v coordinates of the UVs
  31384. * @see http://doc.babylonjs.com/how_to/more_materials#offsetting
  31385. */
  31386. _this.vOffset = 0;
  31387. /**
  31388. * Define an offset on the texture to scale the u coordinates of the UVs
  31389. * @see http://doc.babylonjs.com/how_to/more_materials#tiling
  31390. */
  31391. _this.uScale = 1.0;
  31392. /**
  31393. * Define an offset on the texture to scale the v coordinates of the UVs
  31394. * @see http://doc.babylonjs.com/how_to/more_materials#tiling
  31395. */
  31396. _this.vScale = 1.0;
  31397. /**
  31398. * Define an offset on the texture to rotate around the u coordinates of the UVs
  31399. * @see http://doc.babylonjs.com/how_to/more_materials
  31400. */
  31401. _this.uAng = 0;
  31402. /**
  31403. * Define an offset on the texture to rotate around the v coordinates of the UVs
  31404. * @see http://doc.babylonjs.com/how_to/more_materials
  31405. */
  31406. _this.vAng = 0;
  31407. /**
  31408. * Define an offset on the texture to rotate around the w coordinates of the UVs (in case of 3d texture)
  31409. * @see http://doc.babylonjs.com/how_to/more_materials
  31410. */
  31411. _this.wAng = 0;
  31412. /**
  31413. * Defines the center of rotation (U)
  31414. */
  31415. _this.uRotationCenter = 0.5;
  31416. /**
  31417. * Defines the center of rotation (V)
  31418. */
  31419. _this.vRotationCenter = 0.5;
  31420. /**
  31421. * Defines the center of rotation (W)
  31422. */
  31423. _this.wRotationCenter = 0.5;
  31424. /**
  31425. * Observable triggered once the texture has been loaded.
  31426. */
  31427. _this.onLoadObservable = new BABYLON.Observable();
  31428. _this._isBlocking = true;
  31429. _this.name = url || "";
  31430. _this.url = url;
  31431. _this._noMipmap = noMipmap;
  31432. _this._invertY = invertY;
  31433. _this._samplingMode = samplingMode;
  31434. _this._buffer = buffer;
  31435. _this._deleteBuffer = deleteBuffer;
  31436. if (format) {
  31437. _this._format = format;
  31438. }
  31439. scene = _this.getScene();
  31440. if (!scene) {
  31441. return _this;
  31442. }
  31443. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  31444. var load = function () {
  31445. if (_this.onLoadObservable.hasObservers()) {
  31446. _this.onLoadObservable.notifyObservers(_this);
  31447. }
  31448. if (onLoad) {
  31449. onLoad();
  31450. }
  31451. if (!_this.isBlocking && scene) {
  31452. scene.resetCachedMaterial();
  31453. }
  31454. };
  31455. if (!_this.url) {
  31456. _this._delayedOnLoad = load;
  31457. _this._delayedOnError = onError;
  31458. return _this;
  31459. }
  31460. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  31461. if (!_this._texture) {
  31462. if (!scene.useDelayedTextureLoading) {
  31463. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  31464. if (deleteBuffer) {
  31465. delete _this._buffer;
  31466. }
  31467. }
  31468. else {
  31469. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31470. _this._delayedOnLoad = load;
  31471. _this._delayedOnError = onError;
  31472. }
  31473. }
  31474. else {
  31475. if (_this._texture.isReady) {
  31476. BABYLON.Tools.SetImmediate(function () { return load(); });
  31477. }
  31478. else {
  31479. _this._texture.onLoadedObservable.add(load);
  31480. }
  31481. }
  31482. return _this;
  31483. }
  31484. Object.defineProperty(Texture.prototype, "noMipmap", {
  31485. /**
  31486. * Are mip maps generated for this texture or not.
  31487. */
  31488. get: function () {
  31489. return this._noMipmap;
  31490. },
  31491. enumerable: true,
  31492. configurable: true
  31493. });
  31494. Object.defineProperty(Texture.prototype, "isBlocking", {
  31495. get: function () {
  31496. return this._isBlocking;
  31497. },
  31498. /**
  31499. * Is the texture preventing material to render while loading.
  31500. * If false, a default texture will be used instead of the loading one during the preparation step.
  31501. */
  31502. set: function (value) {
  31503. this._isBlocking = value;
  31504. },
  31505. enumerable: true,
  31506. configurable: true
  31507. });
  31508. Object.defineProperty(Texture.prototype, "samplingMode", {
  31509. /**
  31510. * Get the current sampling mode associated with the texture.
  31511. */
  31512. get: function () {
  31513. return this._samplingMode;
  31514. },
  31515. enumerable: true,
  31516. configurable: true
  31517. });
  31518. /**
  31519. * Update the url (and optional buffer) of this texture if url was null during construction.
  31520. * @param url the url of the texture
  31521. * @param buffer the buffer of the texture (defaults to null)
  31522. */
  31523. Texture.prototype.updateURL = function (url, buffer) {
  31524. if (buffer === void 0) { buffer = null; }
  31525. if (this.url) {
  31526. throw new Error("URL is already set");
  31527. }
  31528. this.url = url;
  31529. this._buffer = buffer;
  31530. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31531. this.delayLoad();
  31532. };
  31533. /**
  31534. * Finish the loading sequence of a texture flagged as delayed load.
  31535. * @hidden
  31536. */
  31537. Texture.prototype.delayLoad = function () {
  31538. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  31539. return;
  31540. }
  31541. var scene = this.getScene();
  31542. if (!scene) {
  31543. return;
  31544. }
  31545. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  31546. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  31547. if (!this._texture) {
  31548. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  31549. if (this._deleteBuffer) {
  31550. delete this._buffer;
  31551. }
  31552. }
  31553. else {
  31554. if (this._delayedOnLoad) {
  31555. if (this._texture.isReady) {
  31556. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  31557. }
  31558. else {
  31559. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  31560. }
  31561. }
  31562. }
  31563. this._delayedOnLoad = null;
  31564. this._delayedOnError = null;
  31565. };
  31566. /**
  31567. * Update the sampling mode of the texture.
  31568. * Default is Trilinear mode.
  31569. *
  31570. * | Value | Type | Description |
  31571. * | ----- | ------------------ | ----------- |
  31572. * | 1 | NEAREST_SAMPLINGMODE or NEAREST_NEAREST_MIPLINEAR | Nearest is: mag = nearest, min = nearest, mip = linear |
  31573. * | 2 | BILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPNEAREST | Bilinear is: mag = linear, min = linear, mip = nearest |
  31574. * | 3 | TRILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPLINEAR | Trilinear is: mag = linear, min = linear, mip = linear |
  31575. * | 4 | NEAREST_NEAREST_MIPNEAREST | |
  31576. * | 5 | NEAREST_LINEAR_MIPNEAREST | |
  31577. * | 6 | NEAREST_LINEAR_MIPLINEAR | |
  31578. * | 7 | NEAREST_LINEAR | |
  31579. * | 8 | NEAREST_NEAREST | |
  31580. * | 9 | LINEAR_NEAREST_MIPNEAREST | |
  31581. * | 10 | LINEAR_NEAREST_MIPLINEAR | |
  31582. * | 11 | LINEAR_LINEAR | |
  31583. * | 12 | LINEAR_NEAREST | |
  31584. *
  31585. * > _mag_: magnification filter (close to the viewer)
  31586. * > _min_: minification filter (far from the viewer)
  31587. * > _mip_: filter used between mip map levels
  31588. *@param samplingMode Define the new sampling mode of the texture
  31589. */
  31590. Texture.prototype.updateSamplingMode = function (samplingMode) {
  31591. if (!this._texture) {
  31592. return;
  31593. }
  31594. var scene = this.getScene();
  31595. if (!scene) {
  31596. return;
  31597. }
  31598. this._samplingMode = samplingMode;
  31599. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  31600. };
  31601. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  31602. x *= this.uScale;
  31603. y *= this.vScale;
  31604. x -= this.uRotationCenter * this.uScale;
  31605. y -= this.vRotationCenter * this.vScale;
  31606. z -= this.wRotationCenter;
  31607. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  31608. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  31609. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  31610. t.z += this.wRotationCenter;
  31611. };
  31612. /**
  31613. * Get the current texture matrix which includes the requested offsetting, tiling and rotation components.
  31614. * @returns the transform matrix of the texture.
  31615. */
  31616. Texture.prototype.getTextureMatrix = function () {
  31617. var _this = this;
  31618. if (this.uOffset === this._cachedUOffset &&
  31619. this.vOffset === this._cachedVOffset &&
  31620. this.uScale === this._cachedUScale &&
  31621. this.vScale === this._cachedVScale &&
  31622. this.uAng === this._cachedUAng &&
  31623. this.vAng === this._cachedVAng &&
  31624. this.wAng === this._cachedWAng) {
  31625. return this._cachedTextureMatrix;
  31626. }
  31627. this._cachedUOffset = this.uOffset;
  31628. this._cachedVOffset = this.vOffset;
  31629. this._cachedUScale = this.uScale;
  31630. this._cachedVScale = this.vScale;
  31631. this._cachedUAng = this.uAng;
  31632. this._cachedVAng = this.vAng;
  31633. this._cachedWAng = this.wAng;
  31634. if (!this._cachedTextureMatrix) {
  31635. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  31636. this._rowGenerationMatrix = new BABYLON.Matrix();
  31637. this._t0 = BABYLON.Vector3.Zero();
  31638. this._t1 = BABYLON.Vector3.Zero();
  31639. this._t2 = BABYLON.Vector3.Zero();
  31640. }
  31641. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  31642. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  31643. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  31644. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  31645. this._t1.subtractInPlace(this._t0);
  31646. this._t2.subtractInPlace(this._t0);
  31647. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31648. this._cachedTextureMatrix.m[0] = this._t1.x;
  31649. this._cachedTextureMatrix.m[1] = this._t1.y;
  31650. this._cachedTextureMatrix.m[2] = this._t1.z;
  31651. this._cachedTextureMatrix.m[4] = this._t2.x;
  31652. this._cachedTextureMatrix.m[5] = this._t2.y;
  31653. this._cachedTextureMatrix.m[6] = this._t2.z;
  31654. this._cachedTextureMatrix.m[8] = this._t0.x;
  31655. this._cachedTextureMatrix.m[9] = this._t0.y;
  31656. this._cachedTextureMatrix.m[10] = this._t0.z;
  31657. var scene = this.getScene();
  31658. if (!scene) {
  31659. return this._cachedTextureMatrix;
  31660. }
  31661. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  31662. return mat.hasTexture(_this);
  31663. });
  31664. return this._cachedTextureMatrix;
  31665. };
  31666. /**
  31667. * Get the current matrix used to apply reflection. This is useful to rotate an environment texture for instance.
  31668. * @returns The reflection texture transform
  31669. */
  31670. Texture.prototype.getReflectionTextureMatrix = function () {
  31671. var _this = this;
  31672. var scene = this.getScene();
  31673. if (!scene) {
  31674. return this._cachedTextureMatrix;
  31675. }
  31676. if (this.uOffset === this._cachedUOffset &&
  31677. this.vOffset === this._cachedVOffset &&
  31678. this.uScale === this._cachedUScale &&
  31679. this.vScale === this._cachedVScale &&
  31680. this.coordinatesMode === this._cachedCoordinatesMode) {
  31681. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  31682. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  31683. return this._cachedTextureMatrix;
  31684. }
  31685. }
  31686. else {
  31687. return this._cachedTextureMatrix;
  31688. }
  31689. }
  31690. if (!this._cachedTextureMatrix) {
  31691. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  31692. }
  31693. if (!this._projectionModeMatrix) {
  31694. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  31695. }
  31696. this._cachedUOffset = this.uOffset;
  31697. this._cachedVOffset = this.vOffset;
  31698. this._cachedUScale = this.uScale;
  31699. this._cachedVScale = this.vScale;
  31700. this._cachedCoordinatesMode = this.coordinatesMode;
  31701. switch (this.coordinatesMode) {
  31702. case Texture.PLANAR_MODE:
  31703. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31704. this._cachedTextureMatrix[0] = this.uScale;
  31705. this._cachedTextureMatrix[5] = this.vScale;
  31706. this._cachedTextureMatrix[12] = this.uOffset;
  31707. this._cachedTextureMatrix[13] = this.vOffset;
  31708. break;
  31709. case Texture.PROJECTION_MODE:
  31710. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  31711. this._projectionModeMatrix.m[0] = 0.5;
  31712. this._projectionModeMatrix.m[5] = -0.5;
  31713. this._projectionModeMatrix.m[10] = 0.0;
  31714. this._projectionModeMatrix.m[12] = 0.5;
  31715. this._projectionModeMatrix.m[13] = 0.5;
  31716. this._projectionModeMatrix.m[14] = 1.0;
  31717. this._projectionModeMatrix.m[15] = 1.0;
  31718. var projectionMatrix = scene.getProjectionMatrix();
  31719. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  31720. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  31721. break;
  31722. default:
  31723. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31724. break;
  31725. }
  31726. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  31727. return (mat.getActiveTextures().indexOf(_this) !== -1);
  31728. });
  31729. return this._cachedTextureMatrix;
  31730. };
  31731. /**
  31732. * Clones the texture.
  31733. * @returns the cloned texture
  31734. */
  31735. Texture.prototype.clone = function () {
  31736. var _this = this;
  31737. return BABYLON.SerializationHelper.Clone(function () {
  31738. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  31739. }, this);
  31740. };
  31741. /**
  31742. * Serialize the texture to a JSON representation we can easily use in the resepective Parse function.
  31743. * @returns The JSON representation of the texture
  31744. */
  31745. Texture.prototype.serialize = function () {
  31746. var serializationObject = _super.prototype.serialize.call(this);
  31747. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  31748. serializationObject.base64String = this._buffer;
  31749. serializationObject.name = serializationObject.name.replace("data:", "");
  31750. }
  31751. serializationObject.invertY = this._invertY;
  31752. serializationObject.samplingMode = this.samplingMode;
  31753. return serializationObject;
  31754. };
  31755. /**
  31756. * Get the current class name of the texture usefull for serialization or dynamic coding.
  31757. * @returns "Texture"
  31758. */
  31759. Texture.prototype.getClassName = function () {
  31760. return "Texture";
  31761. };
  31762. /**
  31763. * Dispose the texture and release its associated resources.
  31764. */
  31765. Texture.prototype.dispose = function () {
  31766. _super.prototype.dispose.call(this);
  31767. this.onLoadObservable.clear();
  31768. this._delayedOnLoad = null;
  31769. this._delayedOnError = null;
  31770. };
  31771. /**
  31772. * Parse the JSON representation of a texture in order to recreate the texture in the given scene.
  31773. * @param parsedTexture Define the JSON representation of the texture
  31774. * @param scene Define the scene the parsed texture should be instantiated in
  31775. * @param rootUrl Define the root url of the parsing sequence in the case of relative dependencies
  31776. * @returns The parsed texture if successful
  31777. */
  31778. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  31779. if (parsedTexture.customType) {
  31780. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  31781. // Update Sampling Mode
  31782. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  31783. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  31784. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  31785. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  31786. }
  31787. }
  31788. return parsedCustomTexture;
  31789. }
  31790. if (parsedTexture.isCube) {
  31791. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  31792. }
  31793. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  31794. return null;
  31795. }
  31796. var texture = BABYLON.SerializationHelper.Parse(function () {
  31797. var generateMipMaps = true;
  31798. if (parsedTexture.noMipmap) {
  31799. generateMipMaps = false;
  31800. }
  31801. if (parsedTexture.mirrorPlane) {
  31802. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31803. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  31804. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  31805. return mirrorTexture;
  31806. }
  31807. else if (parsedTexture.isRenderTarget) {
  31808. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31809. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  31810. return renderTargetTexture;
  31811. }
  31812. else {
  31813. var texture;
  31814. if (parsedTexture.base64String) {
  31815. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  31816. }
  31817. else {
  31818. var url = rootUrl + parsedTexture.name;
  31819. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  31820. url = parsedTexture.url;
  31821. }
  31822. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  31823. }
  31824. return texture;
  31825. }
  31826. }, parsedTexture, scene);
  31827. // Update Sampling Mode
  31828. if (parsedTexture.samplingMode) {
  31829. var sampling = parsedTexture.samplingMode;
  31830. if (texture._samplingMode !== sampling) {
  31831. texture.updateSamplingMode(sampling);
  31832. }
  31833. }
  31834. // Animations
  31835. if (parsedTexture.animations) {
  31836. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  31837. var parsedAnimation = parsedTexture.animations[animationIndex];
  31838. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  31839. }
  31840. }
  31841. return texture;
  31842. };
  31843. /**
  31844. * Creates a texture from its base 64 representation.
  31845. * @param data Define the base64 payload without the data: prefix
  31846. * @param name Define the name of the texture in the scene useful fo caching purpose for instance
  31847. * @param scene Define the scene the texture should belong to
  31848. * @param noMipmap Forces the texture to not create mip map information if true
  31849. * @param invertY define if the texture needs to be inverted on the y axis during loading
  31850. * @param samplingMode define the sampling mode we want for the texture while fectching from it (Texture.NEAREST_SAMPLINGMODE...)
  31851. * @param onLoad define a callback triggered when the texture has been loaded
  31852. * @param onError define a callback triggered when an error occurred during the loading session
  31853. * @param format define the format of the texture we are trying to load (Engine.TEXTUREFORMAT_RGBA...)
  31854. * @returns the created texture
  31855. */
  31856. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31857. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31858. if (onLoad === void 0) { onLoad = null; }
  31859. if (onError === void 0) { onError = null; }
  31860. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31861. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  31862. };
  31863. /**
  31864. * Creates a texture from its data: representation. (data: will be added in case only the payload has been passed in)
  31865. * @param data Define the base64 payload without the data: prefix
  31866. * @param name Define the name of the texture in the scene useful fo caching purpose for instance
  31867. * @param buffer define the buffer to load the texture from in case the texture is loaded from a buffer representation
  31868. * @param scene Define the scene the texture should belong to
  31869. * @param deleteBuffer define if the buffer we are loading the texture from should be deleted after load
  31870. * @param noMipmap Forces the texture to not create mip map information if true
  31871. * @param invertY define if the texture needs to be inverted on the y axis during loading
  31872. * @param samplingMode define the sampling mode we want for the texture while fectching from it (Texture.NEAREST_SAMPLINGMODE...)
  31873. * @param onLoad define a callback triggered when the texture has been loaded
  31874. * @param onError define a callback triggered when an error occurred during the loading session
  31875. * @param format define the format of the texture we are trying to load (Engine.TEXTUREFORMAT_RGBA...)
  31876. * @returns the created texture
  31877. */
  31878. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31879. if (deleteBuffer === void 0) { deleteBuffer = false; }
  31880. if (noMipmap === void 0) { noMipmap = false; }
  31881. if (invertY === void 0) { invertY = true; }
  31882. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31883. if (onLoad === void 0) { onLoad = null; }
  31884. if (onError === void 0) { onError = null; }
  31885. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31886. if (name.substr(0, 5) !== "data:") {
  31887. name = "data:" + name;
  31888. }
  31889. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  31890. };
  31891. /** nearest is mag = nearest and min = nearest and mip = linear */
  31892. Texture.NEAREST_SAMPLINGMODE = BABYLON.Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  31893. /** nearest is mag = nearest and min = nearest and mip = linear */
  31894. Texture.NEAREST_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR; // nearest is mag = nearest and min = nearest and mip = linear
  31895. /** Bilinear is mag = linear and min = linear and mip = nearest */
  31896. Texture.BILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_BILINEAR_SAMPLINGMODE;
  31897. /** Bilinear is mag = linear and min = linear and mip = nearest */
  31898. Texture.LINEAR_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST; // Bilinear is mag = linear and min = linear and mip = nearest
  31899. /** Trilinear is mag = linear and min = linear and mip = linear */
  31900. Texture.TRILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  31901. /** Trilinear is mag = linear and min = linear and mip = linear */
  31902. Texture.LINEAR_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR; // Trilinear is mag = linear and min = linear and mip = linear
  31903. /** mag = nearest and min = nearest and mip = nearest */
  31904. Texture.NEAREST_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST;
  31905. /** mag = nearest and min = linear and mip = nearest */
  31906. Texture.NEAREST_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST;
  31907. /** mag = nearest and min = linear and mip = linear */
  31908. Texture.NEAREST_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR;
  31909. /** mag = nearest and min = linear and mip = none */
  31910. Texture.NEAREST_LINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR;
  31911. /** mag = nearest and min = nearest and mip = none */
  31912. Texture.NEAREST_NEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST;
  31913. /** mag = linear and min = nearest and mip = nearest */
  31914. Texture.LINEAR_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST;
  31915. /** mag = linear and min = nearest and mip = linear */
  31916. Texture.LINEAR_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR;
  31917. /** mag = linear and min = linear and mip = none */
  31918. Texture.LINEAR_LINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR;
  31919. /** mag = linear and min = nearest and mip = none */
  31920. Texture.LINEAR_NEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST;
  31921. /** Explicit coordinates mode */
  31922. Texture.EXPLICIT_MODE = BABYLON.Engine.TEXTURE_EXPLICIT_MODE;
  31923. /** Spherical coordinates mode */
  31924. Texture.SPHERICAL_MODE = BABYLON.Engine.TEXTURE_SPHERICAL_MODE;
  31925. /** Planar coordinates mode */
  31926. Texture.PLANAR_MODE = BABYLON.Engine.TEXTURE_PLANAR_MODE;
  31927. /** Cubic coordinates mode */
  31928. Texture.CUBIC_MODE = BABYLON.Engine.TEXTURE_CUBIC_MODE;
  31929. /** Projection coordinates mode */
  31930. Texture.PROJECTION_MODE = BABYLON.Engine.TEXTURE_PROJECTION_MODE;
  31931. /** Inverse Cubic coordinates mode */
  31932. Texture.SKYBOX_MODE = BABYLON.Engine.TEXTURE_SKYBOX_MODE;
  31933. /** Inverse Cubic coordinates mode */
  31934. Texture.INVCUBIC_MODE = BABYLON.Engine.TEXTURE_INVCUBIC_MODE;
  31935. /** Equirectangular coordinates mode */
  31936. Texture.EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_EQUIRECTANGULAR_MODE;
  31937. /** Equirectangular Fixed coordinates mode */
  31938. Texture.FIXED_EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE;
  31939. /** Equirectangular Fixed Mirrored coordinates mode */
  31940. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE;
  31941. /** Texture is not repeating outside of 0..1 UVs */
  31942. Texture.CLAMP_ADDRESSMODE = BABYLON.Engine.TEXTURE_CLAMP_ADDRESSMODE;
  31943. /** Texture is repeating outside of 0..1 UVs */
  31944. Texture.WRAP_ADDRESSMODE = BABYLON.Engine.TEXTURE_WRAP_ADDRESSMODE;
  31945. /** Texture is repeating and mirrored */
  31946. Texture.MIRROR_ADDRESSMODE = BABYLON.Engine.TEXTURE_MIRROR_ADDRESSMODE;
  31947. /**
  31948. * 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
  31949. */
  31950. Texture.UseSerializedUrlIfAny = false;
  31951. __decorate([
  31952. BABYLON.serialize()
  31953. ], Texture.prototype, "url", void 0);
  31954. __decorate([
  31955. BABYLON.serialize()
  31956. ], Texture.prototype, "uOffset", void 0);
  31957. __decorate([
  31958. BABYLON.serialize()
  31959. ], Texture.prototype, "vOffset", void 0);
  31960. __decorate([
  31961. BABYLON.serialize()
  31962. ], Texture.prototype, "uScale", void 0);
  31963. __decorate([
  31964. BABYLON.serialize()
  31965. ], Texture.prototype, "vScale", void 0);
  31966. __decorate([
  31967. BABYLON.serialize()
  31968. ], Texture.prototype, "uAng", void 0);
  31969. __decorate([
  31970. BABYLON.serialize()
  31971. ], Texture.prototype, "vAng", void 0);
  31972. __decorate([
  31973. BABYLON.serialize()
  31974. ], Texture.prototype, "wAng", void 0);
  31975. __decorate([
  31976. BABYLON.serialize()
  31977. ], Texture.prototype, "uRotationCenter", void 0);
  31978. __decorate([
  31979. BABYLON.serialize()
  31980. ], Texture.prototype, "vRotationCenter", void 0);
  31981. __decorate([
  31982. BABYLON.serialize()
  31983. ], Texture.prototype, "wRotationCenter", void 0);
  31984. __decorate([
  31985. BABYLON.serialize()
  31986. ], Texture.prototype, "isBlocking", null);
  31987. return Texture;
  31988. }(BABYLON.BaseTexture));
  31989. BABYLON.Texture = Texture;
  31990. })(BABYLON || (BABYLON = {}));
  31991. //# sourceMappingURL=babylon.texture.js.map
  31992. var BABYLON;
  31993. (function (BABYLON) {
  31994. /**
  31995. * @hidden
  31996. **/
  31997. var _CreationDataStorage = /** @class */ (function () {
  31998. function _CreationDataStorage() {
  31999. }
  32000. return _CreationDataStorage;
  32001. }());
  32002. BABYLON._CreationDataStorage = _CreationDataStorage;
  32003. /**
  32004. * @hidden
  32005. **/
  32006. var _InstanceDataStorage = /** @class */ (function () {
  32007. function _InstanceDataStorage() {
  32008. this.visibleInstances = {};
  32009. this.renderIdForInstances = new Array();
  32010. this.batchCache = new _InstancesBatch();
  32011. this.instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  32012. }
  32013. return _InstanceDataStorage;
  32014. }());
  32015. /**
  32016. * @hidden
  32017. **/
  32018. var _InstancesBatch = /** @class */ (function () {
  32019. function _InstancesBatch() {
  32020. this.mustReturn = false;
  32021. this.visibleInstances = new Array();
  32022. this.renderSelf = new Array();
  32023. }
  32024. return _InstancesBatch;
  32025. }());
  32026. BABYLON._InstancesBatch = _InstancesBatch;
  32027. /**
  32028. * Class used to represent renderable models
  32029. */
  32030. var Mesh = /** @class */ (function (_super) {
  32031. __extends(Mesh, _super);
  32032. /**
  32033. * @constructor
  32034. * @param name The value used by scene.getMeshByName() to do a lookup.
  32035. * @param scene The scene to add this mesh to.
  32036. * @param parent The parent of this mesh, if it has one
  32037. * @param source An optional Mesh from which geometry is shared, cloned.
  32038. * @param doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  32039. * When false, achieved by calling a clone(), also passing False.
  32040. * This will make creation of children, recursive.
  32041. * @param clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  32042. */
  32043. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  32044. if (scene === void 0) { scene = null; }
  32045. if (parent === void 0) { parent = null; }
  32046. if (source === void 0) { source = null; }
  32047. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32048. var _this = _super.call(this, name, scene) || this;
  32049. // Members
  32050. /**
  32051. * Gets the delay loading state of the mesh (when delay loading is turned on)
  32052. * @see http://doc.babylonjs.com/how_to/using_the_incremental_loading_system
  32053. */
  32054. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  32055. /**
  32056. * Gets the list of instances created from this mesh
  32057. * @see http://doc.babylonjs.com/how_to/how_to_use_instances
  32058. */
  32059. _this.instances = new Array();
  32060. _this._LODLevels = new Array();
  32061. /** @hidden */
  32062. _this._instanceDataStorage = new _InstanceDataStorage();
  32063. // Use by builder only to know what orientation were the mesh build in.
  32064. /** @hidden */
  32065. _this._originalBuilderSideOrientation = Mesh.DEFAULTSIDE;
  32066. /**
  32067. * Use this property to change the original side orientation defined at construction time
  32068. */
  32069. _this.overrideMaterialSideOrientation = null;
  32070. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  32071. // Will be used to save a source mesh reference, If any
  32072. _this._source = null;
  32073. scene = _this.getScene();
  32074. if (source) {
  32075. // Geometry
  32076. if (source._geometry) {
  32077. source._geometry.applyToMesh(_this);
  32078. }
  32079. // Deep copy
  32080. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  32081. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen",
  32082. "onBeforeDrawObservable", "onBeforeRenderObservable", "onAfterRenderObservable", "onBeforeDraw"
  32083. ], ["_poseMatrix"]);
  32084. // Source mesh
  32085. _this._source = source;
  32086. // Construction Params
  32087. // Clone parameters allowing mesh to be updated in case of parametric shapes.
  32088. _this._originalBuilderSideOrientation = source._originalBuilderSideOrientation;
  32089. _this._creationDataStorage = source._creationDataStorage;
  32090. // Animation ranges
  32091. if (_this._source._ranges) {
  32092. var ranges = _this._source._ranges;
  32093. for (var name in ranges) {
  32094. if (!ranges.hasOwnProperty(name)) {
  32095. continue;
  32096. }
  32097. if (!ranges[name]) {
  32098. continue;
  32099. }
  32100. _this.createAnimationRange(name, ranges[name].from, ranges[name].to);
  32101. }
  32102. }
  32103. // Metadata
  32104. if (source.metadata && source.metadata.clone) {
  32105. _this.metadata = source.metadata.clone();
  32106. }
  32107. else {
  32108. _this.metadata = source.metadata;
  32109. }
  32110. // Tags
  32111. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  32112. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  32113. }
  32114. // Parent
  32115. _this.parent = source.parent;
  32116. // Pivot
  32117. _this.setPivotMatrix(source.getPivotMatrix());
  32118. _this.id = name + "." + source.id;
  32119. // Material
  32120. _this.material = source.material;
  32121. var index;
  32122. if (!doNotCloneChildren) {
  32123. // Children
  32124. var directDescendants = source.getDescendants(true);
  32125. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  32126. var child = directDescendants[index_1];
  32127. if (child.clone) {
  32128. child.clone(name + "." + child.name, _this);
  32129. }
  32130. }
  32131. }
  32132. // Physics clone
  32133. var physicsEngine = _this.getScene().getPhysicsEngine();
  32134. if (clonePhysicsImpostor && physicsEngine) {
  32135. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  32136. if (impostor) {
  32137. _this.physicsImpostor = impostor.clone(_this);
  32138. }
  32139. }
  32140. // Particles
  32141. for (index = 0; index < scene.particleSystems.length; index++) {
  32142. var system = scene.particleSystems[index];
  32143. if (system.emitter === source) {
  32144. system.clone(system.name, _this);
  32145. }
  32146. }
  32147. _this.refreshBoundingInfo();
  32148. _this.computeWorldMatrix(true);
  32149. }
  32150. // Parent
  32151. if (parent !== null) {
  32152. _this.parent = parent;
  32153. }
  32154. return _this;
  32155. }
  32156. Object.defineProperty(Mesh.prototype, "onBeforeRenderObservable", {
  32157. /**
  32158. * An event triggered before rendering the mesh
  32159. */
  32160. get: function () {
  32161. if (!this._onBeforeRenderObservable) {
  32162. this._onBeforeRenderObservable = new BABYLON.Observable();
  32163. }
  32164. return this._onBeforeRenderObservable;
  32165. },
  32166. enumerable: true,
  32167. configurable: true
  32168. });
  32169. Object.defineProperty(Mesh.prototype, "onAfterRenderObservable", {
  32170. /**
  32171. * An event triggered after rendering the mesh
  32172. */
  32173. get: function () {
  32174. if (!this._onAfterRenderObservable) {
  32175. this._onAfterRenderObservable = new BABYLON.Observable();
  32176. }
  32177. return this._onAfterRenderObservable;
  32178. },
  32179. enumerable: true,
  32180. configurable: true
  32181. });
  32182. Object.defineProperty(Mesh.prototype, "onBeforeDrawObservable", {
  32183. /**
  32184. * An event triggered before drawing the mesh
  32185. */
  32186. get: function () {
  32187. if (!this._onBeforeDrawObservable) {
  32188. this._onBeforeDrawObservable = new BABYLON.Observable();
  32189. }
  32190. return this._onBeforeDrawObservable;
  32191. },
  32192. enumerable: true,
  32193. configurable: true
  32194. });
  32195. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  32196. /**
  32197. * Sets a callback to call before drawing the mesh. It is recommended to use onBeforeDrawObservable instead
  32198. */
  32199. set: function (callback) {
  32200. if (this._onBeforeDrawObserver) {
  32201. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  32202. }
  32203. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  32204. },
  32205. enumerable: true,
  32206. configurable: true
  32207. });
  32208. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  32209. /**
  32210. * Gets or sets the morph target manager
  32211. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  32212. */
  32213. get: function () {
  32214. return this._morphTargetManager;
  32215. },
  32216. set: function (value) {
  32217. if (this._morphTargetManager === value) {
  32218. return;
  32219. }
  32220. this._morphTargetManager = value;
  32221. this._syncGeometryWithMorphTargetManager();
  32222. },
  32223. enumerable: true,
  32224. configurable: true
  32225. });
  32226. Object.defineProperty(Mesh.prototype, "source", {
  32227. /**
  32228. * Gets the source mesh (the one used to clone this one from)
  32229. */
  32230. get: function () {
  32231. return this._source;
  32232. },
  32233. enumerable: true,
  32234. configurable: true
  32235. });
  32236. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  32237. /**
  32238. * Gets or sets a boolean indicating that this mesh does not use index buffer
  32239. */
  32240. get: function () {
  32241. return this._unIndexed;
  32242. },
  32243. set: function (value) {
  32244. if (this._unIndexed !== value) {
  32245. this._unIndexed = value;
  32246. this._markSubMeshesAsAttributesDirty();
  32247. }
  32248. },
  32249. enumerable: true,
  32250. configurable: true
  32251. });
  32252. // Methods
  32253. /**
  32254. * Gets the class name
  32255. * @returns the string "Mesh".
  32256. */
  32257. Mesh.prototype.getClassName = function () {
  32258. return "Mesh";
  32259. };
  32260. /**
  32261. * Returns a description of this mesh
  32262. * @param fullDetails define if full details about this mesh must be used
  32263. * @returns a descriptive string representing this mesh
  32264. */
  32265. Mesh.prototype.toString = function (fullDetails) {
  32266. var ret = _super.prototype.toString.call(this, fullDetails);
  32267. ret += ", n vertices: " + this.getTotalVertices();
  32268. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  32269. if (this.animations) {
  32270. for (var i = 0; i < this.animations.length; i++) {
  32271. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  32272. }
  32273. }
  32274. if (fullDetails) {
  32275. if (this._geometry) {
  32276. var ib = this.getIndices();
  32277. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32278. if (vb && ib) {
  32279. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  32280. }
  32281. }
  32282. else {
  32283. ret += ", flat shading: UNKNOWN";
  32284. }
  32285. }
  32286. return ret;
  32287. };
  32288. /** @hidden */
  32289. Mesh.prototype._unBindEffect = function () {
  32290. _super.prototype._unBindEffect.call(this);
  32291. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  32292. var instance = _a[_i];
  32293. instance._unBindEffect();
  32294. }
  32295. };
  32296. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  32297. /**
  32298. * Gets a boolean indicating if this mesh has LOD
  32299. */
  32300. get: function () {
  32301. return this._LODLevels.length > 0;
  32302. },
  32303. enumerable: true,
  32304. configurable: true
  32305. });
  32306. /**
  32307. * Gets the list of MeshLODLevel associated with the current mesh
  32308. * @returns an array of MeshLODLevel
  32309. */
  32310. Mesh.prototype.getLODLevels = function () {
  32311. return this._LODLevels;
  32312. };
  32313. Mesh.prototype._sortLODLevels = function () {
  32314. this._LODLevels.sort(function (a, b) {
  32315. if (a.distance < b.distance) {
  32316. return 1;
  32317. }
  32318. if (a.distance > b.distance) {
  32319. return -1;
  32320. }
  32321. return 0;
  32322. });
  32323. };
  32324. /**
  32325. * Add a mesh as LOD level triggered at the given distance.
  32326. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  32327. * @param distance The distance from the center of the object to show this level
  32328. * @param mesh The mesh to be added as LOD level (can be null)
  32329. * @return This mesh (for chaining)
  32330. */
  32331. Mesh.prototype.addLODLevel = function (distance, mesh) {
  32332. if (mesh && mesh._masterMesh) {
  32333. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  32334. return this;
  32335. }
  32336. var level = new BABYLON.MeshLODLevel(distance, mesh);
  32337. this._LODLevels.push(level);
  32338. if (mesh) {
  32339. mesh._masterMesh = this;
  32340. }
  32341. this._sortLODLevels();
  32342. return this;
  32343. };
  32344. /**
  32345. * Returns the LOD level mesh at the passed distance or null if not found.
  32346. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  32347. * @param distance The distance from the center of the object to show this level
  32348. * @returns a Mesh or `null`
  32349. */
  32350. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  32351. for (var index = 0; index < this._LODLevels.length; index++) {
  32352. var level = this._LODLevels[index];
  32353. if (level.distance === distance) {
  32354. return level.mesh;
  32355. }
  32356. }
  32357. return null;
  32358. };
  32359. /**
  32360. * Remove a mesh from the LOD array
  32361. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  32362. * @param mesh defines the mesh to be removed
  32363. * @return This mesh (for chaining)
  32364. */
  32365. Mesh.prototype.removeLODLevel = function (mesh) {
  32366. for (var index = 0; index < this._LODLevels.length; index++) {
  32367. if (this._LODLevels[index].mesh === mesh) {
  32368. this._LODLevels.splice(index, 1);
  32369. if (mesh) {
  32370. mesh._masterMesh = null;
  32371. }
  32372. }
  32373. }
  32374. this._sortLODLevels();
  32375. return this;
  32376. };
  32377. /**
  32378. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  32379. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  32380. * @param camera defines the camera to use to compute distance
  32381. * @param boundingSphere defines a custom bounding sphere to use instead of the one from this mesh
  32382. * @return This mesh (for chaining)
  32383. */
  32384. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  32385. if (!this._LODLevels || this._LODLevels.length === 0) {
  32386. return this;
  32387. }
  32388. var bSphere;
  32389. if (boundingSphere) {
  32390. bSphere = boundingSphere;
  32391. }
  32392. else {
  32393. var boundingInfo = this.getBoundingInfo();
  32394. bSphere = boundingInfo.boundingSphere;
  32395. }
  32396. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  32397. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  32398. if (this.onLODLevelSelection) {
  32399. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  32400. }
  32401. return this;
  32402. }
  32403. for (var index = 0; index < this._LODLevels.length; index++) {
  32404. var level = this._LODLevels[index];
  32405. if (level.distance < distanceToCamera) {
  32406. if (level.mesh) {
  32407. level.mesh._preActivate();
  32408. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  32409. }
  32410. if (this.onLODLevelSelection) {
  32411. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  32412. }
  32413. return level.mesh;
  32414. }
  32415. }
  32416. if (this.onLODLevelSelection) {
  32417. this.onLODLevelSelection(distanceToCamera, this, this);
  32418. }
  32419. return this;
  32420. };
  32421. Object.defineProperty(Mesh.prototype, "geometry", {
  32422. /**
  32423. * Gets the mesh internal Geometry object
  32424. */
  32425. get: function () {
  32426. return this._geometry;
  32427. },
  32428. enumerable: true,
  32429. configurable: true
  32430. });
  32431. /**
  32432. * Returns the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  32433. * @returns the total number of vertices
  32434. */
  32435. Mesh.prototype.getTotalVertices = function () {
  32436. if (this._geometry === null || this._geometry === undefined) {
  32437. return 0;
  32438. }
  32439. return this._geometry.getTotalVertices();
  32440. };
  32441. /**
  32442. * Returns the content of an associated vertex buffer
  32443. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  32444. * - BABYLON.VertexBuffer.PositionKind
  32445. * - BABYLON.VertexBuffer.UVKind
  32446. * - BABYLON.VertexBuffer.UV2Kind
  32447. * - BABYLON.VertexBuffer.UV3Kind
  32448. * - BABYLON.VertexBuffer.UV4Kind
  32449. * - BABYLON.VertexBuffer.UV5Kind
  32450. * - BABYLON.VertexBuffer.UV6Kind
  32451. * - BABYLON.VertexBuffer.ColorKind
  32452. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32453. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32454. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32455. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32456. * @param copyWhenShared defines a boolean indicating that if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one
  32457. * @param forceCopy defines a boolean forcing the copy of the buffer no matter what the value of copyWhenShared is
  32458. * @returns a FloatArray or null if the mesh has no geometry or no vertex buffer for this kind.
  32459. */
  32460. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  32461. if (!this._geometry) {
  32462. return null;
  32463. }
  32464. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  32465. };
  32466. /**
  32467. * Returns the mesh VertexBuffer object from the requested `kind`
  32468. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  32469. * - BABYLON.VertexBuffer.PositionKind
  32470. * - BABYLON.VertexBuffer.UVKind
  32471. * - BABYLON.VertexBuffer.UV2Kind
  32472. * - BABYLON.VertexBuffer.UV3Kind
  32473. * - BABYLON.VertexBuffer.UV4Kind
  32474. * - BABYLON.VertexBuffer.UV5Kind
  32475. * - BABYLON.VertexBuffer.UV6Kind
  32476. * - BABYLON.VertexBuffer.ColorKind
  32477. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32478. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32479. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32480. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32481. * @returns a FloatArray or null if the mesh has no vertex buffer for this kind.
  32482. */
  32483. Mesh.prototype.getVertexBuffer = function (kind) {
  32484. if (!this._geometry) {
  32485. return null;
  32486. }
  32487. return this._geometry.getVertexBuffer(kind);
  32488. };
  32489. /**
  32490. * Tests if a specific vertex buffer is associated with this mesh
  32491. * @param kind defines which buffer to check (positions, indices, normals, etc). Possible `kind` values :
  32492. * - BABYLON.VertexBuffer.PositionKind
  32493. * - BABYLON.VertexBuffer.UVKind
  32494. * - BABYLON.VertexBuffer.UV2Kind
  32495. * - BABYLON.VertexBuffer.UV3Kind
  32496. * - BABYLON.VertexBuffer.UV4Kind
  32497. * - BABYLON.VertexBuffer.UV5Kind
  32498. * - BABYLON.VertexBuffer.UV6Kind
  32499. * - BABYLON.VertexBuffer.ColorKind
  32500. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32501. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32502. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32503. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32504. * @returns a boolean
  32505. */
  32506. Mesh.prototype.isVerticesDataPresent = function (kind) {
  32507. if (!this._geometry) {
  32508. if (this._delayInfo) {
  32509. return this._delayInfo.indexOf(kind) !== -1;
  32510. }
  32511. return false;
  32512. }
  32513. return this._geometry.isVerticesDataPresent(kind);
  32514. };
  32515. /**
  32516. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  32517. * @param kind defines which buffer to check (positions, indices, normals, etc). Possible `kind` values :
  32518. * - BABYLON.VertexBuffer.PositionKind
  32519. * - BABYLON.VertexBuffer.UVKind
  32520. * - BABYLON.VertexBuffer.UV2Kind
  32521. * - BABYLON.VertexBuffer.UV3Kind
  32522. * - BABYLON.VertexBuffer.UV4Kind
  32523. * - BABYLON.VertexBuffer.UV5Kind
  32524. * - BABYLON.VertexBuffer.UV6Kind
  32525. * - BABYLON.VertexBuffer.ColorKind
  32526. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32527. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32528. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32529. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32530. * @returns a boolean
  32531. */
  32532. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  32533. if (!this._geometry) {
  32534. if (this._delayInfo) {
  32535. return this._delayInfo.indexOf(kind) !== -1;
  32536. }
  32537. return false;
  32538. }
  32539. return this._geometry.isVertexBufferUpdatable(kind);
  32540. };
  32541. /**
  32542. * Returns a string which contains the list of existing `kinds` of Vertex Data associated with this mesh.
  32543. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  32544. * - BABYLON.VertexBuffer.PositionKind
  32545. * - BABYLON.VertexBuffer.UVKind
  32546. * - BABYLON.VertexBuffer.UV2Kind
  32547. * - BABYLON.VertexBuffer.UV3Kind
  32548. * - BABYLON.VertexBuffer.UV4Kind
  32549. * - BABYLON.VertexBuffer.UV5Kind
  32550. * - BABYLON.VertexBuffer.UV6Kind
  32551. * - BABYLON.VertexBuffer.ColorKind
  32552. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32553. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32554. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32555. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32556. * @returns an array of strings
  32557. */
  32558. Mesh.prototype.getVerticesDataKinds = function () {
  32559. if (!this._geometry) {
  32560. var result = new Array();
  32561. if (this._delayInfo) {
  32562. this._delayInfo.forEach(function (kind, index, array) {
  32563. result.push(kind);
  32564. });
  32565. }
  32566. return result;
  32567. }
  32568. return this._geometry.getVerticesDataKinds();
  32569. };
  32570. /**
  32571. * Returns a positive integer : the total number of indices in this mesh geometry.
  32572. * @returns the numner of indices or zero if the mesh has no geometry.
  32573. */
  32574. Mesh.prototype.getTotalIndices = function () {
  32575. if (!this._geometry) {
  32576. return 0;
  32577. }
  32578. return this._geometry.getTotalIndices();
  32579. };
  32580. /**
  32581. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  32582. * @param copyWhenShared If true (default false) and and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.
  32583. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  32584. * @returns the indices array or an empty array if the mesh has no geometry
  32585. */
  32586. Mesh.prototype.getIndices = function (copyWhenShared, forceCopy) {
  32587. if (!this._geometry) {
  32588. return [];
  32589. }
  32590. return this._geometry.getIndices(copyWhenShared, forceCopy);
  32591. };
  32592. Object.defineProperty(Mesh.prototype, "isBlocked", {
  32593. get: function () {
  32594. return this._masterMesh !== null && this._masterMesh !== undefined;
  32595. },
  32596. enumerable: true,
  32597. configurable: true
  32598. });
  32599. /**
  32600. * Determine if the current mesh is ready to be rendered
  32601. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  32602. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  32603. * @returns true if all associated assets are ready (material, textures, shaders)
  32604. */
  32605. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  32606. if (completeCheck === void 0) { completeCheck = false; }
  32607. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  32608. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32609. return false;
  32610. }
  32611. if (!_super.prototype.isReady.call(this, completeCheck)) {
  32612. return false;
  32613. }
  32614. if (!this.subMeshes || this.subMeshes.length === 0) {
  32615. return true;
  32616. }
  32617. if (!completeCheck) {
  32618. return true;
  32619. }
  32620. var engine = this.getEngine();
  32621. var scene = this.getScene();
  32622. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  32623. this.computeWorldMatrix();
  32624. var mat = this.material || scene.defaultMaterial;
  32625. if (mat) {
  32626. if (mat.storeEffectOnSubMeshes) {
  32627. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  32628. var subMesh = _a[_i];
  32629. var effectiveMaterial = subMesh.getMaterial();
  32630. if (effectiveMaterial) {
  32631. if (effectiveMaterial.storeEffectOnSubMeshes) {
  32632. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32633. return false;
  32634. }
  32635. }
  32636. else {
  32637. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32638. return false;
  32639. }
  32640. }
  32641. }
  32642. }
  32643. }
  32644. else {
  32645. if (!mat.isReady(this, hardwareInstancedRendering)) {
  32646. return false;
  32647. }
  32648. }
  32649. }
  32650. // Shadows
  32651. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  32652. var light = _c[_b];
  32653. var generator = light.getShadowGenerator();
  32654. if (generator) {
  32655. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  32656. var subMesh = _e[_d];
  32657. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  32658. return false;
  32659. }
  32660. }
  32661. }
  32662. }
  32663. // LOD
  32664. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  32665. var lod = _g[_f];
  32666. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  32667. return false;
  32668. }
  32669. }
  32670. return true;
  32671. };
  32672. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  32673. /**
  32674. * Gets a boolean indicating if the normals aren't to be recomputed on next mesh `positions` array update. This property is pertinent only for updatable parametric shapes.
  32675. */
  32676. get: function () {
  32677. return this._areNormalsFrozen;
  32678. },
  32679. enumerable: true,
  32680. configurable: true
  32681. });
  32682. /**
  32683. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc. It has no effect at all on other shapes. It prevents the mesh normals from being recomputed on next `positions` array update.
  32684. * @returns the current mesh
  32685. */
  32686. Mesh.prototype.freezeNormals = function () {
  32687. this._areNormalsFrozen = true;
  32688. return this;
  32689. };
  32690. /**
  32691. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc. It has no effect at all on other shapes. It reactivates the mesh normals computation if it was previously frozen
  32692. * @returns the current mesh
  32693. */
  32694. Mesh.prototype.unfreezeNormals = function () {
  32695. this._areNormalsFrozen = false;
  32696. return this;
  32697. };
  32698. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  32699. /**
  32700. * Sets a value overriding the instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  32701. */
  32702. set: function (count) {
  32703. this._instanceDataStorage.overridenInstanceCount = count;
  32704. },
  32705. enumerable: true,
  32706. configurable: true
  32707. });
  32708. // Methods
  32709. /** @hidden */
  32710. Mesh.prototype._preActivate = function () {
  32711. var sceneRenderId = this.getScene().getRenderId();
  32712. if (this._preActivateId === sceneRenderId) {
  32713. return this;
  32714. }
  32715. this._preActivateId = sceneRenderId;
  32716. this._instanceDataStorage.visibleInstances = null;
  32717. return this;
  32718. };
  32719. /** @hidden */
  32720. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  32721. if (this._instanceDataStorage.visibleInstances) {
  32722. this._instanceDataStorage.visibleInstances.intermediateDefaultRenderId = renderId;
  32723. }
  32724. return this;
  32725. };
  32726. /** @hidden */
  32727. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  32728. if (!this._instanceDataStorage.visibleInstances) {
  32729. this._instanceDataStorage.visibleInstances = {};
  32730. this._instanceDataStorage.visibleInstances.defaultRenderId = renderId;
  32731. this._instanceDataStorage.visibleInstances.selfDefaultRenderId = this._renderId;
  32732. }
  32733. if (!this._instanceDataStorage.visibleInstances[renderId]) {
  32734. this._instanceDataStorage.visibleInstances[renderId] = new Array();
  32735. }
  32736. this._instanceDataStorage.visibleInstances[renderId].push(instance);
  32737. return this;
  32738. };
  32739. /**
  32740. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  32741. * This means the mesh underlying bounding box and sphere are recomputed.
  32742. * @returns the current mesh
  32743. */
  32744. Mesh.prototype.refreshBoundingInfo = function () {
  32745. return this._refreshBoundingInfo(false);
  32746. };
  32747. /** @hidden */
  32748. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  32749. if (this._boundingInfo && this._boundingInfo.isLocked) {
  32750. return this;
  32751. }
  32752. var data = this._getPositionData(applySkeleton);
  32753. if (data) {
  32754. var bias = this.geometry ? this.geometry.boundingBias : null;
  32755. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices(), bias);
  32756. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  32757. }
  32758. if (this.subMeshes) {
  32759. for (var index = 0; index < this.subMeshes.length; index++) {
  32760. this.subMeshes[index].refreshBoundingInfo();
  32761. }
  32762. }
  32763. this._updateBoundingInfo();
  32764. return this;
  32765. };
  32766. Mesh.prototype._getPositionData = function (applySkeleton) {
  32767. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32768. if (data && applySkeleton && this.skeleton) {
  32769. data = BABYLON.Tools.Slice(data);
  32770. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32771. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32772. if (matricesWeightsData && matricesIndicesData) {
  32773. var needExtras = this.numBoneInfluencers > 4;
  32774. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  32775. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  32776. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  32777. var tempVector = BABYLON.Tmp.Vector3[0];
  32778. var finalMatrix = BABYLON.Tmp.Matrix[0];
  32779. var tempMatrix = BABYLON.Tmp.Matrix[1];
  32780. var matWeightIdx = 0;
  32781. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  32782. finalMatrix.reset();
  32783. var inf;
  32784. var weight;
  32785. for (inf = 0; inf < 4; inf++) {
  32786. weight = matricesWeightsData[matWeightIdx + inf];
  32787. if (weight > 0) {
  32788. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32789. finalMatrix.addToSelf(tempMatrix);
  32790. }
  32791. }
  32792. if (needExtras) {
  32793. for (inf = 0; inf < 4; inf++) {
  32794. weight = matricesWeightsExtraData[matWeightIdx + inf];
  32795. if (weight > 0) {
  32796. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32797. finalMatrix.addToSelf(tempMatrix);
  32798. }
  32799. }
  32800. }
  32801. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  32802. tempVector.toArray(data, index);
  32803. }
  32804. }
  32805. }
  32806. return data;
  32807. };
  32808. /** @hidden */
  32809. Mesh.prototype._createGlobalSubMesh = function (force) {
  32810. var totalVertices = this.getTotalVertices();
  32811. if (!totalVertices || !this.getIndices()) {
  32812. return null;
  32813. }
  32814. // Check if we need to recreate the submeshes
  32815. if (this.subMeshes && this.subMeshes.length > 0) {
  32816. var ib = this.getIndices();
  32817. if (!ib) {
  32818. return null;
  32819. }
  32820. var totalIndices = ib.length;
  32821. var needToRecreate = false;
  32822. if (force) {
  32823. needToRecreate = true;
  32824. }
  32825. else {
  32826. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  32827. var submesh = _a[_i];
  32828. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  32829. needToRecreate = true;
  32830. break;
  32831. }
  32832. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  32833. needToRecreate = true;
  32834. break;
  32835. }
  32836. }
  32837. }
  32838. if (!needToRecreate) {
  32839. return this.subMeshes[0];
  32840. }
  32841. }
  32842. this.releaseSubMeshes();
  32843. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  32844. };
  32845. /**
  32846. * This function will subdivide the mesh into multiple submeshes
  32847. * @param count defines the expected number of submeshes
  32848. */
  32849. Mesh.prototype.subdivide = function (count) {
  32850. if (count < 1) {
  32851. return;
  32852. }
  32853. var totalIndices = this.getTotalIndices();
  32854. var subdivisionSize = (totalIndices / count) | 0;
  32855. var offset = 0;
  32856. // Ensure that subdivisionSize is a multiple of 3
  32857. while (subdivisionSize % 3 !== 0) {
  32858. subdivisionSize++;
  32859. }
  32860. this.releaseSubMeshes();
  32861. for (var index = 0; index < count; index++) {
  32862. if (offset >= totalIndices) {
  32863. break;
  32864. }
  32865. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  32866. offset += subdivisionSize;
  32867. }
  32868. this.synchronizeInstances();
  32869. };
  32870. /**
  32871. * Copy a FloatArray into a specific associated vertex buffer
  32872. * @param kind defines which buffer to write to (positions, indices, normals, etc). Possible `kind` values :
  32873. * - BABYLON.VertexBuffer.PositionKind
  32874. * - BABYLON.VertexBuffer.UVKind
  32875. * - BABYLON.VertexBuffer.UV2Kind
  32876. * - BABYLON.VertexBuffer.UV3Kind
  32877. * - BABYLON.VertexBuffer.UV4Kind
  32878. * - BABYLON.VertexBuffer.UV5Kind
  32879. * - BABYLON.VertexBuffer.UV6Kind
  32880. * - BABYLON.VertexBuffer.ColorKind
  32881. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32882. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32883. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32884. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32885. * @param data defines the data source
  32886. * @param updatable defines if the updated vertex buffer must be flagged as updatable
  32887. * @param stride defines the data stride size (can be null)
  32888. * @returns the current mesh
  32889. */
  32890. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  32891. if (updatable === void 0) { updatable = false; }
  32892. if (!this._geometry) {
  32893. var vertexData = new BABYLON.VertexData();
  32894. vertexData.set(data, kind);
  32895. var scene = this.getScene();
  32896. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32897. }
  32898. else {
  32899. this._geometry.setVerticesData(kind, data, updatable, stride);
  32900. }
  32901. return this;
  32902. };
  32903. /**
  32904. * Flags an associated vertex buffer as updatable
  32905. * @param kind defines which buffer to use (positions, indices, normals, etc). Possible `kind` values :
  32906. * - BABYLON.VertexBuffer.PositionKind
  32907. * - BABYLON.VertexBuffer.UVKind
  32908. * - BABYLON.VertexBuffer.UV2Kind
  32909. * - BABYLON.VertexBuffer.UV3Kind
  32910. * - BABYLON.VertexBuffer.UV4Kind
  32911. * - BABYLON.VertexBuffer.UV5Kind
  32912. * - BABYLON.VertexBuffer.UV6Kind
  32913. * - BABYLON.VertexBuffer.ColorKind
  32914. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32915. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32916. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32917. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32918. * @param updatable defines if the updated vertex buffer must be flagged as updatable
  32919. */
  32920. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  32921. if (updatable === void 0) { updatable = true; }
  32922. var vb = this.getVertexBuffer(kind);
  32923. if (!vb || vb.isUpdatable() === updatable) {
  32924. return;
  32925. }
  32926. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  32927. };
  32928. /**
  32929. * Sets the mesh global Vertex Buffer
  32930. * @param buffer defines the buffer to use
  32931. * @returns the current mesh
  32932. */
  32933. Mesh.prototype.setVerticesBuffer = function (buffer) {
  32934. if (!this._geometry) {
  32935. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  32936. }
  32937. this._geometry.setVerticesBuffer(buffer);
  32938. return this;
  32939. };
  32940. /**
  32941. * Update a specific associated vertex buffer
  32942. * @param kind defines which buffer to write to (positions, indices, normals, etc). Possible `kind` values :
  32943. * - BABYLON.VertexBuffer.PositionKind
  32944. * - BABYLON.VertexBuffer.UVKind
  32945. * - BABYLON.VertexBuffer.UV2Kind
  32946. * - BABYLON.VertexBuffer.UV3Kind
  32947. * - BABYLON.VertexBuffer.UV4Kind
  32948. * - BABYLON.VertexBuffer.UV5Kind
  32949. * - BABYLON.VertexBuffer.UV6Kind
  32950. * - BABYLON.VertexBuffer.ColorKind
  32951. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32952. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32953. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32954. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32955. * @param data defines the data source
  32956. * @param updateExtends defines if extends info of the mesh must be updated (can be null). This is mostly useful for "position" kind
  32957. * @param makeItUnique defines if the geometry associated with the mesh must be cloned to make the change only for this mesh (and not all meshes associated with the same geometry)
  32958. * @returns the current mesh
  32959. */
  32960. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  32961. if (!this._geometry) {
  32962. return this;
  32963. }
  32964. if (!makeItUnique) {
  32965. this._geometry.updateVerticesData(kind, data, updateExtends);
  32966. }
  32967. else {
  32968. this.makeGeometryUnique();
  32969. this.updateVerticesData(kind, data, updateExtends, false);
  32970. }
  32971. return this;
  32972. };
  32973. /**
  32974. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  32975. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  32976. * @param positionFunction is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything
  32977. * @param computeNormals is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update
  32978. * @returns the current mesh
  32979. */
  32980. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  32981. if (computeNormals === void 0) { computeNormals = true; }
  32982. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32983. if (!positions) {
  32984. return this;
  32985. }
  32986. positionFunction(positions);
  32987. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  32988. if (computeNormals) {
  32989. var indices = this.getIndices();
  32990. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32991. if (!normals) {
  32992. return this;
  32993. }
  32994. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  32995. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  32996. }
  32997. return this;
  32998. };
  32999. /**
  33000. * Creates a un-shared specific occurence of the geometry for the mesh.
  33001. * @returns the current mesh
  33002. */
  33003. Mesh.prototype.makeGeometryUnique = function () {
  33004. if (!this._geometry) {
  33005. return this;
  33006. }
  33007. var oldGeometry = this._geometry;
  33008. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  33009. oldGeometry.releaseForMesh(this, true);
  33010. geometry.applyToMesh(this);
  33011. return this;
  33012. };
  33013. /**
  33014. * Set the index buffer of this mesh
  33015. * @param indices defines the source data
  33016. * @param totalVertices defines the total number of vertices referenced by this index data (can be null)
  33017. * @param updatable defines if the updated index buffer must be flagged as updatable (default is false)
  33018. * @returns the current mesh
  33019. */
  33020. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  33021. if (totalVertices === void 0) { totalVertices = null; }
  33022. if (updatable === void 0) { updatable = false; }
  33023. if (!this._geometry) {
  33024. var vertexData = new BABYLON.VertexData();
  33025. vertexData.indices = indices;
  33026. var scene = this.getScene();
  33027. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  33028. }
  33029. else {
  33030. this._geometry.setIndices(indices, totalVertices, updatable);
  33031. }
  33032. return this;
  33033. };
  33034. /**
  33035. * Update the current index buffer
  33036. * @param indices defines the source data
  33037. * @param offset defines the offset in the index buffer where to store the new data (can be null)
  33038. * @returns the current mesh
  33039. */
  33040. Mesh.prototype.updateIndices = function (indices, offset) {
  33041. if (!this._geometry) {
  33042. return this;
  33043. }
  33044. this._geometry.updateIndices(indices, offset);
  33045. return this;
  33046. };
  33047. /**
  33048. * Invert the geometry to move from a right handed system to a left handed one.
  33049. * @returns the current mesh
  33050. */
  33051. Mesh.prototype.toLeftHanded = function () {
  33052. if (!this._geometry) {
  33053. return this;
  33054. }
  33055. this._geometry.toLeftHanded();
  33056. return this;
  33057. };
  33058. /** @hidden */
  33059. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  33060. if (!this._geometry) {
  33061. return this;
  33062. }
  33063. var engine = this.getScene().getEngine();
  33064. // Wireframe
  33065. var indexToBind;
  33066. if (this._unIndexed) {
  33067. indexToBind = null;
  33068. }
  33069. else {
  33070. switch (fillMode) {
  33071. case BABYLON.Material.PointFillMode:
  33072. indexToBind = null;
  33073. break;
  33074. case BABYLON.Material.WireFrameFillMode:
  33075. indexToBind = subMesh._getLinesIndexBuffer(this.getIndices(), engine);
  33076. break;
  33077. default:
  33078. case BABYLON.Material.TriangleFillMode:
  33079. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  33080. break;
  33081. }
  33082. }
  33083. // VBOs
  33084. this._geometry._bind(effect, indexToBind);
  33085. return this;
  33086. };
  33087. /** @hidden */
  33088. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  33089. if (alternate === void 0) { alternate = false; }
  33090. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  33091. return this;
  33092. }
  33093. if (this._onBeforeDrawObservable) {
  33094. this._onBeforeDrawObservable.notifyObservers(this);
  33095. }
  33096. var scene = this.getScene();
  33097. var engine = scene.getEngine();
  33098. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  33099. // or triangles as points
  33100. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  33101. }
  33102. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  33103. // Triangles as wireframe
  33104. engine.drawElementsType(fillMode, 0, subMesh._linesIndexCount, instancesCount);
  33105. }
  33106. else {
  33107. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  33108. }
  33109. if (scene._isAlternateRenderingEnabled && !alternate) {
  33110. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  33111. if (!effect || !scene.activeCamera) {
  33112. return this;
  33113. }
  33114. scene._switchToAlternateCameraConfiguration(true);
  33115. this._effectiveMaterial.bindView(effect);
  33116. this._effectiveMaterial.bindViewProjection(effect);
  33117. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  33118. this._draw(subMesh, fillMode, instancesCount, true);
  33119. engine.setViewport(scene.activeCamera.viewport);
  33120. scene._switchToAlternateCameraConfiguration(false);
  33121. this._effectiveMaterial.bindView(effect);
  33122. this._effectiveMaterial.bindViewProjection(effect);
  33123. }
  33124. return this;
  33125. };
  33126. /**
  33127. * Registers for this mesh a javascript function called just before the rendering process
  33128. * @param func defines the function to call before rendering this mesh
  33129. * @returns the current mesh
  33130. */
  33131. Mesh.prototype.registerBeforeRender = function (func) {
  33132. this.onBeforeRenderObservable.add(func);
  33133. return this;
  33134. };
  33135. /**
  33136. * Disposes a previously registered javascript function called before the rendering
  33137. * @param func defines the function to remove
  33138. * @returns the current mesh
  33139. */
  33140. Mesh.prototype.unregisterBeforeRender = function (func) {
  33141. this.onBeforeRenderObservable.removeCallback(func);
  33142. return this;
  33143. };
  33144. /**
  33145. * Registers for this mesh a javascript function called just after the rendering is complete
  33146. * @param func defines the function to call after rendering this mesh
  33147. * @returns the current mesh
  33148. */
  33149. Mesh.prototype.registerAfterRender = function (func) {
  33150. this.onAfterRenderObservable.add(func);
  33151. return this;
  33152. };
  33153. /**
  33154. * Disposes a previously registered javascript function called after the rendering.
  33155. * @param func defines the function to remove
  33156. * @returns the current mesh
  33157. */
  33158. Mesh.prototype.unregisterAfterRender = function (func) {
  33159. this.onAfterRenderObservable.removeCallback(func);
  33160. return this;
  33161. };
  33162. /** @hidden */
  33163. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  33164. var scene = this.getScene();
  33165. var batchCache = this._instanceDataStorage.batchCache;
  33166. batchCache.mustReturn = false;
  33167. batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  33168. batchCache.visibleInstances[subMeshId] = null;
  33169. if (this._instanceDataStorage.visibleInstances) {
  33170. var visibleInstances = this._instanceDataStorage.visibleInstances;
  33171. var currentRenderId = scene.getRenderId();
  33172. var defaultRenderId = (scene._isInIntermediateRendering() ? visibleInstances.intermediateDefaultRenderId : visibleInstances.defaultRenderId);
  33173. batchCache.visibleInstances[subMeshId] = visibleInstances[currentRenderId];
  33174. var selfRenderId = this._renderId;
  33175. if (!batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  33176. batchCache.visibleInstances[subMeshId] = visibleInstances[defaultRenderId];
  33177. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  33178. selfRenderId = Math.max(visibleInstances.selfDefaultRenderId, currentRenderId);
  33179. }
  33180. var visibleInstancesForSubMesh = batchCache.visibleInstances[subMeshId];
  33181. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  33182. if (this._instanceDataStorage.renderIdForInstances[subMeshId] === currentRenderId) {
  33183. batchCache.mustReturn = true;
  33184. return batchCache;
  33185. }
  33186. if (currentRenderId !== selfRenderId) {
  33187. batchCache.renderSelf[subMeshId] = false;
  33188. }
  33189. }
  33190. this._instanceDataStorage.renderIdForInstances[subMeshId] = currentRenderId;
  33191. }
  33192. return batchCache;
  33193. };
  33194. /** @hidden */
  33195. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  33196. var visibleInstances = batch.visibleInstances[subMesh._id];
  33197. if (!visibleInstances) {
  33198. return this;
  33199. }
  33200. var matricesCount = visibleInstances.length + 1;
  33201. var bufferSize = matricesCount * 16 * 4;
  33202. var instanceStorage = this._instanceDataStorage;
  33203. var currentInstancesBufferSize = instanceStorage.instancesBufferSize;
  33204. var instancesBuffer = instanceStorage.instancesBuffer;
  33205. while (instanceStorage.instancesBufferSize < bufferSize) {
  33206. instanceStorage.instancesBufferSize *= 2;
  33207. }
  33208. if (!instanceStorage.instancesData || currentInstancesBufferSize != instanceStorage.instancesBufferSize) {
  33209. instanceStorage.instancesData = new Float32Array(instanceStorage.instancesBufferSize / 4);
  33210. }
  33211. var offset = 0;
  33212. var instancesCount = 0;
  33213. var world = this.getWorldMatrix();
  33214. if (batch.renderSelf[subMesh._id]) {
  33215. world.copyToArray(instanceStorage.instancesData, offset);
  33216. offset += 16;
  33217. instancesCount++;
  33218. }
  33219. if (visibleInstances) {
  33220. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  33221. var instance = visibleInstances[instanceIndex];
  33222. instance.getWorldMatrix().copyToArray(instanceStorage.instancesData, offset);
  33223. offset += 16;
  33224. instancesCount++;
  33225. }
  33226. }
  33227. if (!instancesBuffer || currentInstancesBufferSize != instanceStorage.instancesBufferSize) {
  33228. if (instancesBuffer) {
  33229. instancesBuffer.dispose();
  33230. }
  33231. instancesBuffer = new BABYLON.Buffer(engine, instanceStorage.instancesData, true, 16, false, true);
  33232. instanceStorage.instancesBuffer = instancesBuffer;
  33233. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  33234. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  33235. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  33236. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  33237. }
  33238. else {
  33239. instancesBuffer.updateDirectly(instanceStorage.instancesData, 0, instancesCount);
  33240. }
  33241. this._bind(subMesh, effect, fillMode);
  33242. this._draw(subMesh, fillMode, instancesCount);
  33243. engine.unbindInstanceAttributes();
  33244. return this;
  33245. };
  33246. /** @hidden */
  33247. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  33248. var scene = this.getScene();
  33249. var engine = scene.getEngine();
  33250. if (hardwareInstancedRendering) {
  33251. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  33252. }
  33253. else {
  33254. if (batch.renderSelf[subMesh._id]) {
  33255. // Draw
  33256. if (onBeforeDraw) {
  33257. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  33258. }
  33259. this._draw(subMesh, fillMode, this._instanceDataStorage.overridenInstanceCount);
  33260. }
  33261. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  33262. if (visibleInstancesForSubMesh) {
  33263. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  33264. var instance = visibleInstancesForSubMesh[instanceIndex];
  33265. // World
  33266. var world = instance.getWorldMatrix();
  33267. if (onBeforeDraw) {
  33268. onBeforeDraw(true, world, effectiveMaterial);
  33269. }
  33270. // Draw
  33271. this._draw(subMesh, fillMode);
  33272. }
  33273. }
  33274. }
  33275. return this;
  33276. };
  33277. /**
  33278. * Triggers the draw call for the mesh. Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager
  33279. * @param subMesh defines the subMesh to render
  33280. * @param enableAlphaMode defines if alpha mode can be changed
  33281. * @returns the current mesh
  33282. */
  33283. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  33284. if (this._checkOcclusionQuery()) {
  33285. return this;
  33286. }
  33287. var scene = this.getScene();
  33288. // Managing instances
  33289. var batch = this._getInstancesRenderList(subMesh._id);
  33290. if (batch.mustReturn) {
  33291. return this;
  33292. }
  33293. // Checking geometry state
  33294. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  33295. return this;
  33296. }
  33297. if (this._onBeforeRenderObservable) {
  33298. this._onBeforeRenderObservable.notifyObservers(this);
  33299. }
  33300. var engine = scene.getEngine();
  33301. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  33302. // Material
  33303. var material = subMesh.getMaterial();
  33304. if (!material) {
  33305. return this;
  33306. }
  33307. this._effectiveMaterial = material;
  33308. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  33309. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  33310. return this;
  33311. }
  33312. }
  33313. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  33314. return this;
  33315. }
  33316. // Alpha mode
  33317. if (enableAlphaMode) {
  33318. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  33319. }
  33320. for (var _i = 0, _a = scene._beforeRenderingMeshStage; _i < _a.length; _i++) {
  33321. var step = _a[_i];
  33322. step.action(this, subMesh, batch);
  33323. }
  33324. var effect;
  33325. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  33326. effect = subMesh.effect;
  33327. }
  33328. else {
  33329. effect = this._effectiveMaterial.getEffect();
  33330. }
  33331. if (!effect) {
  33332. return this;
  33333. }
  33334. var sideOrientation = this.overrideMaterialSideOrientation;
  33335. if (sideOrientation == null) {
  33336. sideOrientation = this._effectiveMaterial.sideOrientation;
  33337. if (this._getWorldMatrixDeterminant() < 0) {
  33338. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  33339. }
  33340. }
  33341. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  33342. if (this._effectiveMaterial.forceDepthWrite) {
  33343. engine.setDepthWrite(true);
  33344. }
  33345. // Bind
  33346. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  33347. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  33348. this._bind(subMesh, effect, fillMode);
  33349. }
  33350. var world = this.getWorldMatrix();
  33351. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  33352. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  33353. }
  33354. else {
  33355. this._effectiveMaterial.bind(world, this);
  33356. }
  33357. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  33358. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  33359. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  33360. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  33361. }
  33362. // Draw
  33363. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  33364. // Unbind
  33365. this._effectiveMaterial.unbind();
  33366. for (var _b = 0, _c = scene._afterRenderingMeshStage; _b < _c.length; _b++) {
  33367. var step = _c[_b];
  33368. step.action(this, subMesh, batch);
  33369. }
  33370. if (this._onAfterRenderObservable) {
  33371. this._onAfterRenderObservable.notifyObservers(this);
  33372. }
  33373. return this;
  33374. };
  33375. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  33376. if (isInstance && effectiveMaterial) {
  33377. effectiveMaterial.bindOnlyWorldMatrix(world);
  33378. }
  33379. };
  33380. /**
  33381. * Renormalize the mesh and patch it up if there are no weights
  33382. * Similar to normalization by adding the weights compute the reciprocal and multiply all elements, this wil ensure that everything adds to 1.
  33383. * However in the case of zero weights then we set just a single influence to 1.
  33384. * We check in the function for extra's present and if so we use the normalizeSkinWeightsWithExtras rather than the FourWeights version.
  33385. */
  33386. Mesh.prototype.cleanMatrixWeights = function () {
  33387. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33388. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  33389. this.normalizeSkinWeightsAndExtra();
  33390. }
  33391. else {
  33392. this.normalizeSkinFourWeights();
  33393. }
  33394. }
  33395. };
  33396. // faster 4 weight version.
  33397. Mesh.prototype.normalizeSkinFourWeights = function () {
  33398. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33399. var numWeights = matricesWeights.length;
  33400. for (var a = 0; a < numWeights; a += 4) {
  33401. // accumulate weights
  33402. var t = matricesWeights[a] + matricesWeights[a + 1] + matricesWeights[a + 2] + matricesWeights[a + 3];
  33403. // check for invalid weight and just set it to 1.
  33404. if (t === 0)
  33405. matricesWeights[a] = 1;
  33406. else {
  33407. // renormalize so everything adds to 1 use reciprical
  33408. var recip = 1 / t;
  33409. matricesWeights[a] *= recip;
  33410. matricesWeights[a + 1] *= recip;
  33411. matricesWeights[a + 2] *= recip;
  33412. matricesWeights[a + 3] *= recip;
  33413. }
  33414. }
  33415. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  33416. };
  33417. // handle special case of extra verts. (in theory gltf can handle 12 influences)
  33418. Mesh.prototype.normalizeSkinWeightsAndExtra = function () {
  33419. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  33420. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33421. var numWeights = matricesWeights.length;
  33422. for (var a = 0; a < numWeights; a += 4) {
  33423. // accumulate weights
  33424. var t = matricesWeights[a] + matricesWeights[a + 1] + matricesWeights[a + 2] + matricesWeights[a + 3];
  33425. t += matricesWeightsExtra[a] + matricesWeightsExtra[a + 1] + matricesWeightsExtra[a + 2] + matricesWeightsExtra[a + 3];
  33426. // check for invalid weight and just set it to 1.
  33427. if (t === 0)
  33428. matricesWeights[a] = 1;
  33429. else {
  33430. // renormalize so everything adds to 1 use reciprical
  33431. var recip = 1 / t;
  33432. matricesWeights[a] *= recip;
  33433. matricesWeights[a + 1] *= recip;
  33434. matricesWeights[a + 2] *= recip;
  33435. matricesWeights[a + 3] *= recip;
  33436. // same goes for extras
  33437. matricesWeightsExtra[a] *= recip;
  33438. matricesWeightsExtra[a + 1] *= recip;
  33439. matricesWeightsExtra[a + 2] *= recip;
  33440. matricesWeightsExtra[a + 3] *= recip;
  33441. }
  33442. }
  33443. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  33444. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsExtra);
  33445. };
  33446. /**
  33447. * ValidateSkinning is used to determine that a mesh has valid skinning data along with skin metrics, if missing weights,
  33448. * or not normalized it is returned as invalid mesh the string can be used for console logs, or on screen messages to let
  33449. * the user know there was an issue with importing the mesh
  33450. * @returns a validation object with skinned, valid and report string
  33451. */
  33452. Mesh.prototype.validateSkinning = function () {
  33453. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  33454. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33455. if (matricesWeights === null || this.skeleton == null) {
  33456. return { skinned: false, valid: true, report: "not skinned" };
  33457. }
  33458. var numWeights = matricesWeights.length;
  33459. var numberNotSorted = 0;
  33460. var missingWeights = 0;
  33461. var maxUsedWeights = 0;
  33462. var numberNotNormalized = 0;
  33463. var numInfluences = matricesWeightsExtra === null ? 4 : 8;
  33464. var usedWeightCounts = new Array();
  33465. for (var a = 0; a <= numInfluences; a++) {
  33466. usedWeightCounts[a] = 0;
  33467. }
  33468. var toleranceEpsilon = 0.001;
  33469. for (var a = 0; a < numWeights; a += 4) {
  33470. var lastWeight = matricesWeights[a];
  33471. var t = lastWeight;
  33472. var usedWeights = t === 0 ? 0 : 1;
  33473. for (var b = 1; b < numInfluences; b++) {
  33474. var d = b < 4 ? matricesWeights[a + b] : matricesWeightsExtra[a + b - 4];
  33475. if (d > lastWeight)
  33476. numberNotSorted++;
  33477. if (d !== 0)
  33478. usedWeights++;
  33479. t += d;
  33480. lastWeight = d;
  33481. }
  33482. // count the buffer weights usage
  33483. usedWeightCounts[usedWeights]++;
  33484. // max influences
  33485. if (usedWeights > maxUsedWeights)
  33486. maxUsedWeights = usedWeights;
  33487. // check for invalid weight and just set it to 1.
  33488. if (t === 0) {
  33489. missingWeights++;
  33490. }
  33491. else {
  33492. // renormalize so everything adds to 1 use reciprical
  33493. var recip = 1 / t;
  33494. var tolerance = 0;
  33495. for (b = 0; b < numInfluences; b++) {
  33496. if (b < 4)
  33497. tolerance += Math.abs(matricesWeights[a + b] - (matricesWeights[a + b] * recip));
  33498. else
  33499. tolerance += Math.abs(matricesWeightsExtra[a + b - 4] - (matricesWeightsExtra[a + b - 4] * recip));
  33500. }
  33501. // arbitary epsilon value for dicdating not normalized
  33502. if (tolerance > toleranceEpsilon)
  33503. numberNotNormalized++;
  33504. }
  33505. }
  33506. // validate bone indices are in range of the skeleton
  33507. var numBones = this.skeleton.bones.length;
  33508. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33509. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  33510. var numBadBoneIndices = 0;
  33511. for (var a = 0; a < numWeights; a++) {
  33512. for (var b = 0; b < numInfluences; b++) {
  33513. var index = b < 4 ? matricesIndices[b] : matricesIndicesExtra[b - 4];
  33514. if (index >= numBones || index < 0)
  33515. numBadBoneIndices++;
  33516. }
  33517. }
  33518. // log mesh stats
  33519. var output = "Number of Weights = " + numWeights / 4 + "\nMaximum influences = " + maxUsedWeights +
  33520. "\nMissing Weights = " + missingWeights + "\nNot Sorted = " + numberNotSorted +
  33521. "\nNot Normalized = " + numberNotNormalized + "\nWeightCounts = [" + usedWeightCounts + "]" +
  33522. "\nNumber of bones = " + numBones + "\nBad Bone Indices = " + numBadBoneIndices;
  33523. return { skinned: true, valid: missingWeights === 0 && numberNotNormalized === 0 && numBadBoneIndices === 0, report: output };
  33524. };
  33525. /** @hidden */
  33526. Mesh.prototype._checkDelayState = function () {
  33527. var scene = this.getScene();
  33528. if (this._geometry) {
  33529. this._geometry.load(scene);
  33530. }
  33531. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  33532. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  33533. this._queueLoad(scene);
  33534. }
  33535. return this;
  33536. };
  33537. Mesh.prototype._queueLoad = function (scene) {
  33538. var _this = this;
  33539. scene._addPendingData(this);
  33540. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  33541. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  33542. if (data instanceof ArrayBuffer) {
  33543. _this._delayLoadingFunction(data, _this);
  33544. }
  33545. else {
  33546. _this._delayLoadingFunction(JSON.parse(data), _this);
  33547. }
  33548. _this.instances.forEach(function (instance) {
  33549. instance._syncSubMeshes();
  33550. });
  33551. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  33552. scene._removePendingData(_this);
  33553. }, function () { }, scene.database, getBinaryData);
  33554. return this;
  33555. };
  33556. /**
  33557. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  33558. * A mesh is in the frustum if its bounding box intersects the frustum
  33559. * @param frustumPlanes defines the frustum to test
  33560. * @returns true if the mesh is in the frustum planes
  33561. */
  33562. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  33563. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  33564. return false;
  33565. }
  33566. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  33567. return false;
  33568. }
  33569. this._checkDelayState();
  33570. return true;
  33571. };
  33572. /**
  33573. * Sets the mesh material by the material or multiMaterial `id` property
  33574. * @param id is a string identifying the material or the multiMaterial
  33575. * @returns the current mesh
  33576. */
  33577. Mesh.prototype.setMaterialByID = function (id) {
  33578. var materials = this.getScene().materials;
  33579. var index;
  33580. for (index = materials.length - 1; index > -1; index--) {
  33581. if (materials[index].id === id) {
  33582. this.material = materials[index];
  33583. return this;
  33584. }
  33585. }
  33586. // Multi
  33587. var multiMaterials = this.getScene().multiMaterials;
  33588. for (index = multiMaterials.length - 1; index > -1; index--) {
  33589. if (multiMaterials[index].id === id) {
  33590. this.material = multiMaterials[index];
  33591. return this;
  33592. }
  33593. }
  33594. return this;
  33595. };
  33596. /**
  33597. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  33598. * @returns an array of IAnimatable
  33599. */
  33600. Mesh.prototype.getAnimatables = function () {
  33601. var results = new Array();
  33602. if (this.material) {
  33603. results.push(this.material);
  33604. }
  33605. if (this.skeleton) {
  33606. results.push(this.skeleton);
  33607. }
  33608. return results;
  33609. };
  33610. /**
  33611. * Modifies the mesh geometry according to the passed transformation matrix.
  33612. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  33613. * The mesh normals are modified using the same transformation.
  33614. * Note that, under the hood, this method sets a new VertexBuffer each call.
  33615. * @param transform defines the transform matrix to use
  33616. * @see http://doc.babylonjs.com/resources/baking_transformations
  33617. * @returns the current mesh
  33618. */
  33619. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  33620. // Position
  33621. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33622. return this;
  33623. }
  33624. var submeshes = this.subMeshes.splice(0);
  33625. this._resetPointsArrayCache();
  33626. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33627. var temp = new Array();
  33628. var index;
  33629. for (index = 0; index < data.length; index += 3) {
  33630. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  33631. }
  33632. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  33633. // Normals
  33634. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33635. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33636. temp = [];
  33637. for (index = 0; index < data.length; index += 3) {
  33638. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  33639. }
  33640. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  33641. }
  33642. // flip faces?
  33643. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  33644. this.flipFaces();
  33645. }
  33646. // Restore submeshes
  33647. this.releaseSubMeshes();
  33648. this.subMeshes = submeshes;
  33649. return this;
  33650. };
  33651. /**
  33652. * Modifies the mesh geometry according to its own current World Matrix.
  33653. * The mesh World Matrix is then reset.
  33654. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  33655. * Note that, under the hood, this method sets a new VertexBuffer each call.
  33656. * @see http://doc.babylonjs.com/resources/baking_transformations
  33657. * @returns the current mesh
  33658. */
  33659. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  33660. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  33661. this.scaling.copyFromFloats(1, 1, 1);
  33662. this.position.copyFromFloats(0, 0, 0);
  33663. this.rotation.copyFromFloats(0, 0, 0);
  33664. //only if quaternion is already set
  33665. if (this.rotationQuaternion) {
  33666. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  33667. }
  33668. this._worldMatrix = BABYLON.Matrix.Identity();
  33669. return this;
  33670. };
  33671. Object.defineProperty(Mesh.prototype, "_positions", {
  33672. // Cache
  33673. /** @hidden */
  33674. get: function () {
  33675. if (this._geometry) {
  33676. return this._geometry._positions;
  33677. }
  33678. return null;
  33679. },
  33680. enumerable: true,
  33681. configurable: true
  33682. });
  33683. /** @hidden */
  33684. Mesh.prototype._resetPointsArrayCache = function () {
  33685. if (this._geometry) {
  33686. this._geometry._resetPointsArrayCache();
  33687. }
  33688. return this;
  33689. };
  33690. /** @hidden */
  33691. Mesh.prototype._generatePointsArray = function () {
  33692. if (this._geometry) {
  33693. return this._geometry._generatePointsArray();
  33694. }
  33695. return false;
  33696. };
  33697. /**
  33698. * Returns a new Mesh object generated from the current mesh properties.
  33699. * This method must not get confused with createInstance()
  33700. * @param name is a string, the name given to the new mesh
  33701. * @param newParent can be any Node object (default `null`)
  33702. * @param doNotCloneChildren allows/denies the recursive cloning of the original mesh children if any (default `false`)
  33703. * @param clonePhysicsImpostor allows/denies the cloning in the same time of the original mesh `body` used by the physics engine, if any (default `true`)
  33704. * @returns a new mesh
  33705. */
  33706. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  33707. if (name === void 0) { name = ""; }
  33708. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  33709. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  33710. };
  33711. /**
  33712. * Releases resources associated with this mesh.
  33713. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  33714. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  33715. */
  33716. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  33717. var _this = this;
  33718. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  33719. this.morphTargetManager = null;
  33720. if (this._geometry) {
  33721. this._geometry.releaseForMesh(this, true);
  33722. }
  33723. if (this._onBeforeDrawObservable) {
  33724. this._onBeforeDrawObservable.clear();
  33725. }
  33726. if (this._onBeforeRenderObservable) {
  33727. this._onBeforeRenderObservable.clear();
  33728. }
  33729. if (this._onAfterRenderObservable) {
  33730. this._onAfterRenderObservable.clear();
  33731. }
  33732. // Sources
  33733. var meshes = this.getScene().meshes;
  33734. meshes.forEach(function (abstractMesh) {
  33735. var mesh = abstractMesh;
  33736. if (mesh._source && mesh._source === _this) {
  33737. mesh._source = null;
  33738. }
  33739. });
  33740. this._source = null;
  33741. // Instances
  33742. if (this._instanceDataStorage.instancesBuffer) {
  33743. this._instanceDataStorage.instancesBuffer.dispose();
  33744. this._instanceDataStorage.instancesBuffer = null;
  33745. }
  33746. while (this.instances.length) {
  33747. this.instances[0].dispose();
  33748. }
  33749. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  33750. };
  33751. /**
  33752. * Modifies the mesh geometry according to a displacement map.
  33753. * 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.
  33754. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  33755. * @param url is a string, the URL from the image file is to be downloaded.
  33756. * @param minHeight is the lower limit of the displacement.
  33757. * @param maxHeight is the upper limit of the displacement.
  33758. * @param onSuccess is an optional Javascript function to be called just after the mesh is modified. It is passed the modified mesh and must return nothing.
  33759. * @param uvOffset is an optional vector2 used to offset UV.
  33760. * @param uvScale is an optional vector2 used to scale UV.
  33761. * @param forceUpdate defines whether or not to force an update of the generated buffers. This is usefull to apply on a deserialized model for instance.
  33762. * @returns the Mesh.
  33763. */
  33764. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale, forceUpdate) {
  33765. var _this = this;
  33766. if (forceUpdate === void 0) { forceUpdate = false; }
  33767. var scene = this.getScene();
  33768. var onload = function (img) {
  33769. // Getting height map data
  33770. var canvas = document.createElement("canvas");
  33771. var context = canvas.getContext("2d");
  33772. var heightMapWidth = img.width;
  33773. var heightMapHeight = img.height;
  33774. canvas.width = heightMapWidth;
  33775. canvas.height = heightMapHeight;
  33776. context.drawImage(img, 0, 0);
  33777. // Create VertexData from map data
  33778. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  33779. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  33780. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate);
  33781. //execute success callback, if set
  33782. if (onSuccess) {
  33783. onSuccess(_this);
  33784. }
  33785. };
  33786. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  33787. return this;
  33788. };
  33789. /**
  33790. * Modifies the mesh geometry according to a displacementMap buffer.
  33791. * 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.
  33792. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  33793. * @param buffer is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
  33794. * @param heightMapWidth is the width of the buffer image.
  33795. * @param heightMapHeight is the height of the buffer image.
  33796. * @param minHeight is the lower limit of the displacement.
  33797. * @param maxHeight is the upper limit of the displacement.
  33798. * @param onSuccess is an optional Javascript function to be called just after the mesh is modified. It is passed the modified mesh and must return nothing.
  33799. * @param uvOffset is an optional vector2 used to offset UV.
  33800. * @param uvScale is an optional vector2 used to scale UV.
  33801. * @param forceUpdate defines whether or not to force an update of the generated buffers. This is usefull to apply on a deserialized model for instance.
  33802. * @returns the Mesh.
  33803. */
  33804. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate) {
  33805. if (forceUpdate === void 0) { forceUpdate = false; }
  33806. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  33807. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  33808. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33809. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  33810. return this;
  33811. }
  33812. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, true, true);
  33813. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33814. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  33815. var position = BABYLON.Vector3.Zero();
  33816. var normal = BABYLON.Vector3.Zero();
  33817. var uv = BABYLON.Vector2.Zero();
  33818. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  33819. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  33820. for (var index = 0; index < positions.length; index += 3) {
  33821. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  33822. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  33823. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  33824. // Compute height
  33825. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  33826. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  33827. var pos = (u + v * heightMapWidth) * 4;
  33828. var r = buffer[pos] / 255.0;
  33829. var g = buffer[pos + 1] / 255.0;
  33830. var b = buffer[pos + 2] / 255.0;
  33831. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  33832. normal.normalize();
  33833. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  33834. position = position.add(normal);
  33835. position.toArray(positions, index);
  33836. }
  33837. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  33838. if (forceUpdate) {
  33839. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  33840. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  33841. }
  33842. else {
  33843. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  33844. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  33845. }
  33846. return this;
  33847. };
  33848. /**
  33849. * Modify the mesh to get a flat shading rendering.
  33850. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  33851. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  33852. * @returns current mesh
  33853. */
  33854. Mesh.prototype.convertToFlatShadedMesh = function () {
  33855. var kinds = this.getVerticesDataKinds();
  33856. var vbs = {};
  33857. var data = {};
  33858. var newdata = {};
  33859. var updatableNormals = false;
  33860. var kindIndex;
  33861. var kind;
  33862. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33863. kind = kinds[kindIndex];
  33864. var vertexBuffer = this.getVertexBuffer(kind);
  33865. if (kind === BABYLON.VertexBuffer.NormalKind) {
  33866. updatableNormals = vertexBuffer.isUpdatable();
  33867. kinds.splice(kindIndex, 1);
  33868. kindIndex--;
  33869. continue;
  33870. }
  33871. vbs[kind] = vertexBuffer;
  33872. data[kind] = vbs[kind].getData();
  33873. newdata[kind] = [];
  33874. }
  33875. // Save previous submeshes
  33876. var previousSubmeshes = this.subMeshes.slice(0);
  33877. var indices = this.getIndices();
  33878. var totalIndices = this.getTotalIndices();
  33879. // Generating unique vertices per face
  33880. var index;
  33881. for (index = 0; index < totalIndices; index++) {
  33882. var vertexIndex = indices[index];
  33883. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33884. kind = kinds[kindIndex];
  33885. var stride = vbs[kind].getStrideSize();
  33886. for (var offset = 0; offset < stride; offset++) {
  33887. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  33888. }
  33889. }
  33890. }
  33891. // Updating faces & normal
  33892. var normals = [];
  33893. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  33894. for (index = 0; index < totalIndices; index += 3) {
  33895. indices[index] = index;
  33896. indices[index + 1] = index + 1;
  33897. indices[index + 2] = index + 2;
  33898. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  33899. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  33900. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  33901. var p1p2 = p1.subtract(p2);
  33902. var p3p2 = p3.subtract(p2);
  33903. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  33904. // Store same normals for every vertex
  33905. for (var localIndex = 0; localIndex < 3; localIndex++) {
  33906. normals.push(normal.x);
  33907. normals.push(normal.y);
  33908. normals.push(normal.z);
  33909. }
  33910. }
  33911. this.setIndices(indices);
  33912. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  33913. // Updating vertex buffers
  33914. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33915. kind = kinds[kindIndex];
  33916. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  33917. }
  33918. // Updating submeshes
  33919. this.releaseSubMeshes();
  33920. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  33921. var previousOne = previousSubmeshes[submeshIndex];
  33922. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  33923. }
  33924. this.synchronizeInstances();
  33925. return this;
  33926. };
  33927. /**
  33928. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  33929. * In other words, more vertices, no more indices and a single bigger VBO.
  33930. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  33931. * @returns current mesh
  33932. */
  33933. Mesh.prototype.convertToUnIndexedMesh = function () {
  33934. var kinds = this.getVerticesDataKinds();
  33935. var vbs = {};
  33936. var data = {};
  33937. var newdata = {};
  33938. var kindIndex;
  33939. var kind;
  33940. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33941. kind = kinds[kindIndex];
  33942. var vertexBuffer = this.getVertexBuffer(kind);
  33943. vbs[kind] = vertexBuffer;
  33944. data[kind] = vbs[kind].getData();
  33945. newdata[kind] = [];
  33946. }
  33947. // Save previous submeshes
  33948. var previousSubmeshes = this.subMeshes.slice(0);
  33949. var indices = this.getIndices();
  33950. var totalIndices = this.getTotalIndices();
  33951. // Generating unique vertices per face
  33952. var index;
  33953. for (index = 0; index < totalIndices; index++) {
  33954. var vertexIndex = indices[index];
  33955. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33956. kind = kinds[kindIndex];
  33957. var stride = vbs[kind].getStrideSize();
  33958. for (var offset = 0; offset < stride; offset++) {
  33959. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  33960. }
  33961. }
  33962. }
  33963. // Updating indices
  33964. for (index = 0; index < totalIndices; index += 3) {
  33965. indices[index] = index;
  33966. indices[index + 1] = index + 1;
  33967. indices[index + 2] = index + 2;
  33968. }
  33969. this.setIndices(indices);
  33970. // Updating vertex buffers
  33971. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33972. kind = kinds[kindIndex];
  33973. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  33974. }
  33975. // Updating submeshes
  33976. this.releaseSubMeshes();
  33977. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  33978. var previousOne = previousSubmeshes[submeshIndex];
  33979. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  33980. }
  33981. this._unIndexed = true;
  33982. this.synchronizeInstances();
  33983. return this;
  33984. };
  33985. /**
  33986. * Inverses facet orientations.
  33987. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  33988. * @param flipNormals will also inverts the normals
  33989. * @returns current mesh
  33990. */
  33991. Mesh.prototype.flipFaces = function (flipNormals) {
  33992. if (flipNormals === void 0) { flipNormals = false; }
  33993. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  33994. var i;
  33995. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  33996. for (i = 0; i < vertex_data.normals.length; i++) {
  33997. vertex_data.normals[i] *= -1;
  33998. }
  33999. }
  34000. if (vertex_data.indices) {
  34001. var temp;
  34002. for (i = 0; i < vertex_data.indices.length; i += 3) {
  34003. // reassign indices
  34004. temp = vertex_data.indices[i + 1];
  34005. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  34006. vertex_data.indices[i + 2] = temp;
  34007. }
  34008. }
  34009. vertex_data.applyToMesh(this);
  34010. return this;
  34011. };
  34012. // Instances
  34013. /**
  34014. * Creates a new InstancedMesh object from the mesh model.
  34015. * Warning : this method is not supported for Line mesh and LineSystem
  34016. * @see http://doc.babylonjs.com/how_to/how_to_use_instances
  34017. * @param name defines the name of the new instance
  34018. * @returns a new InstancedMesh
  34019. */
  34020. Mesh.prototype.createInstance = function (name) {
  34021. return new BABYLON.InstancedMesh(name, this);
  34022. };
  34023. /**
  34024. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  34025. * After this call, all the mesh instances have the same submeshes than the current mesh.
  34026. * @returns the current mesh
  34027. */
  34028. Mesh.prototype.synchronizeInstances = function () {
  34029. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  34030. var instance = this.instances[instanceIndex];
  34031. instance._syncSubMeshes();
  34032. }
  34033. return this;
  34034. };
  34035. /**
  34036. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  34037. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  34038. * This should be used together with the simplification to avoid disappearing triangles.
  34039. * @param successCallback an optional success callback to be called after the optimization finished.
  34040. * @returns the current mesh
  34041. */
  34042. Mesh.prototype.optimizeIndices = function (successCallback) {
  34043. var _this = this;
  34044. var indices = this.getIndices();
  34045. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34046. if (!positions || !indices) {
  34047. return this;
  34048. }
  34049. var vectorPositions = new Array();
  34050. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  34051. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  34052. }
  34053. var dupes = new Array();
  34054. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  34055. var realPos = vectorPositions.length - 1 - iteration;
  34056. var testedPosition = vectorPositions[realPos];
  34057. for (var j = 0; j < realPos; ++j) {
  34058. var againstPosition = vectorPositions[j];
  34059. if (testedPosition.equals(againstPosition)) {
  34060. dupes[realPos] = j;
  34061. break;
  34062. }
  34063. }
  34064. }, function () {
  34065. for (var i = 0; i < indices.length; ++i) {
  34066. indices[i] = dupes[indices[i]] || indices[i];
  34067. }
  34068. //indices are now reordered
  34069. var originalSubMeshes = _this.subMeshes.slice(0);
  34070. _this.setIndices(indices);
  34071. _this.subMeshes = originalSubMeshes;
  34072. if (successCallback) {
  34073. successCallback(_this);
  34074. }
  34075. });
  34076. return this;
  34077. };
  34078. /**
  34079. * Serialize current mesh
  34080. * @param serializationObject defines the object which will receive the serialization data
  34081. */
  34082. Mesh.prototype.serialize = function (serializationObject) {
  34083. serializationObject.name = this.name;
  34084. serializationObject.id = this.id;
  34085. serializationObject.type = this.getClassName();
  34086. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  34087. serializationObject.tags = BABYLON.Tags.GetTags(this);
  34088. }
  34089. serializationObject.position = this.position.asArray();
  34090. if (this.rotationQuaternion) {
  34091. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  34092. }
  34093. else if (this.rotation) {
  34094. serializationObject.rotation = this.rotation.asArray();
  34095. }
  34096. serializationObject.scaling = this.scaling.asArray();
  34097. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  34098. serializationObject.isEnabled = this.isEnabled(false);
  34099. serializationObject.isVisible = this.isVisible;
  34100. serializationObject.infiniteDistance = this.infiniteDistance;
  34101. serializationObject.pickable = this.isPickable;
  34102. serializationObject.receiveShadows = this.receiveShadows;
  34103. serializationObject.billboardMode = this.billboardMode;
  34104. serializationObject.visibility = this.visibility;
  34105. serializationObject.checkCollisions = this.checkCollisions;
  34106. serializationObject.isBlocker = this.isBlocker;
  34107. // Parent
  34108. if (this.parent) {
  34109. serializationObject.parentId = this.parent.id;
  34110. }
  34111. // Geometry
  34112. serializationObject.isUnIndexed = this.isUnIndexed;
  34113. var geometry = this._geometry;
  34114. if (geometry) {
  34115. var geometryId = geometry.id;
  34116. serializationObject.geometryId = geometryId;
  34117. // SubMeshes
  34118. serializationObject.subMeshes = [];
  34119. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  34120. var subMesh = this.subMeshes[subIndex];
  34121. serializationObject.subMeshes.push({
  34122. materialIndex: subMesh.materialIndex,
  34123. verticesStart: subMesh.verticesStart,
  34124. verticesCount: subMesh.verticesCount,
  34125. indexStart: subMesh.indexStart,
  34126. indexCount: subMesh.indexCount
  34127. });
  34128. }
  34129. }
  34130. // Material
  34131. if (this.material) {
  34132. serializationObject.materialId = this.material.id;
  34133. }
  34134. else {
  34135. this.material = null;
  34136. }
  34137. // Morph targets
  34138. if (this.morphTargetManager) {
  34139. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  34140. }
  34141. // Skeleton
  34142. if (this.skeleton) {
  34143. serializationObject.skeletonId = this.skeleton.id;
  34144. }
  34145. // Physics
  34146. //TODO implement correct serialization for physics impostors.
  34147. var impostor = this.getPhysicsImpostor();
  34148. if (impostor) {
  34149. serializationObject.physicsMass = impostor.getParam("mass");
  34150. serializationObject.physicsFriction = impostor.getParam("friction");
  34151. serializationObject.physicsRestitution = impostor.getParam("mass");
  34152. serializationObject.physicsImpostor = impostor.type;
  34153. }
  34154. // Metadata
  34155. if (this.metadata) {
  34156. serializationObject.metadata = this.metadata;
  34157. }
  34158. // Instances
  34159. serializationObject.instances = [];
  34160. for (var index = 0; index < this.instances.length; index++) {
  34161. var instance = this.instances[index];
  34162. if (instance.doNotSerialize) {
  34163. continue;
  34164. }
  34165. var serializationInstance = {
  34166. name: instance.name,
  34167. id: instance.id,
  34168. position: instance.position.asArray(),
  34169. scaling: instance.scaling.asArray()
  34170. };
  34171. if (instance.parent) {
  34172. serializationInstance.parentId = instance.parent.id;
  34173. }
  34174. if (instance.rotationQuaternion) {
  34175. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  34176. }
  34177. else if (instance.rotation) {
  34178. serializationInstance.rotation = instance.rotation.asArray();
  34179. }
  34180. serializationObject.instances.push(serializationInstance);
  34181. // Animations
  34182. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  34183. serializationInstance.ranges = instance.serializeAnimationRanges();
  34184. }
  34185. //
  34186. // Animations
  34187. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  34188. serializationObject.ranges = this.serializeAnimationRanges();
  34189. // Layer mask
  34190. serializationObject.layerMask = this.layerMask;
  34191. // Alpha
  34192. serializationObject.alphaIndex = this.alphaIndex;
  34193. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  34194. // Overlay
  34195. serializationObject.overlayAlpha = this.overlayAlpha;
  34196. serializationObject.overlayColor = this.overlayColor.asArray();
  34197. serializationObject.renderOverlay = this.renderOverlay;
  34198. // Fog
  34199. serializationObject.applyFog = this.applyFog;
  34200. // Action Manager
  34201. if (this.actionManager) {
  34202. serializationObject.actions = this.actionManager.serialize(this.name);
  34203. }
  34204. };
  34205. /** @hidden */
  34206. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  34207. if (!this.geometry) {
  34208. return;
  34209. }
  34210. this._markSubMeshesAsAttributesDirty();
  34211. var morphTargetManager = this._morphTargetManager;
  34212. if (morphTargetManager && morphTargetManager.vertexCount) {
  34213. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  34214. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  34215. this.morphTargetManager = null;
  34216. return;
  34217. }
  34218. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  34219. var morphTarget = morphTargetManager.getActiveTarget(index);
  34220. var positions = morphTarget.getPositions();
  34221. if (!positions) {
  34222. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  34223. return;
  34224. }
  34225. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  34226. var normals = morphTarget.getNormals();
  34227. if (normals) {
  34228. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  34229. }
  34230. var tangents = morphTarget.getTangents();
  34231. if (tangents) {
  34232. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  34233. }
  34234. }
  34235. }
  34236. else {
  34237. var index = 0;
  34238. // Positions
  34239. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  34240. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  34241. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  34242. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  34243. }
  34244. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  34245. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  34246. }
  34247. index++;
  34248. }
  34249. }
  34250. };
  34251. // Statics
  34252. /**
  34253. * Returns a new Mesh object parsed from the source provided.
  34254. * @param parsedMesh is the source
  34255. * @param scene defines the hosting scene
  34256. * @param rootUrl is the root URL to prefix the `delayLoadingFile` property with
  34257. * @returns a new Mesh
  34258. */
  34259. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  34260. var mesh;
  34261. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  34262. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  34263. }
  34264. else {
  34265. mesh = new Mesh(parsedMesh.name, scene);
  34266. }
  34267. mesh.id = parsedMesh.id;
  34268. if (BABYLON.Tags) {
  34269. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  34270. }
  34271. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  34272. if (parsedMesh.metadata !== undefined) {
  34273. mesh.metadata = parsedMesh.metadata;
  34274. }
  34275. if (parsedMesh.rotationQuaternion) {
  34276. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  34277. }
  34278. else if (parsedMesh.rotation) {
  34279. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  34280. }
  34281. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  34282. if (parsedMesh.localMatrix) {
  34283. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  34284. }
  34285. else if (parsedMesh.pivotMatrix) {
  34286. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  34287. }
  34288. mesh.setEnabled(parsedMesh.isEnabled);
  34289. mesh.isVisible = parsedMesh.isVisible;
  34290. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  34291. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  34292. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  34293. if (parsedMesh.applyFog !== undefined) {
  34294. mesh.applyFog = parsedMesh.applyFog;
  34295. }
  34296. if (parsedMesh.pickable !== undefined) {
  34297. mesh.isPickable = parsedMesh.pickable;
  34298. }
  34299. if (parsedMesh.alphaIndex !== undefined) {
  34300. mesh.alphaIndex = parsedMesh.alphaIndex;
  34301. }
  34302. mesh.receiveShadows = parsedMesh.receiveShadows;
  34303. mesh.billboardMode = parsedMesh.billboardMode;
  34304. if (parsedMesh.visibility !== undefined) {
  34305. mesh.visibility = parsedMesh.visibility;
  34306. }
  34307. mesh.checkCollisions = parsedMesh.checkCollisions;
  34308. if (parsedMesh.isBlocker !== undefined) {
  34309. mesh.isBlocker = parsedMesh.isBlocker;
  34310. }
  34311. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  34312. // freezeWorldMatrix
  34313. if (parsedMesh.freezeWorldMatrix) {
  34314. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  34315. }
  34316. // Parent
  34317. if (parsedMesh.parentId) {
  34318. mesh._waitingParentId = parsedMesh.parentId;
  34319. }
  34320. // Actions
  34321. if (parsedMesh.actions !== undefined) {
  34322. mesh._waitingActions = parsedMesh.actions;
  34323. }
  34324. // Overlay
  34325. if (parsedMesh.overlayAlpha !== undefined) {
  34326. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  34327. }
  34328. if (parsedMesh.overlayColor !== undefined) {
  34329. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  34330. }
  34331. if (parsedMesh.renderOverlay !== undefined) {
  34332. mesh.renderOverlay = parsedMesh.renderOverlay;
  34333. }
  34334. // Geometry
  34335. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  34336. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  34337. if (parsedMesh.delayLoadingFile) {
  34338. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  34339. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  34340. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  34341. if (parsedMesh._binaryInfo) {
  34342. mesh._binaryInfo = parsedMesh._binaryInfo;
  34343. }
  34344. mesh._delayInfo = [];
  34345. if (parsedMesh.hasUVs) {
  34346. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  34347. }
  34348. if (parsedMesh.hasUVs2) {
  34349. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  34350. }
  34351. if (parsedMesh.hasUVs3) {
  34352. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  34353. }
  34354. if (parsedMesh.hasUVs4) {
  34355. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  34356. }
  34357. if (parsedMesh.hasUVs5) {
  34358. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  34359. }
  34360. if (parsedMesh.hasUVs6) {
  34361. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  34362. }
  34363. if (parsedMesh.hasColors) {
  34364. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  34365. }
  34366. if (parsedMesh.hasMatricesIndices) {
  34367. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  34368. }
  34369. if (parsedMesh.hasMatricesWeights) {
  34370. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  34371. }
  34372. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  34373. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  34374. mesh._checkDelayState();
  34375. }
  34376. }
  34377. else {
  34378. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  34379. }
  34380. // Material
  34381. if (parsedMesh.materialId) {
  34382. mesh.setMaterialByID(parsedMesh.materialId);
  34383. }
  34384. else {
  34385. mesh.material = null;
  34386. }
  34387. // Morph targets
  34388. if (parsedMesh.morphTargetManagerId > -1) {
  34389. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  34390. }
  34391. // Skeleton
  34392. if (parsedMesh.skeletonId > -1) {
  34393. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  34394. if (parsedMesh.numBoneInfluencers) {
  34395. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  34396. }
  34397. }
  34398. // Animations
  34399. if (parsedMesh.animations) {
  34400. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  34401. var parsedAnimation = parsedMesh.animations[animationIndex];
  34402. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  34403. }
  34404. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  34405. }
  34406. if (parsedMesh.autoAnimate) {
  34407. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  34408. }
  34409. // Layer Mask
  34410. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  34411. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  34412. }
  34413. else {
  34414. mesh.layerMask = 0x0FFFFFFF;
  34415. }
  34416. // Physics
  34417. if (parsedMesh.physicsImpostor) {
  34418. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  34419. mass: parsedMesh.physicsMass,
  34420. friction: parsedMesh.physicsFriction,
  34421. restitution: parsedMesh.physicsRestitution
  34422. }, scene);
  34423. }
  34424. // Instances
  34425. if (parsedMesh.instances) {
  34426. for (var index = 0; index < parsedMesh.instances.length; index++) {
  34427. var parsedInstance = parsedMesh.instances[index];
  34428. var instance = mesh.createInstance(parsedInstance.name);
  34429. if (parsedInstance.id) {
  34430. instance.id = parsedInstance.id;
  34431. }
  34432. if (BABYLON.Tags) {
  34433. if (parsedInstance.tags) {
  34434. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  34435. }
  34436. else {
  34437. BABYLON.Tags.AddTagsTo(instance, parsedMesh.tags);
  34438. }
  34439. }
  34440. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  34441. if (parsedInstance.parentId) {
  34442. instance._waitingParentId = parsedInstance.parentId;
  34443. }
  34444. if (parsedInstance.rotationQuaternion) {
  34445. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  34446. }
  34447. else if (parsedInstance.rotation) {
  34448. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  34449. }
  34450. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  34451. if (parsedInstance.checkCollisions != undefined && parsedInstance.checkCollisions != null) {
  34452. instance.checkCollisions = parsedInstance.checkCollisions;
  34453. }
  34454. if (parsedInstance.pickable != undefined && parsedInstance.pickable != null) {
  34455. instance.isPickable = parsedInstance.pickable;
  34456. }
  34457. if (parsedInstance.showBoundingBox != undefined && parsedInstance.showBoundingBox != null) {
  34458. instance.showBoundingBox = parsedInstance.showBoundingBox;
  34459. }
  34460. if (parsedInstance.showSubMeshesBoundingBox != undefined && parsedInstance.showSubMeshesBoundingBox != null) {
  34461. instance.showSubMeshesBoundingBox = parsedInstance.showSubMeshesBoundingBox;
  34462. }
  34463. if (parsedInstance.alphaIndex != undefined && parsedInstance.showSubMeshesBoundingBox != null) {
  34464. instance.alphaIndex = parsedInstance.alphaIndex;
  34465. }
  34466. // Physics
  34467. if (parsedInstance.physicsImpostor) {
  34468. instance.physicsImpostor = new BABYLON.PhysicsImpostor(instance, parsedInstance.physicsImpostor, {
  34469. mass: parsedInstance.physicsMass,
  34470. friction: parsedInstance.physicsFriction,
  34471. restitution: parsedInstance.physicsRestitution
  34472. }, scene);
  34473. }
  34474. // Animation
  34475. if (parsedInstance.animations) {
  34476. for (animationIndex = 0; animationIndex < parsedInstance.animations.length; animationIndex++) {
  34477. parsedAnimation = parsedInstance.animations[animationIndex];
  34478. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  34479. }
  34480. BABYLON.Node.ParseAnimationRanges(instance, parsedInstance, scene);
  34481. if (parsedInstance.autoAnimate) {
  34482. scene.beginAnimation(instance, parsedInstance.autoAnimateFrom, parsedInstance.autoAnimateTo, parsedInstance.autoAnimateLoop, parsedInstance.autoAnimateSpeed || 1.0);
  34483. }
  34484. }
  34485. }
  34486. }
  34487. return mesh;
  34488. };
  34489. /**
  34490. * Creates a ribbon mesh. Please consider using the same method from the MeshBuilder class instead
  34491. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  34492. * @param name defines the name of the mesh to create
  34493. * @param pathArray is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  34494. * @param closeArray creates a seam between the first and the last paths of the path array (default is false)
  34495. * @param closePath creates a seam between the first and the last points of each path of the path array
  34496. * @param offset is taken in account only if the `pathArray` is containing a single path
  34497. * @param scene defines the hosting scene
  34498. * @param updatable defines if the mesh must be flagged as updatable
  34499. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34500. * @param instance defines an instance of an existing Ribbon object to be updated with the passed `pathArray` parameter (http://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#ribbon)
  34501. * @returns a new Mesh
  34502. */
  34503. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  34504. if (closeArray === void 0) { closeArray = false; }
  34505. if (updatable === void 0) { updatable = false; }
  34506. return BABYLON.MeshBuilder.CreateRibbon(name, {
  34507. pathArray: pathArray,
  34508. closeArray: closeArray,
  34509. closePath: closePath,
  34510. offset: offset,
  34511. updatable: updatable,
  34512. sideOrientation: sideOrientation,
  34513. instance: instance
  34514. }, scene);
  34515. };
  34516. /**
  34517. * Creates a plane polygonal mesh. By default, this is a disc. Please consider using the same method from the MeshBuilder class instead
  34518. * @param name defines the name of the mesh to create
  34519. * @param radius sets the radius size (float) of the polygon (default 0.5)
  34520. * @param 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
  34521. * @param scene defines the hosting scene
  34522. * @param updatable defines if the mesh must be flagged as updatable
  34523. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34524. * @returns a new Mesh
  34525. */
  34526. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  34527. if (scene === void 0) { scene = null; }
  34528. var options = {
  34529. radius: radius,
  34530. tessellation: tessellation,
  34531. sideOrientation: sideOrientation,
  34532. updatable: updatable
  34533. };
  34534. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  34535. };
  34536. /**
  34537. * Creates a box mesh. Please consider using the same method from the MeshBuilder class instead
  34538. * @param name defines the name of the mesh to create
  34539. * @param size sets the size (float) of each box side (default 1)
  34540. * @param scene defines the hosting scene
  34541. * @param updatable defines if the mesh must be flagged as updatable
  34542. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34543. * @returns a new Mesh
  34544. */
  34545. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  34546. if (scene === void 0) { scene = null; }
  34547. var options = {
  34548. size: size,
  34549. sideOrientation: sideOrientation,
  34550. updatable: updatable
  34551. };
  34552. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  34553. };
  34554. /**
  34555. * Creates a sphere mesh. Please consider using the same method from the MeshBuilder class instead
  34556. * @param name defines the name of the mesh to create
  34557. * @param segments sets the sphere number of horizontal stripes (positive integer, default 32)
  34558. * @param diameter sets the diameter size (float) of the sphere (default 1)
  34559. * @param scene defines the hosting scene
  34560. * @param updatable defines if the mesh must be flagged as updatable
  34561. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34562. * @returns a new Mesh
  34563. */
  34564. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  34565. var options = {
  34566. segments: segments,
  34567. diameterX: diameter,
  34568. diameterY: diameter,
  34569. diameterZ: diameter,
  34570. sideOrientation: sideOrientation,
  34571. updatable: updatable
  34572. };
  34573. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  34574. };
  34575. /**
  34576. * Creates a cylinder or a cone mesh. Please consider using the same method from the MeshBuilder class instead
  34577. * @param name defines the name of the mesh to create
  34578. * @param height sets the height size (float) of the cylinder/cone (float, default 2)
  34579. * @param diameterTop set the top cap diameter (floats, default 1)
  34580. * @param diameterBottom set the bottom cap diameter (floats, default 1). This value can't be zero
  34581. * @param tessellation sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance
  34582. * @param subdivisions sets the number of rings along the cylinder height (positive integer, default 1)
  34583. * @param scene defines the hosting scene
  34584. * @param updatable defines if the mesh must be flagged as updatable
  34585. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34586. * @returns a new Mesh
  34587. */
  34588. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  34589. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  34590. if (scene !== undefined) {
  34591. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  34592. updatable = scene;
  34593. }
  34594. scene = subdivisions;
  34595. subdivisions = 1;
  34596. }
  34597. var options = {
  34598. height: height,
  34599. diameterTop: diameterTop,
  34600. diameterBottom: diameterBottom,
  34601. tessellation: tessellation,
  34602. subdivisions: subdivisions,
  34603. sideOrientation: sideOrientation,
  34604. updatable: updatable
  34605. };
  34606. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  34607. };
  34608. // Torus (Code from SharpDX.org)
  34609. /**
  34610. * Creates a torus mesh. Please consider using the same method from the MeshBuilder class instead
  34611. * @param name defines the name of the mesh to create
  34612. * @param diameter sets the diameter size (float) of the torus (default 1)
  34613. * @param thickness sets the diameter size of the tube of the torus (float, default 0.5)
  34614. * @param tessellation sets the number of torus sides (postive integer, default 16)
  34615. * @param scene defines the hosting scene
  34616. * @param updatable defines if the mesh must be flagged as updatable
  34617. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34618. * @returns a new Mesh
  34619. */
  34620. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  34621. var options = {
  34622. diameter: diameter,
  34623. thickness: thickness,
  34624. tessellation: tessellation,
  34625. sideOrientation: sideOrientation,
  34626. updatable: updatable
  34627. };
  34628. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  34629. };
  34630. /**
  34631. * Creates a torus knot mesh. Please consider using the same method from the MeshBuilder class instead
  34632. * @param name defines the name of the mesh to create
  34633. * @param radius sets the global radius size (float) of the torus knot (default 2)
  34634. * @param tube sets the diameter size of the tube of the torus (float, default 0.5)
  34635. * @param radialSegments sets the number of sides on each tube segments (positive integer, default 32)
  34636. * @param tubularSegments sets the number of tubes to decompose the knot into (positive integer, default 32)
  34637. * @param p the number of windings on X axis (positive integers, default 2)
  34638. * @param q the number of windings on Y axis (positive integers, default 3)
  34639. * @param scene defines the hosting scene
  34640. * @param updatable defines if the mesh must be flagged as updatable
  34641. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34642. * @returns a new Mesh
  34643. */
  34644. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  34645. var options = {
  34646. radius: radius,
  34647. tube: tube,
  34648. radialSegments: radialSegments,
  34649. tubularSegments: tubularSegments,
  34650. p: p,
  34651. q: q,
  34652. sideOrientation: sideOrientation,
  34653. updatable: updatable
  34654. };
  34655. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  34656. };
  34657. /**
  34658. * Creates a line mesh. Please consider using the same method from the MeshBuilder class instead.
  34659. * @param name defines the name of the mesh to create
  34660. * @param points is an array successive Vector3
  34661. * @param scene defines the hosting scene
  34662. * @param updatable defines if the mesh must be flagged as updatable
  34663. * @param instance is an instance of an existing LineMesh object to be updated with the passed `points` parameter (http://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#lines-and-dashedlines).
  34664. * @returns a new Mesh
  34665. */
  34666. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  34667. if (scene === void 0) { scene = null; }
  34668. if (updatable === void 0) { updatable = false; }
  34669. if (instance === void 0) { instance = null; }
  34670. var options = {
  34671. points: points,
  34672. updatable: updatable,
  34673. instance: instance
  34674. };
  34675. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  34676. };
  34677. /**
  34678. * Creates a dashed line mesh. Please consider using the same method from the MeshBuilder class instead
  34679. * @param name defines the name of the mesh to create
  34680. * @param points is an array successive Vector3
  34681. * @param dashSize is the size of the dashes relatively the dash number (positive float, default 3)
  34682. * @param gapSize is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  34683. * @param dashNb is the intended total number of dashes (positive integer, default 200)
  34684. * @param scene defines the hosting scene
  34685. * @param updatable defines if the mesh must be flagged as updatable
  34686. * @param instance is an instance of an existing LineMesh object to be updated with the passed `points` parameter (http://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#lines-and-dashedlines)
  34687. * @returns a new Mesh
  34688. */
  34689. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  34690. if (scene === void 0) { scene = null; }
  34691. var options = {
  34692. points: points,
  34693. dashSize: dashSize,
  34694. gapSize: gapSize,
  34695. dashNb: dashNb,
  34696. updatable: updatable,
  34697. instance: instance
  34698. };
  34699. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  34700. };
  34701. /**
  34702. * Creates a polygon mesh.
  34703. * Please consider using the same method from the MeshBuilder class instead.
  34704. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  34705. * 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.
  34706. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34707. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34708. * Remember you can only change the shape positions, not their number when updating a polygon.
  34709. */
  34710. /**
  34711. * Creates a polygon mesh.Please consider using the same method from the MeshBuilder class instead
  34712. * @see http://doc.babylonjs.com/how_to/parametric_shapes#non-regular-polygon
  34713. * @param name defines the name of the mesh to create
  34714. * @param 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
  34715. * @param scene defines the hosting scene
  34716. * @param holes is a required array of arrays of successive Vector3 used to defines holes in the polygon
  34717. * @param updatable defines if the mesh must be flagged as updatable
  34718. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34719. * @returns a new Mesh
  34720. */
  34721. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  34722. var options = {
  34723. shape: shape,
  34724. holes: holes,
  34725. updatable: updatable,
  34726. sideOrientation: sideOrientation
  34727. };
  34728. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  34729. };
  34730. /**
  34731. * Creates an extruded polygon mesh, with depth in the Y direction. Please consider using the same method from the MeshBuilder class instead.
  34732. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-non-regular-polygon
  34733. * @param name defines the name of the mesh to create
  34734. * @param 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
  34735. * @param depth defines the height of extrusion
  34736. * @param scene defines the hosting scene
  34737. * @param holes is a required array of arrays of successive Vector3 used to defines holes in the polygon
  34738. * @param updatable defines if the mesh must be flagged as updatable
  34739. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34740. * @returns a new Mesh
  34741. */
  34742. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  34743. var options = {
  34744. shape: shape,
  34745. holes: holes,
  34746. depth: depth,
  34747. updatable: updatable,
  34748. sideOrientation: sideOrientation
  34749. };
  34750. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  34751. };
  34752. /**
  34753. * Creates an extruded shape mesh.
  34754. * The extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters. Please consider using the same method from the MeshBuilder class instead
  34755. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  34756. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  34757. * @param name defines the name of the mesh to create
  34758. * @param 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
  34759. * @param path is a required array of successive Vector3. This is the axis curve the shape is extruded along
  34760. * @param scale is the value to scale the shape
  34761. * @param rotation 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
  34762. * @param 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
  34763. * @param scene defines the hosting scene
  34764. * @param updatable defines if the mesh must be flagged as updatable
  34765. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34766. * @param 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/how_to/How_to_dynamically_morph_a_mesh#extruded-shape)
  34767. * @returns a new Mesh
  34768. */
  34769. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  34770. if (scene === void 0) { scene = null; }
  34771. var options = {
  34772. shape: shape,
  34773. path: path,
  34774. scale: scale,
  34775. rotation: rotation,
  34776. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  34777. sideOrientation: sideOrientation,
  34778. instance: instance,
  34779. updatable: updatable
  34780. };
  34781. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  34782. };
  34783. /**
  34784. * Creates an custom extruded shape mesh.
  34785. * The custom extrusion is a parametric shape.
  34786. * It has no predefined shape. Its final shape will depend on the input parameters.
  34787. * Please consider using the same method from the MeshBuilder class instead
  34788. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  34789. * @param name defines the name of the mesh to create
  34790. * @param 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
  34791. * @param path is a required array of successive Vector3. This is the axis curve the shape is extruded along
  34792. * @param scaleFunction is a custom Javascript function called on each path point
  34793. * @param rotationFunction is a custom Javascript function called on each path point
  34794. * @param ribbonCloseArray forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  34795. * @param ribbonClosePath forces the extrusion underlying ribbon to close its `pathArray`
  34796. * @param 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
  34797. * @param scene defines the hosting scene
  34798. * @param updatable defines if the mesh must be flagged as updatable
  34799. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34800. * @param 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/how_to/how_to_dynamically_morph_a_mesh#extruded-shape)
  34801. * @returns a new Mesh
  34802. */
  34803. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  34804. var options = {
  34805. shape: shape,
  34806. path: path,
  34807. scaleFunction: scaleFunction,
  34808. rotationFunction: rotationFunction,
  34809. ribbonCloseArray: ribbonCloseArray,
  34810. ribbonClosePath: ribbonClosePath,
  34811. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  34812. sideOrientation: sideOrientation,
  34813. instance: instance,
  34814. updatable: updatable
  34815. };
  34816. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  34817. };
  34818. /**
  34819. * Creates lathe mesh.
  34820. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  34821. * Please consider using the same method from the MeshBuilder class instead
  34822. * @param name defines the name of the mesh to create
  34823. * @param 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
  34824. * @param radius is the radius value of the lathe
  34825. * @param tessellation is the side number of the lathe.
  34826. * @param scene defines the hosting scene
  34827. * @param updatable defines if the mesh must be flagged as updatable
  34828. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34829. * @returns a new Mesh
  34830. */
  34831. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  34832. var options = {
  34833. shape: shape,
  34834. radius: radius,
  34835. tessellation: tessellation,
  34836. sideOrientation: sideOrientation,
  34837. updatable: updatable
  34838. };
  34839. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  34840. };
  34841. /**
  34842. * Creates a plane mesh. Please consider using the same method from the MeshBuilder class instead
  34843. * @param name defines the name of the mesh to create
  34844. * @param size sets the size (float) of both sides of the plane at once (default 1)
  34845. * @param scene defines the hosting scene
  34846. * @param updatable defines if the mesh must be flagged as updatable
  34847. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34848. * @returns a new Mesh
  34849. */
  34850. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  34851. var options = {
  34852. size: size,
  34853. width: size,
  34854. height: size,
  34855. sideOrientation: sideOrientation,
  34856. updatable: updatable
  34857. };
  34858. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  34859. };
  34860. /**
  34861. * Creates a ground mesh.
  34862. * Please consider using the same method from the MeshBuilder class instead
  34863. * @param name defines the name of the mesh to create
  34864. * @param width set the width of the ground
  34865. * @param height set the height of the ground
  34866. * @param subdivisions sets the number of subdivisions per side
  34867. * @param scene defines the hosting scene
  34868. * @param updatable defines if the mesh must be flagged as updatable
  34869. * @returns a new Mesh
  34870. */
  34871. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  34872. var options = {
  34873. width: width,
  34874. height: height,
  34875. subdivisions: subdivisions,
  34876. updatable: updatable
  34877. };
  34878. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  34879. };
  34880. /**
  34881. * Creates a tiled ground mesh.
  34882. * Please consider using the same method from the MeshBuilder class instead
  34883. * @param name defines the name of the mesh to create
  34884. * @param xmin set the ground minimum X coordinate
  34885. * @param zmin set the ground minimum Y coordinate
  34886. * @param xmax set the ground maximum X coordinate
  34887. * @param zmax set the ground maximum Z coordinate
  34888. * @param subdivisions is an 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
  34889. * @param precision is an 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
  34890. * @param scene defines the hosting scene
  34891. * @param updatable defines if the mesh must be flagged as updatable
  34892. * @returns a new Mesh
  34893. */
  34894. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  34895. var options = {
  34896. xmin: xmin,
  34897. zmin: zmin,
  34898. xmax: xmax,
  34899. zmax: zmax,
  34900. subdivisions: subdivisions,
  34901. precision: precision,
  34902. updatable: updatable
  34903. };
  34904. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  34905. };
  34906. /**
  34907. * Creates a ground mesh from a height map.
  34908. * Please consider using the same method from the MeshBuilder class instead
  34909. * @see http://doc.babylonjs.com/babylon101/height_map
  34910. * @param name defines the name of the mesh to create
  34911. * @param url sets the URL of the height map image resource
  34912. * @param width set the ground width size
  34913. * @param height set the ground height size
  34914. * @param subdivisions sets the number of subdivision per side
  34915. * @param minHeight is the minimum altitude on the ground
  34916. * @param maxHeight is the maximum altitude on the ground
  34917. * @param scene defines the hosting scene
  34918. * @param updatable defines if the mesh must be flagged as updatable
  34919. * @param onReady is a callback function that will be called once the mesh is built (the height map download can last some time)
  34920. * @param alphaFilter will filter any data where the alpha channel is below this value, defaults 0 (all data visible)
  34921. * @returns a new Mesh
  34922. */
  34923. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady, alphaFilter) {
  34924. var options = {
  34925. width: width,
  34926. height: height,
  34927. subdivisions: subdivisions,
  34928. minHeight: minHeight,
  34929. maxHeight: maxHeight,
  34930. updatable: updatable,
  34931. onReady: onReady,
  34932. alphaFilter: alphaFilter
  34933. };
  34934. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  34935. };
  34936. /**
  34937. * Creates a tube mesh.
  34938. * The tube is a parametric shape.
  34939. * It has no predefined shape. Its final shape will depend on the input parameters.
  34940. * Please consider using the same method from the MeshBuilder class instead
  34941. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  34942. * @param name defines the name of the mesh to create
  34943. * @param path is a required array of successive Vector3. It is the curve used as the axis of the tube
  34944. * @param radius sets the tube radius size
  34945. * @param tessellation is the number of sides on the tubular surface
  34946. * @param radiusFunction is a custom function. If it is not null, it overwrittes the parameter `radius`. 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
  34947. * @param 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
  34948. * @param scene defines the hosting scene
  34949. * @param updatable defines if the mesh must be flagged as updatable
  34950. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34951. * @param instance is an instance of an existing Tube object to be updated with the passed `pathArray` parameter (http://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#tube)
  34952. * @returns a new Mesh
  34953. */
  34954. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  34955. var options = {
  34956. path: path,
  34957. radius: radius,
  34958. tessellation: tessellation,
  34959. radiusFunction: radiusFunction,
  34960. arc: 1,
  34961. cap: cap,
  34962. updatable: updatable,
  34963. sideOrientation: sideOrientation,
  34964. instance: instance
  34965. };
  34966. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  34967. };
  34968. /**
  34969. * Creates a polyhedron mesh.
  34970. * Please consider using the same method from the MeshBuilder class instead.
  34971. * * 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
  34972. * * The parameter `size` (positive float, default 1) sets the polygon size
  34973. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  34974. * * 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`
  34975. * * 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
  34976. * * 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)`)
  34977. * * 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
  34978. * * 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
  34979. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34980. * * 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
  34981. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  34982. * @param name defines the name of the mesh to create
  34983. * @param options defines the options used to create the mesh
  34984. * @param scene defines the hosting scene
  34985. * @returns a new Mesh
  34986. */
  34987. Mesh.CreatePolyhedron = function (name, options, scene) {
  34988. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  34989. };
  34990. /**
  34991. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  34992. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  34993. * * 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`)
  34994. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  34995. * * 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
  34996. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34997. * * 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
  34998. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  34999. * @param name defines the name of the mesh
  35000. * @param options defines the options used to create the mesh
  35001. * @param scene defines the hosting scene
  35002. * @returns a new Mesh
  35003. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  35004. */
  35005. Mesh.CreateIcoSphere = function (name, options, scene) {
  35006. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  35007. };
  35008. /**
  35009. * Creates a decal mesh.
  35010. * Please consider using the same method from the MeshBuilder class instead.
  35011. * A decal is a mesh usually applied as a model onto the surface of another mesh
  35012. * @param name defines the name of the mesh
  35013. * @param sourceMesh defines the mesh receiving the decal
  35014. * @param position sets the position of the decal in world coordinates
  35015. * @param normal sets the normal of the mesh where the decal is applied onto in world coordinates
  35016. * @param size sets the decal scaling
  35017. * @param angle sets the angle to rotate the decal
  35018. * @returns a new Mesh
  35019. */
  35020. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  35021. var options = {
  35022. position: position,
  35023. normal: normal,
  35024. size: size,
  35025. angle: angle
  35026. };
  35027. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  35028. };
  35029. // Skeletons
  35030. /**
  35031. * Prepare internal position array for software CPU skinning
  35032. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh
  35033. */
  35034. Mesh.prototype.setPositionsForCPUSkinning = function () {
  35035. if (!this._sourcePositions) {
  35036. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35037. if (!source) {
  35038. return this._sourcePositions;
  35039. }
  35040. this._sourcePositions = new Float32Array(source);
  35041. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  35042. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  35043. }
  35044. }
  35045. return this._sourcePositions;
  35046. };
  35047. /**
  35048. * Prepare internal normal array for software CPU skinning
  35049. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  35050. */
  35051. Mesh.prototype.setNormalsForCPUSkinning = function () {
  35052. if (!this._sourceNormals) {
  35053. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  35054. if (!source) {
  35055. return this._sourceNormals;
  35056. }
  35057. this._sourceNormals = new Float32Array(source);
  35058. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  35059. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  35060. }
  35061. }
  35062. return this._sourceNormals;
  35063. };
  35064. /**
  35065. * Updates the vertex buffer by applying transformation from the bones
  35066. * @param skeleton defines the skeleton to apply to current mesh
  35067. * @returns the current mesh
  35068. */
  35069. Mesh.prototype.applySkeleton = function (skeleton) {
  35070. if (!this.geometry) {
  35071. return this;
  35072. }
  35073. if (this.geometry._softwareSkinningFrameId == this.getScene().getFrameId()) {
  35074. return this;
  35075. }
  35076. this.geometry._softwareSkinningFrameId = this.getScene().getFrameId();
  35077. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  35078. return this;
  35079. }
  35080. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35081. return this;
  35082. }
  35083. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35084. return this;
  35085. }
  35086. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35087. return this;
  35088. }
  35089. if (!this._sourcePositions) {
  35090. var submeshes = this.subMeshes.slice();
  35091. this.setPositionsForCPUSkinning();
  35092. this.subMeshes = submeshes;
  35093. }
  35094. if (!this._sourceNormals) {
  35095. this.setNormalsForCPUSkinning();
  35096. }
  35097. // positionsData checks for not being Float32Array will only pass at most once
  35098. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35099. if (!positionsData) {
  35100. return this;
  35101. }
  35102. if (!(positionsData instanceof Float32Array)) {
  35103. positionsData = new Float32Array(positionsData);
  35104. }
  35105. // normalsData checks for not being Float32Array will only pass at most once
  35106. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  35107. if (!normalsData) {
  35108. return this;
  35109. }
  35110. if (!(normalsData instanceof Float32Array)) {
  35111. normalsData = new Float32Array(normalsData);
  35112. }
  35113. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  35114. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  35115. if (!matricesWeightsData || !matricesIndicesData) {
  35116. return this;
  35117. }
  35118. var needExtras = this.numBoneInfluencers > 4;
  35119. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  35120. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  35121. var skeletonMatrices = skeleton.getTransformMatrices(this);
  35122. var tempVector3 = BABYLON.Vector3.Zero();
  35123. var finalMatrix = new BABYLON.Matrix();
  35124. var tempMatrix = new BABYLON.Matrix();
  35125. var matWeightIdx = 0;
  35126. var inf;
  35127. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  35128. var weight;
  35129. for (inf = 0; inf < 4; inf++) {
  35130. weight = matricesWeightsData[matWeightIdx + inf];
  35131. if (weight > 0) {
  35132. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  35133. finalMatrix.addToSelf(tempMatrix);
  35134. }
  35135. }
  35136. if (needExtras) {
  35137. for (inf = 0; inf < 4; inf++) {
  35138. weight = matricesWeightsExtraData[matWeightIdx + inf];
  35139. if (weight > 0) {
  35140. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  35141. finalMatrix.addToSelf(tempMatrix);
  35142. }
  35143. }
  35144. }
  35145. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  35146. tempVector3.toArray(positionsData, index);
  35147. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  35148. tempVector3.toArray(normalsData, index);
  35149. finalMatrix.reset();
  35150. }
  35151. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  35152. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  35153. return this;
  35154. };
  35155. // Tools
  35156. /**
  35157. * Returns an object containing a min and max Vector3 which are the minimum and maximum vectors of each mesh bounding box from the passed array, in the world coordinates
  35158. * @param meshes defines the list of meshes to scan
  35159. * @returns an object `{min:` Vector3`, max:` Vector3`}`
  35160. */
  35161. Mesh.MinMax = function (meshes) {
  35162. var minVector = null;
  35163. var maxVector = null;
  35164. meshes.forEach(function (mesh, index, array) {
  35165. var boundingInfo = mesh.getBoundingInfo();
  35166. var boundingBox = boundingInfo.boundingBox;
  35167. if (!minVector || !maxVector) {
  35168. minVector = boundingBox.minimumWorld;
  35169. maxVector = boundingBox.maximumWorld;
  35170. }
  35171. else {
  35172. minVector.minimizeInPlace(boundingBox.minimumWorld);
  35173. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  35174. }
  35175. });
  35176. if (!minVector || !maxVector) {
  35177. return {
  35178. min: BABYLON.Vector3.Zero(),
  35179. max: BABYLON.Vector3.Zero()
  35180. };
  35181. }
  35182. return {
  35183. min: minVector,
  35184. max: maxVector
  35185. };
  35186. };
  35187. /**
  35188. * Returns the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array
  35189. * @param meshesOrMinMaxVector could be an array of meshes or a `{min:` Vector3`, max:` Vector3`}` object
  35190. * @returns a vector3
  35191. */
  35192. Mesh.Center = function (meshesOrMinMaxVector) {
  35193. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  35194. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  35195. };
  35196. /**
  35197. * Merge the array of meshes into a single mesh for performance reasons.
  35198. * @param meshes defines he vertices source. They should all be of the same material. Entries can empty
  35199. * @param disposeSource when true (default), dispose of the vertices from the source meshes
  35200. * @param allow32BitsIndices when the sum of the vertices > 64k, this must be set to true
  35201. * @param meshSubclass when set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  35202. * @param subdivideWithSubMeshes when true (false default), subdivide mesh to his subMesh array with meshes source.
  35203. * @returns a new mesh
  35204. */
  35205. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  35206. if (disposeSource === void 0) { disposeSource = true; }
  35207. var index;
  35208. if (!allow32BitsIndices) {
  35209. var totalVertices = 0;
  35210. // Counting vertices
  35211. for (index = 0; index < meshes.length; index++) {
  35212. if (meshes[index]) {
  35213. totalVertices += meshes[index].getTotalVertices();
  35214. if (totalVertices > 65536) {
  35215. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  35216. return null;
  35217. }
  35218. }
  35219. }
  35220. }
  35221. // Merge
  35222. var vertexData = null;
  35223. var otherVertexData;
  35224. var indiceArray = new Array();
  35225. var source = null;
  35226. for (index = 0; index < meshes.length; index++) {
  35227. if (meshes[index]) {
  35228. var wm = meshes[index].computeWorldMatrix(true);
  35229. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  35230. otherVertexData.transform(wm);
  35231. if (vertexData) {
  35232. vertexData.merge(otherVertexData, allow32BitsIndices);
  35233. }
  35234. else {
  35235. vertexData = otherVertexData;
  35236. source = meshes[index];
  35237. }
  35238. if (subdivideWithSubMeshes) {
  35239. indiceArray.push(meshes[index].getTotalIndices());
  35240. }
  35241. }
  35242. }
  35243. source = source;
  35244. if (!meshSubclass) {
  35245. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  35246. }
  35247. vertexData.applyToMesh(meshSubclass);
  35248. // Setting properties
  35249. meshSubclass.material = source.material;
  35250. meshSubclass.checkCollisions = source.checkCollisions;
  35251. // Cleaning
  35252. if (disposeSource) {
  35253. for (index = 0; index < meshes.length; index++) {
  35254. if (meshes[index]) {
  35255. meshes[index].dispose();
  35256. }
  35257. }
  35258. }
  35259. // Subdivide
  35260. if (subdivideWithSubMeshes) {
  35261. //-- removal of global submesh
  35262. meshSubclass.releaseSubMeshes();
  35263. index = 0;
  35264. var offset = 0;
  35265. //-- apply subdivision according to index table
  35266. while (index < indiceArray.length) {
  35267. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  35268. offset += indiceArray[index];
  35269. index++;
  35270. }
  35271. }
  35272. return meshSubclass;
  35273. };
  35274. // Consts
  35275. /**
  35276. * Mesh side orientation : usually the external or front surface
  35277. */
  35278. Mesh.FRONTSIDE = 0;
  35279. /**
  35280. * Mesh side orientation : usually the internal or back surface
  35281. */
  35282. Mesh.BACKSIDE = 1;
  35283. /**
  35284. * Mesh side orientation : both internal and external or front and back surfaces
  35285. */
  35286. Mesh.DOUBLESIDE = 2;
  35287. /**
  35288. * Mesh side orientation : by default, `FRONTSIDE`
  35289. */
  35290. Mesh.DEFAULTSIDE = 0;
  35291. /**
  35292. * Mesh cap setting : no cap
  35293. */
  35294. Mesh.NO_CAP = 0;
  35295. /**
  35296. * Mesh cap setting : one cap at the beginning of the mesh
  35297. */
  35298. Mesh.CAP_START = 1;
  35299. /**
  35300. * Mesh cap setting : one cap at the end of the mesh
  35301. */
  35302. Mesh.CAP_END = 2;
  35303. /**
  35304. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  35305. */
  35306. Mesh.CAP_ALL = 3;
  35307. return Mesh;
  35308. }(BABYLON.AbstractMesh));
  35309. BABYLON.Mesh = Mesh;
  35310. })(BABYLON || (BABYLON = {}));
  35311. //# sourceMappingURL=babylon.mesh.js.map
  35312. var BABYLON;
  35313. (function (BABYLON) {
  35314. /**
  35315. * Base class for submeshes
  35316. */
  35317. var BaseSubMesh = /** @class */ (function () {
  35318. function BaseSubMesh() {
  35319. }
  35320. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  35321. /**
  35322. * Gets associated effect
  35323. */
  35324. get: function () {
  35325. return this._materialEffect;
  35326. },
  35327. enumerable: true,
  35328. configurable: true
  35329. });
  35330. /**
  35331. * Sets associated effect (effect used to render this submesh)
  35332. * @param effect defines the effect to associate with
  35333. * @param defines defines the set of defines used to compile this effect
  35334. */
  35335. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  35336. if (defines === void 0) { defines = null; }
  35337. if (this._materialEffect === effect) {
  35338. if (!effect) {
  35339. this._materialDefines = null;
  35340. }
  35341. return;
  35342. }
  35343. this._materialDefines = defines;
  35344. this._materialEffect = effect;
  35345. };
  35346. return BaseSubMesh;
  35347. }());
  35348. BABYLON.BaseSubMesh = BaseSubMesh;
  35349. /**
  35350. * Defines a subdivision inside a mesh
  35351. */
  35352. var SubMesh = /** @class */ (function (_super) {
  35353. __extends(SubMesh, _super);
  35354. /**
  35355. * Creates a new submesh
  35356. * @param materialIndex defines the material index to use
  35357. * @param verticesStart defines vertex index start
  35358. * @param verticesCount defines vertices count
  35359. * @param indexStart defines index start
  35360. * @param indexCount defines indices count
  35361. * @param mesh defines the parent mesh
  35362. * @param renderingMesh defines an optional rendering mesh
  35363. * @param createBoundingBox defines if bounding box should be created for this submesh
  35364. */
  35365. function SubMesh(
  35366. /** the material index to use */
  35367. materialIndex,
  35368. /** vertex index start */
  35369. verticesStart,
  35370. /** vertices count */
  35371. verticesCount,
  35372. /** index start */
  35373. indexStart,
  35374. /** indices count */
  35375. indexCount, mesh, renderingMesh, createBoundingBox) {
  35376. if (createBoundingBox === void 0) { createBoundingBox = true; }
  35377. var _this = _super.call(this) || this;
  35378. _this.materialIndex = materialIndex;
  35379. _this.verticesStart = verticesStart;
  35380. _this.verticesCount = verticesCount;
  35381. _this.indexStart = indexStart;
  35382. _this.indexCount = indexCount;
  35383. /** @hidden */
  35384. _this._renderId = 0;
  35385. _this._mesh = mesh;
  35386. _this._renderingMesh = renderingMesh || mesh;
  35387. mesh.subMeshes.push(_this);
  35388. _this._trianglePlanes = [];
  35389. _this._id = mesh.subMeshes.length - 1;
  35390. if (createBoundingBox) {
  35391. _this.refreshBoundingInfo();
  35392. mesh.computeWorldMatrix(true);
  35393. }
  35394. return _this;
  35395. }
  35396. /**
  35397. * Add a new submesh to a mesh
  35398. * @param materialIndex defines the material index to use
  35399. * @param verticesStart defines vertex index start
  35400. * @param verticesCount defines vertices count
  35401. * @param indexStart defines index start
  35402. * @param indexCount defines indices count
  35403. * @param mesh defines the parent mesh
  35404. * @param renderingMesh defines an optional rendering mesh
  35405. * @param createBoundingBox defines if bounding box should be created for this submesh
  35406. * @returns the new submesh
  35407. */
  35408. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  35409. if (createBoundingBox === void 0) { createBoundingBox = true; }
  35410. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  35411. };
  35412. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  35413. /**
  35414. * Returns true if this submesh covers the entire parent mesh
  35415. * @ignorenaming
  35416. */
  35417. get: function () {
  35418. return (this.verticesStart === 0 && this.verticesCount === this._mesh.getTotalVertices());
  35419. },
  35420. enumerable: true,
  35421. configurable: true
  35422. });
  35423. /**
  35424. * Returns the submesh BoudingInfo object
  35425. * @returns current bounding info (or mesh's one if the submesh is global)
  35426. */
  35427. SubMesh.prototype.getBoundingInfo = function () {
  35428. if (this.IsGlobal) {
  35429. return this._mesh.getBoundingInfo();
  35430. }
  35431. return this._boundingInfo;
  35432. };
  35433. /**
  35434. * Sets the submesh BoundingInfo
  35435. * @param boundingInfo defines the new bounding info to use
  35436. * @returns the SubMesh
  35437. */
  35438. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  35439. this._boundingInfo = boundingInfo;
  35440. return this;
  35441. };
  35442. /**
  35443. * Returns the mesh of the current submesh
  35444. * @return the parent mesh
  35445. */
  35446. SubMesh.prototype.getMesh = function () {
  35447. return this._mesh;
  35448. };
  35449. /**
  35450. * Returns the rendering mesh of the submesh
  35451. * @returns the rendering mesh (could be different from parent mesh)
  35452. */
  35453. SubMesh.prototype.getRenderingMesh = function () {
  35454. return this._renderingMesh;
  35455. };
  35456. /**
  35457. * Returns the submesh material
  35458. * @returns null or the current material
  35459. */
  35460. SubMesh.prototype.getMaterial = function () {
  35461. var rootMaterial = this._renderingMesh.material;
  35462. if (rootMaterial === null || rootMaterial === undefined) {
  35463. return this._mesh.getScene().defaultMaterial;
  35464. }
  35465. else if (rootMaterial.getSubMaterial) {
  35466. var multiMaterial = rootMaterial;
  35467. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  35468. if (this._currentMaterial !== effectiveMaterial) {
  35469. this._currentMaterial = effectiveMaterial;
  35470. this._materialDefines = null;
  35471. }
  35472. return effectiveMaterial;
  35473. }
  35474. return rootMaterial;
  35475. };
  35476. // Methods
  35477. /**
  35478. * Sets a new updated BoundingInfo object to the submesh
  35479. * @returns the SubMesh
  35480. */
  35481. SubMesh.prototype.refreshBoundingInfo = function () {
  35482. this._lastColliderWorldVertices = null;
  35483. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  35484. return this;
  35485. }
  35486. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35487. if (!data) {
  35488. this._boundingInfo = this._mesh.getBoundingInfo();
  35489. return this;
  35490. }
  35491. var indices = this._renderingMesh.getIndices();
  35492. var extend;
  35493. //is this the only submesh?
  35494. if (this.indexStart === 0 && this.indexCount === indices.length) {
  35495. var boundingInfo = this._renderingMesh.getBoundingInfo();
  35496. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  35497. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  35498. }
  35499. else {
  35500. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  35501. }
  35502. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  35503. return this;
  35504. };
  35505. /** @hidden */
  35506. SubMesh.prototype._checkCollision = function (collider) {
  35507. var boundingInfo = this.getBoundingInfo();
  35508. return boundingInfo._checkCollision(collider);
  35509. };
  35510. /**
  35511. * Updates the submesh BoundingInfo
  35512. * @param world defines the world matrix to use to update the bounding info
  35513. * @returns the submesh
  35514. */
  35515. SubMesh.prototype.updateBoundingInfo = function (world) {
  35516. var boundingInfo = this.getBoundingInfo();
  35517. if (!boundingInfo) {
  35518. this.refreshBoundingInfo();
  35519. boundingInfo = this.getBoundingInfo();
  35520. }
  35521. boundingInfo.update(world);
  35522. return this;
  35523. };
  35524. /**
  35525. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  35526. * @param frustumPlanes defines the frustum planes
  35527. * @returns true if the submesh is intersecting with the frustum
  35528. */
  35529. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  35530. var boundingInfo = this.getBoundingInfo();
  35531. if (!boundingInfo) {
  35532. return false;
  35533. }
  35534. return boundingInfo.isInFrustum(frustumPlanes, this._mesh.cullingStrategy);
  35535. };
  35536. /**
  35537. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes
  35538. * @param frustumPlanes defines the frustum planes
  35539. * @returns true if the submesh is inside the frustum
  35540. */
  35541. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  35542. var boundingInfo = this.getBoundingInfo();
  35543. if (!boundingInfo) {
  35544. return false;
  35545. }
  35546. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  35547. };
  35548. /**
  35549. * Renders the submesh
  35550. * @param enableAlphaMode defines if alpha needs to be used
  35551. * @returns the submesh
  35552. */
  35553. SubMesh.prototype.render = function (enableAlphaMode) {
  35554. this._renderingMesh.render(this, enableAlphaMode);
  35555. return this;
  35556. };
  35557. /**
  35558. * @hidden
  35559. */
  35560. SubMesh.prototype._getLinesIndexBuffer = function (indices, engine) {
  35561. if (!this._linesIndexBuffer) {
  35562. var linesIndices = [];
  35563. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  35564. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  35565. }
  35566. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  35567. this._linesIndexCount = linesIndices.length;
  35568. }
  35569. return this._linesIndexBuffer;
  35570. };
  35571. /**
  35572. * Checks if the submesh intersects with a ray
  35573. * @param ray defines the ray to test
  35574. * @returns true is the passed ray intersects the submesh bounding box
  35575. */
  35576. SubMesh.prototype.canIntersects = function (ray) {
  35577. var boundingInfo = this.getBoundingInfo();
  35578. if (!boundingInfo) {
  35579. return false;
  35580. }
  35581. return ray.intersectsBox(boundingInfo.boundingBox);
  35582. };
  35583. /**
  35584. * Intersects current submesh with a ray
  35585. * @param ray defines the ray to test
  35586. * @param positions defines mesh's positions array
  35587. * @param indices defines mesh's indices array
  35588. * @param fastCheck defines if only bounding info should be used
  35589. * @returns intersection info or null if no intersection
  35590. */
  35591. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  35592. var intersectInfo = null;
  35593. var material = this.getMaterial();
  35594. if (!material) {
  35595. return null;
  35596. }
  35597. switch (material.fillMode) {
  35598. case BABYLON.Material.PointListDrawMode:
  35599. case BABYLON.Material.LineListDrawMode:
  35600. case BABYLON.Material.LineLoopDrawMode:
  35601. case BABYLON.Material.LineStripDrawMode:
  35602. case BABYLON.Material.TriangleFanDrawMode:
  35603. case BABYLON.Material.TriangleStripDrawMode:
  35604. return null;
  35605. }
  35606. // LineMesh first as it's also a Mesh...
  35607. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  35608. var lineMesh = this._mesh;
  35609. // Line test
  35610. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  35611. var p0 = positions[indices[index]];
  35612. var p1 = positions[indices[index + 1]];
  35613. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  35614. if (length < 0) {
  35615. continue;
  35616. }
  35617. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  35618. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  35619. if (fastCheck) {
  35620. break;
  35621. }
  35622. }
  35623. }
  35624. }
  35625. else {
  35626. // Triangles test
  35627. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  35628. var p0 = positions[indices[index]];
  35629. var p1 = positions[indices[index + 1]];
  35630. var p2 = positions[indices[index + 2]];
  35631. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  35632. if (currentIntersectInfo) {
  35633. if (currentIntersectInfo.distance < 0) {
  35634. continue;
  35635. }
  35636. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  35637. intersectInfo = currentIntersectInfo;
  35638. intersectInfo.faceId = index / 3;
  35639. if (fastCheck) {
  35640. break;
  35641. }
  35642. }
  35643. }
  35644. }
  35645. }
  35646. return intersectInfo;
  35647. };
  35648. /** @hidden */
  35649. SubMesh.prototype._rebuild = function () {
  35650. if (this._linesIndexBuffer) {
  35651. this._linesIndexBuffer = null;
  35652. }
  35653. };
  35654. // Clone
  35655. /**
  35656. * Creates a new submesh from the passed mesh
  35657. * @param newMesh defines the new hosting mesh
  35658. * @param newRenderingMesh defines an optional rendering mesh
  35659. * @returns the new submesh
  35660. */
  35661. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  35662. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  35663. if (!this.IsGlobal) {
  35664. var boundingInfo = this.getBoundingInfo();
  35665. if (!boundingInfo) {
  35666. return result;
  35667. }
  35668. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  35669. }
  35670. return result;
  35671. };
  35672. // Dispose
  35673. /**
  35674. * Release associated resources
  35675. */
  35676. SubMesh.prototype.dispose = function () {
  35677. if (this._linesIndexBuffer) {
  35678. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  35679. this._linesIndexBuffer = null;
  35680. }
  35681. // Remove from mesh
  35682. var index = this._mesh.subMeshes.indexOf(this);
  35683. this._mesh.subMeshes.splice(index, 1);
  35684. };
  35685. // Statics
  35686. /**
  35687. * Creates a new submesh from indices data
  35688. * @param materialIndex the index of the main mesh material
  35689. * @param startIndex the index where to start the copy in the mesh indices array
  35690. * @param indexCount the number of indices to copy then from the startIndex
  35691. * @param mesh the main mesh to create the submesh from
  35692. * @param renderingMesh the optional rendering mesh
  35693. * @returns a new submesh
  35694. */
  35695. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  35696. var minVertexIndex = Number.MAX_VALUE;
  35697. var maxVertexIndex = -Number.MAX_VALUE;
  35698. renderingMesh = (renderingMesh || mesh);
  35699. var indices = renderingMesh.getIndices();
  35700. for (var index = startIndex; index < startIndex + indexCount; index++) {
  35701. var vertexIndex = indices[index];
  35702. if (vertexIndex < minVertexIndex)
  35703. minVertexIndex = vertexIndex;
  35704. if (vertexIndex > maxVertexIndex)
  35705. maxVertexIndex = vertexIndex;
  35706. }
  35707. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  35708. };
  35709. return SubMesh;
  35710. }(BaseSubMesh));
  35711. BABYLON.SubMesh = SubMesh;
  35712. })(BABYLON || (BABYLON = {}));
  35713. //# sourceMappingURL=babylon.subMesh.js.map
  35714. var __assign = (this && this.__assign) || function () {
  35715. __assign = Object.assign || function(t) {
  35716. for (var s, i = 1, n = arguments.length; i < n; i++) {
  35717. s = arguments[i];
  35718. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  35719. t[p] = s[p];
  35720. }
  35721. return t;
  35722. };
  35723. return __assign.apply(this, arguments);
  35724. };
  35725. var BABYLON;
  35726. (function (BABYLON) {
  35727. /**
  35728. * Manages the defines for the Material
  35729. */
  35730. var MaterialDefines = /** @class */ (function () {
  35731. function MaterialDefines() {
  35732. this._isDirty = true;
  35733. /** @hidden */
  35734. this._areLightsDirty = true;
  35735. /** @hidden */
  35736. this._areAttributesDirty = true;
  35737. /** @hidden */
  35738. this._areTexturesDirty = true;
  35739. /** @hidden */
  35740. this._areFresnelDirty = true;
  35741. /** @hidden */
  35742. this._areMiscDirty = true;
  35743. /** @hidden */
  35744. this._areImageProcessingDirty = true;
  35745. /** @hidden */
  35746. this._normals = false;
  35747. /** @hidden */
  35748. this._uvs = false;
  35749. /** @hidden */
  35750. this._needNormals = false;
  35751. /** @hidden */
  35752. this._needUVs = false;
  35753. }
  35754. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  35755. /**
  35756. * Specifies if the material needs to be re-calculated
  35757. */
  35758. get: function () {
  35759. return this._isDirty;
  35760. },
  35761. enumerable: true,
  35762. configurable: true
  35763. });
  35764. /**
  35765. * Marks the material to indicate that it has been re-calculated
  35766. */
  35767. MaterialDefines.prototype.markAsProcessed = function () {
  35768. this._isDirty = false;
  35769. this._areAttributesDirty = false;
  35770. this._areTexturesDirty = false;
  35771. this._areFresnelDirty = false;
  35772. this._areLightsDirty = false;
  35773. this._areMiscDirty = false;
  35774. this._areImageProcessingDirty = false;
  35775. };
  35776. /**
  35777. * Marks the material to indicate that it needs to be re-calculated
  35778. */
  35779. MaterialDefines.prototype.markAsUnprocessed = function () {
  35780. this._isDirty = true;
  35781. };
  35782. /**
  35783. * Marks the material to indicate all of its defines need to be re-calculated
  35784. */
  35785. MaterialDefines.prototype.markAllAsDirty = function () {
  35786. this._areTexturesDirty = true;
  35787. this._areAttributesDirty = true;
  35788. this._areLightsDirty = true;
  35789. this._areFresnelDirty = true;
  35790. this._areMiscDirty = true;
  35791. this._areImageProcessingDirty = true;
  35792. this._isDirty = true;
  35793. };
  35794. /**
  35795. * Marks the material to indicate that image processing needs to be re-calculated
  35796. */
  35797. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  35798. this._areImageProcessingDirty = true;
  35799. this._isDirty = true;
  35800. };
  35801. /**
  35802. * Marks the material to indicate the lights need to be re-calculated
  35803. */
  35804. MaterialDefines.prototype.markAsLightDirty = function () {
  35805. this._areLightsDirty = true;
  35806. this._isDirty = true;
  35807. };
  35808. /**
  35809. * Marks the attribute state as changed
  35810. */
  35811. MaterialDefines.prototype.markAsAttributesDirty = function () {
  35812. this._areAttributesDirty = true;
  35813. this._isDirty = true;
  35814. };
  35815. /**
  35816. * Marks the texture state as changed
  35817. */
  35818. MaterialDefines.prototype.markAsTexturesDirty = function () {
  35819. this._areTexturesDirty = true;
  35820. this._isDirty = true;
  35821. };
  35822. /**
  35823. * Marks the fresnel state as changed
  35824. */
  35825. MaterialDefines.prototype.markAsFresnelDirty = function () {
  35826. this._areFresnelDirty = true;
  35827. this._isDirty = true;
  35828. };
  35829. /**
  35830. * Marks the misc state as changed
  35831. */
  35832. MaterialDefines.prototype.markAsMiscDirty = function () {
  35833. this._areMiscDirty = true;
  35834. this._isDirty = true;
  35835. };
  35836. /**
  35837. * Rebuilds the material defines
  35838. */
  35839. MaterialDefines.prototype.rebuild = function () {
  35840. if (this._keys) {
  35841. delete this._keys;
  35842. }
  35843. this._keys = [];
  35844. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  35845. var key = _a[_i];
  35846. if (key[0] === "_") {
  35847. continue;
  35848. }
  35849. this._keys.push(key);
  35850. }
  35851. };
  35852. /**
  35853. * Specifies if two material defines are equal
  35854. * @param other - A material define instance to compare to
  35855. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  35856. */
  35857. MaterialDefines.prototype.isEqual = function (other) {
  35858. if (this._keys.length !== other._keys.length) {
  35859. return false;
  35860. }
  35861. for (var index = 0; index < this._keys.length; index++) {
  35862. var prop = this._keys[index];
  35863. if (this[prop] !== other[prop]) {
  35864. return false;
  35865. }
  35866. }
  35867. return true;
  35868. };
  35869. /**
  35870. * Clones this instance's defines to another instance
  35871. * @param other - material defines to clone values to
  35872. */
  35873. MaterialDefines.prototype.cloneTo = function (other) {
  35874. if (this._keys.length !== other._keys.length) {
  35875. other._keys = this._keys.slice(0);
  35876. }
  35877. for (var index = 0; index < this._keys.length; index++) {
  35878. var prop = this._keys[index];
  35879. other[prop] = this[prop];
  35880. }
  35881. };
  35882. /**
  35883. * Resets the material define values
  35884. */
  35885. MaterialDefines.prototype.reset = function () {
  35886. for (var index = 0; index < this._keys.length; index++) {
  35887. var prop = this._keys[index];
  35888. var type = typeof this[prop];
  35889. switch (type) {
  35890. case "number":
  35891. this[prop] = 0;
  35892. break;
  35893. case "string":
  35894. this[prop] = "";
  35895. break;
  35896. default:
  35897. this[prop] = false;
  35898. break;
  35899. }
  35900. }
  35901. };
  35902. /**
  35903. * Converts the material define values to a string
  35904. * @returns - String of material define information
  35905. */
  35906. MaterialDefines.prototype.toString = function () {
  35907. var result = "";
  35908. for (var index = 0; index < this._keys.length; index++) {
  35909. var prop = this._keys[index];
  35910. var value = this[prop];
  35911. var type = typeof value;
  35912. switch (type) {
  35913. case "number":
  35914. case "string":
  35915. result += "#define " + prop + " " + value + "\n";
  35916. break;
  35917. default:
  35918. if (value) {
  35919. result += "#define " + prop + "\n";
  35920. }
  35921. break;
  35922. }
  35923. }
  35924. return result;
  35925. };
  35926. return MaterialDefines;
  35927. }());
  35928. BABYLON.MaterialDefines = MaterialDefines;
  35929. /**
  35930. * Base class for the main features of a material in Babylon.js
  35931. */
  35932. var Material = /** @class */ (function () {
  35933. /**
  35934. * Creates a material instance
  35935. * @param name defines the name of the material
  35936. * @param scene defines the scene to reference
  35937. * @param doNotAdd specifies if the material should be added to the scene
  35938. */
  35939. function Material(name, scene, doNotAdd) {
  35940. /**
  35941. * Specifies if the ready state should be checked on each call
  35942. */
  35943. this.checkReadyOnEveryCall = false;
  35944. /**
  35945. * Specifies if the ready state should be checked once
  35946. */
  35947. this.checkReadyOnlyOnce = false;
  35948. /**
  35949. * The state of the material
  35950. */
  35951. this.state = "";
  35952. /**
  35953. * The alpha value of the material
  35954. */
  35955. this._alpha = 1.0;
  35956. /**
  35957. * Specifies if back face culling is enabled
  35958. */
  35959. this._backFaceCulling = true;
  35960. /**
  35961. * Specifies if the material should be serialized
  35962. */
  35963. this.doNotSerialize = false;
  35964. /**
  35965. * Specifies if the effect should be stored on sub meshes
  35966. */
  35967. this.storeEffectOnSubMeshes = false;
  35968. /**
  35969. * An event triggered when the material is disposed
  35970. */
  35971. this.onDisposeObservable = new BABYLON.Observable();
  35972. /**
  35973. * Stores the value of the alpha mode
  35974. */
  35975. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  35976. /**
  35977. * Stores the state of the need depth pre-pass value
  35978. */
  35979. this._needDepthPrePass = false;
  35980. /**
  35981. * Specifies if depth writing should be disabled
  35982. */
  35983. this.disableDepthWrite = false;
  35984. /**
  35985. * Specifies if depth writing should be forced
  35986. */
  35987. this.forceDepthWrite = false;
  35988. /**
  35989. * Specifies if there should be a separate pass for culling
  35990. */
  35991. this.separateCullingPass = false;
  35992. /**
  35993. * Stores the state specifing if fog should be enabled
  35994. */
  35995. this._fogEnabled = true;
  35996. /**
  35997. * Stores the size of points
  35998. */
  35999. this.pointSize = 1.0;
  36000. /**
  36001. * Stores the z offset value
  36002. */
  36003. this.zOffset = 0;
  36004. /**
  36005. * @hidden
  36006. * Specifies if the material was previously ready
  36007. */
  36008. this._wasPreviouslyReady = false;
  36009. /**
  36010. * Stores the fill mode state
  36011. */
  36012. this._fillMode = Material.TriangleFillMode;
  36013. this.name = name;
  36014. this.id = name || BABYLON.Tools.RandomId();
  36015. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  36016. this.uniqueId = this._scene.getUniqueId();
  36017. if (this._scene.useRightHandedSystem) {
  36018. this.sideOrientation = Material.ClockWiseSideOrientation;
  36019. }
  36020. else {
  36021. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  36022. }
  36023. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  36024. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  36025. if (!doNotAdd) {
  36026. this._scene.materials.push(this);
  36027. this._scene.onNewMaterialAddedObservable.notifyObservers(this);
  36028. }
  36029. }
  36030. Object.defineProperty(Material, "TriangleFillMode", {
  36031. /**
  36032. * Returns the triangle fill mode
  36033. */
  36034. get: function () {
  36035. return Material._TriangleFillMode;
  36036. },
  36037. enumerable: true,
  36038. configurable: true
  36039. });
  36040. Object.defineProperty(Material, "WireFrameFillMode", {
  36041. /**
  36042. * Returns the wireframe mode
  36043. */
  36044. get: function () {
  36045. return Material._WireFrameFillMode;
  36046. },
  36047. enumerable: true,
  36048. configurable: true
  36049. });
  36050. Object.defineProperty(Material, "PointFillMode", {
  36051. /**
  36052. * Returns the point fill mode
  36053. */
  36054. get: function () {
  36055. return Material._PointFillMode;
  36056. },
  36057. enumerable: true,
  36058. configurable: true
  36059. });
  36060. Object.defineProperty(Material, "PointListDrawMode", {
  36061. /**
  36062. * Returns the point list draw mode
  36063. */
  36064. get: function () {
  36065. return Material._PointListDrawMode;
  36066. },
  36067. enumerable: true,
  36068. configurable: true
  36069. });
  36070. Object.defineProperty(Material, "LineListDrawMode", {
  36071. /**
  36072. * Returns the line list draw mode
  36073. */
  36074. get: function () {
  36075. return Material._LineListDrawMode;
  36076. },
  36077. enumerable: true,
  36078. configurable: true
  36079. });
  36080. Object.defineProperty(Material, "LineLoopDrawMode", {
  36081. /**
  36082. * Returns the line loop draw mode
  36083. */
  36084. get: function () {
  36085. return Material._LineLoopDrawMode;
  36086. },
  36087. enumerable: true,
  36088. configurable: true
  36089. });
  36090. Object.defineProperty(Material, "LineStripDrawMode", {
  36091. /**
  36092. * Returns the line strip draw mode
  36093. */
  36094. get: function () {
  36095. return Material._LineStripDrawMode;
  36096. },
  36097. enumerable: true,
  36098. configurable: true
  36099. });
  36100. Object.defineProperty(Material, "TriangleStripDrawMode", {
  36101. /**
  36102. * Returns the triangle strip draw mode
  36103. */
  36104. get: function () {
  36105. return Material._TriangleStripDrawMode;
  36106. },
  36107. enumerable: true,
  36108. configurable: true
  36109. });
  36110. Object.defineProperty(Material, "TriangleFanDrawMode", {
  36111. /**
  36112. * Returns the triangle fan draw mode
  36113. */
  36114. get: function () {
  36115. return Material._TriangleFanDrawMode;
  36116. },
  36117. enumerable: true,
  36118. configurable: true
  36119. });
  36120. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  36121. /**
  36122. * Returns the clock-wise side orientation
  36123. */
  36124. get: function () {
  36125. return Material._ClockWiseSideOrientation;
  36126. },
  36127. enumerable: true,
  36128. configurable: true
  36129. });
  36130. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  36131. /**
  36132. * Returns the counter clock-wise side orientation
  36133. */
  36134. get: function () {
  36135. return Material._CounterClockWiseSideOrientation;
  36136. },
  36137. enumerable: true,
  36138. configurable: true
  36139. });
  36140. Object.defineProperty(Material.prototype, "alpha", {
  36141. /**
  36142. * Gets the alpha value of the material
  36143. */
  36144. get: function () {
  36145. return this._alpha;
  36146. },
  36147. /**
  36148. * Sets the alpha value of the material
  36149. */
  36150. set: function (value) {
  36151. if (this._alpha === value) {
  36152. return;
  36153. }
  36154. this._alpha = value;
  36155. this.markAsDirty(Material.MiscDirtyFlag);
  36156. },
  36157. enumerable: true,
  36158. configurable: true
  36159. });
  36160. Object.defineProperty(Material.prototype, "backFaceCulling", {
  36161. /**
  36162. * Gets the back-face culling state
  36163. */
  36164. get: function () {
  36165. return this._backFaceCulling;
  36166. },
  36167. /**
  36168. * Sets the back-face culling state
  36169. */
  36170. set: function (value) {
  36171. if (this._backFaceCulling === value) {
  36172. return;
  36173. }
  36174. this._backFaceCulling = value;
  36175. this.markAsDirty(Material.TextureDirtyFlag);
  36176. },
  36177. enumerable: true,
  36178. configurable: true
  36179. });
  36180. Object.defineProperty(Material.prototype, "hasRenderTargetTextures", {
  36181. /**
  36182. * Gets a boolean indicating that current material needs to register RTT
  36183. */
  36184. get: function () {
  36185. return false;
  36186. },
  36187. enumerable: true,
  36188. configurable: true
  36189. });
  36190. Object.defineProperty(Material.prototype, "onDispose", {
  36191. /**
  36192. * Called during a dispose event
  36193. */
  36194. set: function (callback) {
  36195. if (this._onDisposeObserver) {
  36196. this.onDisposeObservable.remove(this._onDisposeObserver);
  36197. }
  36198. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  36199. },
  36200. enumerable: true,
  36201. configurable: true
  36202. });
  36203. Object.defineProperty(Material.prototype, "onBindObservable", {
  36204. /**
  36205. * An event triggered when the material is bound
  36206. */
  36207. get: function () {
  36208. if (!this._onBindObservable) {
  36209. this._onBindObservable = new BABYLON.Observable();
  36210. }
  36211. return this._onBindObservable;
  36212. },
  36213. enumerable: true,
  36214. configurable: true
  36215. });
  36216. Object.defineProperty(Material.prototype, "onBind", {
  36217. /**
  36218. * Called during a bind event
  36219. */
  36220. set: function (callback) {
  36221. if (this._onBindObserver) {
  36222. this.onBindObservable.remove(this._onBindObserver);
  36223. }
  36224. this._onBindObserver = this.onBindObservable.add(callback);
  36225. },
  36226. enumerable: true,
  36227. configurable: true
  36228. });
  36229. Object.defineProperty(Material.prototype, "onUnBindObservable", {
  36230. /**
  36231. * An event triggered when the material is unbound
  36232. */
  36233. get: function () {
  36234. if (!this._onUnBindObservable) {
  36235. this._onUnBindObservable = new BABYLON.Observable();
  36236. }
  36237. return this._onUnBindObservable;
  36238. },
  36239. enumerable: true,
  36240. configurable: true
  36241. });
  36242. Object.defineProperty(Material.prototype, "alphaMode", {
  36243. /**
  36244. * Gets the value of the alpha mode
  36245. */
  36246. get: function () {
  36247. return this._alphaMode;
  36248. },
  36249. /**
  36250. * Sets the value of the alpha mode.
  36251. *
  36252. * | Value | Type | Description |
  36253. * | --- | --- | --- |
  36254. * | 0 | ALPHA_DISABLE | |
  36255. * | 1 | ALPHA_ADD | |
  36256. * | 2 | ALPHA_COMBINE | |
  36257. * | 3 | ALPHA_SUBTRACT | |
  36258. * | 4 | ALPHA_MULTIPLY | |
  36259. * | 5 | ALPHA_MAXIMIZED | |
  36260. * | 6 | ALPHA_ONEONE | |
  36261. * | 7 | ALPHA_PREMULTIPLIED | |
  36262. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  36263. * | 9 | ALPHA_INTERPOLATE | |
  36264. * | 10 | ALPHA_SCREENMODE | |
  36265. *
  36266. */
  36267. set: function (value) {
  36268. if (this._alphaMode === value) {
  36269. return;
  36270. }
  36271. this._alphaMode = value;
  36272. this.markAsDirty(Material.TextureDirtyFlag);
  36273. },
  36274. enumerable: true,
  36275. configurable: true
  36276. });
  36277. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  36278. /**
  36279. * Gets the depth pre-pass value
  36280. */
  36281. get: function () {
  36282. return this._needDepthPrePass;
  36283. },
  36284. /**
  36285. * Sets the need depth pre-pass value
  36286. */
  36287. set: function (value) {
  36288. if (this._needDepthPrePass === value) {
  36289. return;
  36290. }
  36291. this._needDepthPrePass = value;
  36292. if (this._needDepthPrePass) {
  36293. this.checkReadyOnEveryCall = true;
  36294. }
  36295. },
  36296. enumerable: true,
  36297. configurable: true
  36298. });
  36299. Object.defineProperty(Material.prototype, "fogEnabled", {
  36300. /**
  36301. * Gets the value of the fog enabled state
  36302. */
  36303. get: function () {
  36304. return this._fogEnabled;
  36305. },
  36306. /**
  36307. * Sets the state for enabling fog
  36308. */
  36309. set: function (value) {
  36310. if (this._fogEnabled === value) {
  36311. return;
  36312. }
  36313. this._fogEnabled = value;
  36314. this.markAsDirty(Material.MiscDirtyFlag);
  36315. },
  36316. enumerable: true,
  36317. configurable: true
  36318. });
  36319. Object.defineProperty(Material.prototype, "wireframe", {
  36320. /**
  36321. * Gets a value specifying if wireframe mode is enabled
  36322. */
  36323. get: function () {
  36324. switch (this._fillMode) {
  36325. case Material.WireFrameFillMode:
  36326. case Material.LineListDrawMode:
  36327. case Material.LineLoopDrawMode:
  36328. case Material.LineStripDrawMode:
  36329. return true;
  36330. }
  36331. return this._scene.forceWireframe;
  36332. },
  36333. /**
  36334. * Sets the state of wireframe mode
  36335. */
  36336. set: function (value) {
  36337. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  36338. },
  36339. enumerable: true,
  36340. configurable: true
  36341. });
  36342. Object.defineProperty(Material.prototype, "pointsCloud", {
  36343. /**
  36344. * Gets the value specifying if point clouds are enabled
  36345. */
  36346. get: function () {
  36347. switch (this._fillMode) {
  36348. case Material.PointFillMode:
  36349. case Material.PointListDrawMode:
  36350. return true;
  36351. }
  36352. return this._scene.forcePointsCloud;
  36353. },
  36354. /**
  36355. * Sets the state of point cloud mode
  36356. */
  36357. set: function (value) {
  36358. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  36359. },
  36360. enumerable: true,
  36361. configurable: true
  36362. });
  36363. Object.defineProperty(Material.prototype, "fillMode", {
  36364. /**
  36365. * Gets the material fill mode
  36366. */
  36367. get: function () {
  36368. return this._fillMode;
  36369. },
  36370. /**
  36371. * Sets the material fill mode
  36372. */
  36373. set: function (value) {
  36374. if (this._fillMode === value) {
  36375. return;
  36376. }
  36377. this._fillMode = value;
  36378. this.markAsDirty(Material.MiscDirtyFlag);
  36379. },
  36380. enumerable: true,
  36381. configurable: true
  36382. });
  36383. /**
  36384. * Returns a string representation of the current material
  36385. * @param fullDetails defines a boolean indicating which levels of logging is desired
  36386. * @returns a string with material information
  36387. */
  36388. Material.prototype.toString = function (fullDetails) {
  36389. var ret = "Name: " + this.name;
  36390. if (fullDetails) {
  36391. }
  36392. return ret;
  36393. };
  36394. /**
  36395. * Gets the class name of the material
  36396. * @returns a string with the class name of the material
  36397. */
  36398. Material.prototype.getClassName = function () {
  36399. return "Material";
  36400. };
  36401. Object.defineProperty(Material.prototype, "isFrozen", {
  36402. /**
  36403. * Specifies if updates for the material been locked
  36404. */
  36405. get: function () {
  36406. return this.checkReadyOnlyOnce;
  36407. },
  36408. enumerable: true,
  36409. configurable: true
  36410. });
  36411. /**
  36412. * Locks updates for the material
  36413. */
  36414. Material.prototype.freeze = function () {
  36415. this.checkReadyOnlyOnce = true;
  36416. };
  36417. /**
  36418. * Unlocks updates for the material
  36419. */
  36420. Material.prototype.unfreeze = function () {
  36421. this.checkReadyOnlyOnce = false;
  36422. };
  36423. /**
  36424. * Specifies if the material is ready to be used
  36425. * @param mesh defines the mesh to check
  36426. * @param useInstances specifies if instances should be used
  36427. * @returns a boolean indicating if the material is ready to be used
  36428. */
  36429. Material.prototype.isReady = function (mesh, useInstances) {
  36430. return true;
  36431. };
  36432. /**
  36433. * Specifies that the submesh is ready to be used
  36434. * @param mesh defines the mesh to check
  36435. * @param subMesh defines which submesh to check
  36436. * @param useInstances specifies that instances should be used
  36437. * @returns a boolean indicating that the submesh is ready or not
  36438. */
  36439. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  36440. return false;
  36441. };
  36442. /**
  36443. * Returns the material effect
  36444. * @returns the effect associated with the material
  36445. */
  36446. Material.prototype.getEffect = function () {
  36447. return this._effect;
  36448. };
  36449. /**
  36450. * Returns the current scene
  36451. * @returns a Scene
  36452. */
  36453. Material.prototype.getScene = function () {
  36454. return this._scene;
  36455. };
  36456. /**
  36457. * Specifies if the material will require alpha blending
  36458. * @returns a boolean specifying if alpha blending is needed
  36459. */
  36460. Material.prototype.needAlphaBlending = function () {
  36461. return (this.alpha < 1.0);
  36462. };
  36463. /**
  36464. * Specifies if the mesh will require alpha blending
  36465. * @param mesh defines the mesh to check
  36466. * @returns a boolean specifying if alpha blending is needed for the mesh
  36467. */
  36468. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  36469. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  36470. };
  36471. /**
  36472. * Specifies if this material should be rendered in alpha test mode
  36473. * @returns a boolean specifying if an alpha test is needed.
  36474. */
  36475. Material.prototype.needAlphaTesting = function () {
  36476. return false;
  36477. };
  36478. /**
  36479. * Gets the texture used for the alpha test
  36480. * @returns the texture to use for alpha testing
  36481. */
  36482. Material.prototype.getAlphaTestTexture = function () {
  36483. return null;
  36484. };
  36485. /**
  36486. * Marks the material to indicate that it needs to be re-calculated
  36487. */
  36488. Material.prototype.markDirty = function () {
  36489. this._wasPreviouslyReady = false;
  36490. };
  36491. /** @hidden */
  36492. Material.prototype._preBind = function (effect, overrideOrientation) {
  36493. if (overrideOrientation === void 0) { overrideOrientation = null; }
  36494. var engine = this._scene.getEngine();
  36495. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  36496. var reverse = orientation === Material.ClockWiseSideOrientation;
  36497. engine.enableEffect(effect ? effect : this._effect);
  36498. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  36499. return reverse;
  36500. };
  36501. /**
  36502. * Binds the material to the mesh
  36503. * @param world defines the world transformation matrix
  36504. * @param mesh defines the mesh to bind the material to
  36505. */
  36506. Material.prototype.bind = function (world, mesh) {
  36507. };
  36508. /**
  36509. * Binds the submesh to the material
  36510. * @param world defines the world transformation matrix
  36511. * @param mesh defines the mesh containing the submesh
  36512. * @param subMesh defines the submesh to bind the material to
  36513. */
  36514. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  36515. };
  36516. /**
  36517. * Binds the world matrix to the material
  36518. * @param world defines the world transformation matrix
  36519. */
  36520. Material.prototype.bindOnlyWorldMatrix = function (world) {
  36521. };
  36522. /**
  36523. * Binds the scene's uniform buffer to the effect.
  36524. * @param effect defines the effect to bind to the scene uniform buffer
  36525. * @param sceneUbo defines the uniform buffer storing scene data
  36526. */
  36527. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  36528. sceneUbo.bindToEffect(effect, "Scene");
  36529. };
  36530. /**
  36531. * Binds the view matrix to the effect
  36532. * @param effect defines the effect to bind the view matrix to
  36533. */
  36534. Material.prototype.bindView = function (effect) {
  36535. if (!this._useUBO) {
  36536. effect.setMatrix("view", this.getScene().getViewMatrix());
  36537. }
  36538. else {
  36539. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  36540. }
  36541. };
  36542. /**
  36543. * Binds the view projection matrix to the effect
  36544. * @param effect defines the effect to bind the view projection matrix to
  36545. */
  36546. Material.prototype.bindViewProjection = function (effect) {
  36547. if (!this._useUBO) {
  36548. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  36549. }
  36550. else {
  36551. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  36552. }
  36553. };
  36554. /**
  36555. * Specifies if material alpha testing should be turned on for the mesh
  36556. * @param mesh defines the mesh to check
  36557. */
  36558. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  36559. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  36560. };
  36561. /**
  36562. * Processes to execute after binding the material to a mesh
  36563. * @param mesh defines the rendered mesh
  36564. */
  36565. Material.prototype._afterBind = function (mesh) {
  36566. this._scene._cachedMaterial = this;
  36567. if (mesh) {
  36568. this._scene._cachedVisibility = mesh.visibility;
  36569. }
  36570. else {
  36571. this._scene._cachedVisibility = 1;
  36572. }
  36573. if (this._onBindObservable && mesh) {
  36574. this._onBindObservable.notifyObservers(mesh);
  36575. }
  36576. if (this.disableDepthWrite) {
  36577. var engine = this._scene.getEngine();
  36578. this._cachedDepthWriteState = engine.getDepthWrite();
  36579. engine.setDepthWrite(false);
  36580. }
  36581. };
  36582. /**
  36583. * Unbinds the material from the mesh
  36584. */
  36585. Material.prototype.unbind = function () {
  36586. if (this._onUnBindObservable) {
  36587. this._onUnBindObservable.notifyObservers(this);
  36588. }
  36589. if (this.disableDepthWrite) {
  36590. var engine = this._scene.getEngine();
  36591. engine.setDepthWrite(this._cachedDepthWriteState);
  36592. }
  36593. };
  36594. /**
  36595. * Gets the active textures from the material
  36596. * @returns an array of textures
  36597. */
  36598. Material.prototype.getActiveTextures = function () {
  36599. return [];
  36600. };
  36601. /**
  36602. * Specifies if the material uses a texture
  36603. * @param texture defines the texture to check against the material
  36604. * @returns a boolean specifying if the material uses the texture
  36605. */
  36606. Material.prototype.hasTexture = function (texture) {
  36607. return false;
  36608. };
  36609. /**
  36610. * Makes a duplicate of the material, and gives it a new name
  36611. * @param name defines the new name for the duplicated material
  36612. * @returns the cloned material
  36613. */
  36614. Material.prototype.clone = function (name) {
  36615. return null;
  36616. };
  36617. /**
  36618. * Gets the meshes bound to the material
  36619. * @returns an array of meshes bound to the material
  36620. */
  36621. Material.prototype.getBindedMeshes = function () {
  36622. var result = new Array();
  36623. for (var index = 0; index < this._scene.meshes.length; index++) {
  36624. var mesh = this._scene.meshes[index];
  36625. if (mesh.material === this) {
  36626. result.push(mesh);
  36627. }
  36628. }
  36629. return result;
  36630. };
  36631. /**
  36632. * Force shader compilation
  36633. * @param mesh defines the mesh associated with this material
  36634. * @param onCompiled defines a function to execute once the material is compiled
  36635. * @param options defines the options to configure the compilation
  36636. */
  36637. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  36638. var _this = this;
  36639. var localOptions = __assign({ clipPlane: false }, options);
  36640. var subMesh = new BABYLON.BaseSubMesh();
  36641. var scene = this.getScene();
  36642. var checkReady = function () {
  36643. if (!_this._scene || !_this._scene.getEngine()) {
  36644. return;
  36645. }
  36646. if (subMesh._materialDefines) {
  36647. subMesh._materialDefines._renderId = -1;
  36648. }
  36649. var clipPlaneState = scene.clipPlane;
  36650. if (localOptions.clipPlane) {
  36651. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  36652. }
  36653. if (_this.storeEffectOnSubMeshes) {
  36654. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  36655. if (onCompiled) {
  36656. onCompiled(_this);
  36657. }
  36658. }
  36659. else {
  36660. setTimeout(checkReady, 16);
  36661. }
  36662. }
  36663. else {
  36664. if (_this.isReady(mesh)) {
  36665. if (onCompiled) {
  36666. onCompiled(_this);
  36667. }
  36668. }
  36669. else {
  36670. setTimeout(checkReady, 16);
  36671. }
  36672. }
  36673. if (localOptions.clipPlane) {
  36674. scene.clipPlane = clipPlaneState;
  36675. }
  36676. };
  36677. checkReady();
  36678. };
  36679. /**
  36680. * Force shader compilation
  36681. * @param mesh defines the mesh that will use this material
  36682. * @param options defines additional options for compiling the shaders
  36683. * @returns a promise that resolves when the compilation completes
  36684. */
  36685. Material.prototype.forceCompilationAsync = function (mesh, options) {
  36686. var _this = this;
  36687. return new Promise(function (resolve) {
  36688. _this.forceCompilation(mesh, function () {
  36689. resolve();
  36690. }, options);
  36691. });
  36692. };
  36693. /**
  36694. * Marks a define in the material to indicate that it needs to be re-computed
  36695. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  36696. */
  36697. Material.prototype.markAsDirty = function (flag) {
  36698. if (flag & Material.TextureDirtyFlag) {
  36699. this._markAllSubMeshesAsTexturesDirty();
  36700. }
  36701. if (flag & Material.LightDirtyFlag) {
  36702. this._markAllSubMeshesAsLightsDirty();
  36703. }
  36704. if (flag & Material.FresnelDirtyFlag) {
  36705. this._markAllSubMeshesAsFresnelDirty();
  36706. }
  36707. if (flag & Material.AttributesDirtyFlag) {
  36708. this._markAllSubMeshesAsAttributesDirty();
  36709. }
  36710. if (flag & Material.MiscDirtyFlag) {
  36711. this._markAllSubMeshesAsMiscDirty();
  36712. }
  36713. this.getScene().resetCachedMaterial();
  36714. };
  36715. /**
  36716. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  36717. * @param func defines a function which checks material defines against the submeshes
  36718. */
  36719. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  36720. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  36721. var mesh = _a[_i];
  36722. if (!mesh.subMeshes) {
  36723. continue;
  36724. }
  36725. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  36726. var subMesh = _c[_b];
  36727. if (subMesh.getMaterial() !== this) {
  36728. continue;
  36729. }
  36730. if (!subMesh._materialDefines) {
  36731. continue;
  36732. }
  36733. func(subMesh._materialDefines);
  36734. }
  36735. }
  36736. };
  36737. /**
  36738. * Indicates that image processing needs to be re-calculated for all submeshes
  36739. */
  36740. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  36741. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  36742. };
  36743. /**
  36744. * Indicates that textures need to be re-calculated for all submeshes
  36745. */
  36746. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  36747. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  36748. };
  36749. /**
  36750. * Indicates that fresnel needs to be re-calculated for all submeshes
  36751. */
  36752. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  36753. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  36754. };
  36755. /**
  36756. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  36757. */
  36758. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  36759. this._markAllSubMeshesAsDirty(function (defines) {
  36760. defines.markAsFresnelDirty();
  36761. defines.markAsMiscDirty();
  36762. });
  36763. };
  36764. /**
  36765. * Indicates that lights need to be re-calculated for all submeshes
  36766. */
  36767. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  36768. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  36769. };
  36770. /**
  36771. * Indicates that attributes need to be re-calculated for all submeshes
  36772. */
  36773. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  36774. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  36775. };
  36776. /**
  36777. * Indicates that misc needs to be re-calculated for all submeshes
  36778. */
  36779. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  36780. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  36781. };
  36782. /**
  36783. * Indicates that textures and misc need to be re-calculated for all submeshes
  36784. */
  36785. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  36786. this._markAllSubMeshesAsDirty(function (defines) {
  36787. defines.markAsTexturesDirty();
  36788. defines.markAsMiscDirty();
  36789. });
  36790. };
  36791. /**
  36792. * Disposes the material
  36793. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  36794. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  36795. */
  36796. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  36797. // Animations
  36798. this.getScene().stopAnimation(this);
  36799. this.getScene().freeProcessedMaterials();
  36800. // Remove from scene
  36801. var index = this._scene.materials.indexOf(this);
  36802. if (index >= 0) {
  36803. this._scene.materials.splice(index, 1);
  36804. }
  36805. this._scene.onMaterialRemovedObservable.notifyObservers(this);
  36806. // Remove from meshes
  36807. for (index = 0; index < this._scene.meshes.length; index++) {
  36808. var mesh = this._scene.meshes[index];
  36809. if (mesh.material === this) {
  36810. mesh.material = null;
  36811. if (mesh.geometry) {
  36812. var geometry = (mesh.geometry);
  36813. if (this.storeEffectOnSubMeshes) {
  36814. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  36815. var subMesh = _a[_i];
  36816. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  36817. if (forceDisposeEffect && subMesh._materialEffect) {
  36818. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  36819. }
  36820. }
  36821. }
  36822. else {
  36823. geometry._releaseVertexArrayObject(this._effect);
  36824. }
  36825. }
  36826. }
  36827. }
  36828. this._uniformBuffer.dispose();
  36829. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  36830. if (forceDisposeEffect && this._effect) {
  36831. if (!this.storeEffectOnSubMeshes) {
  36832. this._scene.getEngine()._releaseEffect(this._effect);
  36833. }
  36834. this._effect = null;
  36835. }
  36836. // Callback
  36837. this.onDisposeObservable.notifyObservers(this);
  36838. this.onDisposeObservable.clear();
  36839. if (this._onBindObservable) {
  36840. this._onBindObservable.clear();
  36841. }
  36842. if (this._onUnBindObservable) {
  36843. this._onUnBindObservable.clear();
  36844. }
  36845. };
  36846. /**
  36847. * Serializes this material
  36848. * @returns the serialized material object
  36849. */
  36850. Material.prototype.serialize = function () {
  36851. return BABYLON.SerializationHelper.Serialize(this);
  36852. };
  36853. /**
  36854. * Creates a MultiMaterial from parsed MultiMaterial data.
  36855. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  36856. * @param scene defines the hosting scene
  36857. * @returns a new MultiMaterial
  36858. */
  36859. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  36860. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  36861. multiMaterial.id = parsedMultiMaterial.id;
  36862. if (BABYLON.Tags) {
  36863. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  36864. }
  36865. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  36866. var subMatId = parsedMultiMaterial.materials[matIndex];
  36867. if (subMatId) {
  36868. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  36869. }
  36870. else {
  36871. multiMaterial.subMaterials.push(null);
  36872. }
  36873. }
  36874. return multiMaterial;
  36875. };
  36876. /**
  36877. * Creates a material from parsed material data
  36878. * @param parsedMaterial defines parsed material data
  36879. * @param scene defines the hosting scene
  36880. * @param rootUrl defines the root URL to use to load textures
  36881. * @returns a new material
  36882. */
  36883. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  36884. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  36885. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  36886. }
  36887. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  36888. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  36889. if (!BABYLON.LegacyPBRMaterial) {
  36890. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  36891. return;
  36892. }
  36893. }
  36894. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  36895. return materialType.Parse(parsedMaterial, scene, rootUrl);
  36896. };
  36897. // Triangle views
  36898. Material._TriangleFillMode = 0;
  36899. Material._WireFrameFillMode = 1;
  36900. Material._PointFillMode = 2;
  36901. // Draw modes
  36902. Material._PointListDrawMode = 3;
  36903. Material._LineListDrawMode = 4;
  36904. Material._LineLoopDrawMode = 5;
  36905. Material._LineStripDrawMode = 6;
  36906. Material._TriangleStripDrawMode = 7;
  36907. Material._TriangleFanDrawMode = 8;
  36908. /**
  36909. * Stores the clock-wise side orientation
  36910. */
  36911. Material._ClockWiseSideOrientation = 0;
  36912. /**
  36913. * Stores the counter clock-wise side orientation
  36914. */
  36915. Material._CounterClockWiseSideOrientation = 1;
  36916. /**
  36917. * The dirty texture flag value
  36918. */
  36919. Material.TextureDirtyFlag = 1;
  36920. /**
  36921. * The dirty light flag value
  36922. */
  36923. Material.LightDirtyFlag = 2;
  36924. /**
  36925. * The dirty fresnel flag value
  36926. */
  36927. Material.FresnelDirtyFlag = 4;
  36928. /**
  36929. * The dirty attribute flag value
  36930. */
  36931. Material.AttributesDirtyFlag = 8;
  36932. /**
  36933. * The dirty misc flag value
  36934. */
  36935. Material.MiscDirtyFlag = 16;
  36936. /**
  36937. * The all dirty flag value
  36938. */
  36939. Material.AllDirtyFlag = 31;
  36940. __decorate([
  36941. BABYLON.serialize()
  36942. ], Material.prototype, "id", void 0);
  36943. __decorate([
  36944. BABYLON.serialize()
  36945. ], Material.prototype, "uniqueId", void 0);
  36946. __decorate([
  36947. BABYLON.serialize()
  36948. ], Material.prototype, "name", void 0);
  36949. __decorate([
  36950. BABYLON.serialize()
  36951. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  36952. __decorate([
  36953. BABYLON.serialize()
  36954. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  36955. __decorate([
  36956. BABYLON.serialize()
  36957. ], Material.prototype, "state", void 0);
  36958. __decorate([
  36959. BABYLON.serialize("alpha")
  36960. ], Material.prototype, "_alpha", void 0);
  36961. __decorate([
  36962. BABYLON.serialize("backFaceCulling")
  36963. ], Material.prototype, "_backFaceCulling", void 0);
  36964. __decorate([
  36965. BABYLON.serialize()
  36966. ], Material.prototype, "sideOrientation", void 0);
  36967. __decorate([
  36968. BABYLON.serialize("alphaMode")
  36969. ], Material.prototype, "_alphaMode", void 0);
  36970. __decorate([
  36971. BABYLON.serialize()
  36972. ], Material.prototype, "_needDepthPrePass", void 0);
  36973. __decorate([
  36974. BABYLON.serialize()
  36975. ], Material.prototype, "disableDepthWrite", void 0);
  36976. __decorate([
  36977. BABYLON.serialize()
  36978. ], Material.prototype, "forceDepthWrite", void 0);
  36979. __decorate([
  36980. BABYLON.serialize()
  36981. ], Material.prototype, "separateCullingPass", void 0);
  36982. __decorate([
  36983. BABYLON.serialize("fogEnabled")
  36984. ], Material.prototype, "_fogEnabled", void 0);
  36985. __decorate([
  36986. BABYLON.serialize()
  36987. ], Material.prototype, "pointSize", void 0);
  36988. __decorate([
  36989. BABYLON.serialize()
  36990. ], Material.prototype, "zOffset", void 0);
  36991. __decorate([
  36992. BABYLON.serialize()
  36993. ], Material.prototype, "wireframe", null);
  36994. __decorate([
  36995. BABYLON.serialize()
  36996. ], Material.prototype, "pointsCloud", null);
  36997. __decorate([
  36998. BABYLON.serialize()
  36999. ], Material.prototype, "fillMode", null);
  37000. return Material;
  37001. }());
  37002. BABYLON.Material = Material;
  37003. })(BABYLON || (BABYLON = {}));
  37004. //# sourceMappingURL=babylon.material.js.map
  37005. var BABYLON;
  37006. (function (BABYLON) {
  37007. /**
  37008. * Uniform buffer objects.
  37009. *
  37010. * Handles blocks of uniform on the GPU.
  37011. *
  37012. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  37013. *
  37014. * For more information, please refer to :
  37015. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  37016. */
  37017. var UniformBuffer = /** @class */ (function () {
  37018. /**
  37019. * Instantiates a new Uniform buffer objects.
  37020. *
  37021. * Handles blocks of uniform on the GPU.
  37022. *
  37023. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  37024. *
  37025. * For more information, please refer to :
  37026. * @see https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  37027. * @param engine Define the engine the buffer is associated with
  37028. * @param data Define the data contained in the buffer
  37029. * @param dynamic Define if the buffer is updatable
  37030. */
  37031. function UniformBuffer(engine, data, dynamic) {
  37032. this._engine = engine;
  37033. this._noUBO = !engine.supportsUniformBuffers;
  37034. this._dynamic = dynamic;
  37035. this._data = data || [];
  37036. this._uniformLocations = {};
  37037. this._uniformSizes = {};
  37038. this._uniformLocationPointer = 0;
  37039. this._needSync = false;
  37040. if (this._noUBO) {
  37041. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  37042. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  37043. this.updateFloat = this._updateFloatForEffect;
  37044. this.updateFloat2 = this._updateFloat2ForEffect;
  37045. this.updateFloat3 = this._updateFloat3ForEffect;
  37046. this.updateFloat4 = this._updateFloat4ForEffect;
  37047. this.updateMatrix = this._updateMatrixForEffect;
  37048. this.updateVector3 = this._updateVector3ForEffect;
  37049. this.updateVector4 = this._updateVector4ForEffect;
  37050. this.updateColor3 = this._updateColor3ForEffect;
  37051. this.updateColor4 = this._updateColor4ForEffect;
  37052. }
  37053. else {
  37054. this._engine._uniformBuffers.push(this);
  37055. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  37056. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  37057. this.updateFloat = this._updateFloatForUniform;
  37058. this.updateFloat2 = this._updateFloat2ForUniform;
  37059. this.updateFloat3 = this._updateFloat3ForUniform;
  37060. this.updateFloat4 = this._updateFloat4ForUniform;
  37061. this.updateMatrix = this._updateMatrixForUniform;
  37062. this.updateVector3 = this._updateVector3ForUniform;
  37063. this.updateVector4 = this._updateVector4ForUniform;
  37064. this.updateColor3 = this._updateColor3ForUniform;
  37065. this.updateColor4 = this._updateColor4ForUniform;
  37066. }
  37067. }
  37068. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  37069. /**
  37070. * Indicates if the buffer is using the WebGL2 UBO implementation,
  37071. * or just falling back on setUniformXXX calls.
  37072. */
  37073. get: function () {
  37074. return !this._noUBO;
  37075. },
  37076. enumerable: true,
  37077. configurable: true
  37078. });
  37079. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  37080. /**
  37081. * Indicates if the WebGL underlying uniform buffer is in sync
  37082. * with the javascript cache data.
  37083. */
  37084. get: function () {
  37085. return !this._needSync;
  37086. },
  37087. enumerable: true,
  37088. configurable: true
  37089. });
  37090. /**
  37091. * Indicates if the WebGL underlying uniform buffer is dynamic.
  37092. * Also, a dynamic UniformBuffer will disable cache verification and always
  37093. * update the underlying WebGL uniform buffer to the GPU.
  37094. * @returns if Dynamic, otherwise false
  37095. */
  37096. UniformBuffer.prototype.isDynamic = function () {
  37097. return this._dynamic !== undefined;
  37098. };
  37099. /**
  37100. * The data cache on JS side.
  37101. * @returns the underlying data as a float array
  37102. */
  37103. UniformBuffer.prototype.getData = function () {
  37104. return this._bufferData;
  37105. };
  37106. /**
  37107. * The underlying WebGL Uniform buffer.
  37108. * @returns the webgl buffer
  37109. */
  37110. UniformBuffer.prototype.getBuffer = function () {
  37111. return this._buffer;
  37112. };
  37113. /**
  37114. * std140 layout specifies how to align data within an UBO structure.
  37115. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  37116. * for specs.
  37117. */
  37118. UniformBuffer.prototype._fillAlignment = function (size) {
  37119. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  37120. // and 4x4 matrices
  37121. // TODO : change if other types are used
  37122. var alignment;
  37123. if (size <= 2) {
  37124. alignment = size;
  37125. }
  37126. else {
  37127. alignment = 4;
  37128. }
  37129. if ((this._uniformLocationPointer % alignment) !== 0) {
  37130. var oldPointer = this._uniformLocationPointer;
  37131. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  37132. var diff = this._uniformLocationPointer - oldPointer;
  37133. for (var i = 0; i < diff; i++) {
  37134. this._data.push(0);
  37135. }
  37136. }
  37137. };
  37138. /**
  37139. * Adds an uniform in the buffer.
  37140. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  37141. * for the layout to be correct !
  37142. * @param name Name of the uniform, as used in the uniform block in the shader.
  37143. * @param size Data size, or data directly.
  37144. */
  37145. UniformBuffer.prototype.addUniform = function (name, size) {
  37146. if (this._noUBO) {
  37147. return;
  37148. }
  37149. if (this._uniformLocations[name] !== undefined) {
  37150. // Already existing uniform
  37151. return;
  37152. }
  37153. // This function must be called in the order of the shader layout !
  37154. // size can be the size of the uniform, or data directly
  37155. var data;
  37156. if (size instanceof Array) {
  37157. data = size;
  37158. size = data.length;
  37159. }
  37160. else {
  37161. size = size;
  37162. data = [];
  37163. // Fill with zeros
  37164. for (var i = 0; i < size; i++) {
  37165. data.push(0);
  37166. }
  37167. }
  37168. this._fillAlignment(size);
  37169. this._uniformSizes[name] = size;
  37170. this._uniformLocations[name] = this._uniformLocationPointer;
  37171. this._uniformLocationPointer += size;
  37172. for (var i = 0; i < size; i++) {
  37173. this._data.push(data[i]);
  37174. }
  37175. this._needSync = true;
  37176. };
  37177. /**
  37178. * Adds a Matrix 4x4 to the uniform buffer.
  37179. * @param name Name of the uniform, as used in the uniform block in the shader.
  37180. * @param mat A 4x4 matrix.
  37181. */
  37182. UniformBuffer.prototype.addMatrix = function (name, mat) {
  37183. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  37184. };
  37185. /**
  37186. * Adds a vec2 to the uniform buffer.
  37187. * @param name Name of the uniform, as used in the uniform block in the shader.
  37188. * @param x Define the x component value of the vec2
  37189. * @param y Define the y component value of the vec2
  37190. */
  37191. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  37192. var temp = [x, y];
  37193. this.addUniform(name, temp);
  37194. };
  37195. /**
  37196. * Adds a vec3 to the uniform buffer.
  37197. * @param name Name of the uniform, as used in the uniform block in the shader.
  37198. * @param x Define the x component value of the vec3
  37199. * @param y Define the y component value of the vec3
  37200. * @param z Define the z component value of the vec3
  37201. */
  37202. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  37203. var temp = [x, y, z];
  37204. this.addUniform(name, temp);
  37205. };
  37206. /**
  37207. * Adds a vec3 to the uniform buffer.
  37208. * @param name Name of the uniform, as used in the uniform block in the shader.
  37209. * @param color Define the vec3 from a Color
  37210. */
  37211. UniformBuffer.prototype.addColor3 = function (name, color) {
  37212. var temp = new Array();
  37213. color.toArray(temp);
  37214. this.addUniform(name, temp);
  37215. };
  37216. /**
  37217. * Adds a vec4 to the uniform buffer.
  37218. * @param name Name of the uniform, as used in the uniform block in the shader.
  37219. * @param color Define the rgb components from a Color
  37220. * @param alpha Define the a component of the vec4
  37221. */
  37222. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  37223. var temp = new Array();
  37224. color.toArray(temp);
  37225. temp.push(alpha);
  37226. this.addUniform(name, temp);
  37227. };
  37228. /**
  37229. * Adds a vec3 to the uniform buffer.
  37230. * @param name Name of the uniform, as used in the uniform block in the shader.
  37231. * @param vector Define the vec3 components from a Vector
  37232. */
  37233. UniformBuffer.prototype.addVector3 = function (name, vector) {
  37234. var temp = new Array();
  37235. vector.toArray(temp);
  37236. this.addUniform(name, temp);
  37237. };
  37238. /**
  37239. * Adds a Matrix 3x3 to the uniform buffer.
  37240. * @param name Name of the uniform, as used in the uniform block in the shader.
  37241. */
  37242. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  37243. this.addUniform(name, 12);
  37244. };
  37245. /**
  37246. * Adds a Matrix 2x2 to the uniform buffer.
  37247. * @param name Name of the uniform, as used in the uniform block in the shader.
  37248. */
  37249. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  37250. this.addUniform(name, 8);
  37251. };
  37252. /**
  37253. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  37254. */
  37255. UniformBuffer.prototype.create = function () {
  37256. if (this._noUBO) {
  37257. return;
  37258. }
  37259. if (this._buffer) {
  37260. return; // nothing to do
  37261. }
  37262. // See spec, alignment must be filled as a vec4
  37263. this._fillAlignment(4);
  37264. this._bufferData = new Float32Array(this._data);
  37265. this._rebuild();
  37266. this._needSync = true;
  37267. };
  37268. /** @hidden */
  37269. UniformBuffer.prototype._rebuild = function () {
  37270. if (this._noUBO) {
  37271. return;
  37272. }
  37273. if (this._dynamic) {
  37274. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  37275. }
  37276. else {
  37277. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  37278. }
  37279. };
  37280. /**
  37281. * Updates the WebGL Uniform Buffer on the GPU.
  37282. * If the `dynamic` flag is set to true, no cache comparison is done.
  37283. * Otherwise, the buffer will be updated only if the cache differs.
  37284. */
  37285. UniformBuffer.prototype.update = function () {
  37286. if (!this._buffer) {
  37287. this.create();
  37288. return;
  37289. }
  37290. if (!this._dynamic && !this._needSync) {
  37291. return;
  37292. }
  37293. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  37294. this._needSync = false;
  37295. };
  37296. /**
  37297. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  37298. * @param uniformName Define the name of the uniform, as used in the uniform block in the shader.
  37299. * @param data Define the flattened data
  37300. * @param size Define the size of the data.
  37301. */
  37302. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  37303. var location = this._uniformLocations[uniformName];
  37304. if (location === undefined) {
  37305. if (this._buffer) {
  37306. // Cannot add an uniform if the buffer is already created
  37307. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  37308. return;
  37309. }
  37310. this.addUniform(uniformName, size);
  37311. location = this._uniformLocations[uniformName];
  37312. }
  37313. if (!this._buffer) {
  37314. this.create();
  37315. }
  37316. if (!this._dynamic) {
  37317. // Cache for static uniform buffers
  37318. var changed = false;
  37319. for (var i = 0; i < size; i++) {
  37320. if (this._bufferData[location + i] !== data[i]) {
  37321. changed = true;
  37322. this._bufferData[location + i] = data[i];
  37323. }
  37324. }
  37325. this._needSync = this._needSync || changed;
  37326. }
  37327. else {
  37328. // No cache for dynamic
  37329. for (var i = 0; i < size; i++) {
  37330. this._bufferData[location + i] = data[i];
  37331. }
  37332. }
  37333. };
  37334. // Update methods
  37335. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  37336. // To match std140, matrix must be realigned
  37337. for (var i = 0; i < 3; i++) {
  37338. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  37339. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  37340. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  37341. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  37342. }
  37343. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  37344. };
  37345. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  37346. this._currentEffect.setMatrix3x3(name, matrix);
  37347. };
  37348. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  37349. this._currentEffect.setMatrix2x2(name, matrix);
  37350. };
  37351. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  37352. // To match std140, matrix must be realigned
  37353. for (var i = 0; i < 2; i++) {
  37354. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  37355. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  37356. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  37357. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  37358. }
  37359. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  37360. };
  37361. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  37362. this._currentEffect.setFloat(name, x);
  37363. };
  37364. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  37365. UniformBuffer._tempBuffer[0] = x;
  37366. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  37367. };
  37368. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  37369. if (suffix === void 0) { suffix = ""; }
  37370. this._currentEffect.setFloat2(name + suffix, x, y);
  37371. };
  37372. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  37373. if (suffix === void 0) { suffix = ""; }
  37374. UniformBuffer._tempBuffer[0] = x;
  37375. UniformBuffer._tempBuffer[1] = y;
  37376. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  37377. };
  37378. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  37379. if (suffix === void 0) { suffix = ""; }
  37380. this._currentEffect.setFloat3(name + suffix, x, y, z);
  37381. };
  37382. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  37383. if (suffix === void 0) { suffix = ""; }
  37384. UniformBuffer._tempBuffer[0] = x;
  37385. UniformBuffer._tempBuffer[1] = y;
  37386. UniformBuffer._tempBuffer[2] = z;
  37387. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  37388. };
  37389. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  37390. if (suffix === void 0) { suffix = ""; }
  37391. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  37392. };
  37393. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  37394. if (suffix === void 0) { suffix = ""; }
  37395. UniformBuffer._tempBuffer[0] = x;
  37396. UniformBuffer._tempBuffer[1] = y;
  37397. UniformBuffer._tempBuffer[2] = z;
  37398. UniformBuffer._tempBuffer[3] = w;
  37399. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  37400. };
  37401. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  37402. this._currentEffect.setMatrix(name, mat);
  37403. };
  37404. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  37405. this.updateUniform(name, mat.toArray(), 16);
  37406. };
  37407. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  37408. this._currentEffect.setVector3(name, vector);
  37409. };
  37410. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  37411. vector.toArray(UniformBuffer._tempBuffer);
  37412. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  37413. };
  37414. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  37415. this._currentEffect.setVector4(name, vector);
  37416. };
  37417. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  37418. vector.toArray(UniformBuffer._tempBuffer);
  37419. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  37420. };
  37421. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  37422. if (suffix === void 0) { suffix = ""; }
  37423. this._currentEffect.setColor3(name + suffix, color);
  37424. };
  37425. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  37426. if (suffix === void 0) { suffix = ""; }
  37427. color.toArray(UniformBuffer._tempBuffer);
  37428. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  37429. };
  37430. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  37431. if (suffix === void 0) { suffix = ""; }
  37432. this._currentEffect.setColor4(name + suffix, color, alpha);
  37433. };
  37434. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  37435. if (suffix === void 0) { suffix = ""; }
  37436. color.toArray(UniformBuffer._tempBuffer);
  37437. UniformBuffer._tempBuffer[3] = alpha;
  37438. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  37439. };
  37440. /**
  37441. * Sets a sampler uniform on the effect.
  37442. * @param name Define the name of the sampler.
  37443. * @param texture Define the texture to set in the sampler
  37444. */
  37445. UniformBuffer.prototype.setTexture = function (name, texture) {
  37446. this._currentEffect.setTexture(name, texture);
  37447. };
  37448. /**
  37449. * Directly updates the value of the uniform in the cache AND on the GPU.
  37450. * @param uniformName Define the name of the uniform, as used in the uniform block in the shader.
  37451. * @param data Define the flattened data
  37452. */
  37453. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  37454. this.updateUniform(uniformName, data, data.length);
  37455. this.update();
  37456. };
  37457. /**
  37458. * Binds this uniform buffer to an effect.
  37459. * @param effect Define the effect to bind the buffer to
  37460. * @param name Name of the uniform block in the shader.
  37461. */
  37462. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  37463. this._currentEffect = effect;
  37464. if (this._noUBO || !this._buffer) {
  37465. return;
  37466. }
  37467. effect.bindUniformBuffer(this._buffer, name);
  37468. };
  37469. /**
  37470. * Disposes the uniform buffer.
  37471. */
  37472. UniformBuffer.prototype.dispose = function () {
  37473. if (this._noUBO) {
  37474. return;
  37475. }
  37476. var index = this._engine._uniformBuffers.indexOf(this);
  37477. if (index !== -1) {
  37478. this._engine._uniformBuffers.splice(index, 1);
  37479. }
  37480. if (!this._buffer) {
  37481. return;
  37482. }
  37483. if (this._engine._releaseBuffer(this._buffer)) {
  37484. this._buffer = null;
  37485. }
  37486. };
  37487. // Pool for avoiding memory leaks
  37488. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  37489. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  37490. return UniformBuffer;
  37491. }());
  37492. BABYLON.UniformBuffer = UniformBuffer;
  37493. })(BABYLON || (BABYLON = {}));
  37494. //# sourceMappingURL=babylon.uniformBuffer.js.map
  37495. var BABYLON;
  37496. (function (BABYLON) {
  37497. /**
  37498. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  37499. */
  37500. var VertexData = /** @class */ (function () {
  37501. function VertexData() {
  37502. }
  37503. /**
  37504. * Uses the passed data array to set the set the values for the specified kind of data
  37505. * @param data a linear array of floating numbers
  37506. * @param kind the type of data that is being set, eg positions, colors etc
  37507. */
  37508. VertexData.prototype.set = function (data, kind) {
  37509. switch (kind) {
  37510. case BABYLON.VertexBuffer.PositionKind:
  37511. this.positions = data;
  37512. break;
  37513. case BABYLON.VertexBuffer.NormalKind:
  37514. this.normals = data;
  37515. break;
  37516. case BABYLON.VertexBuffer.TangentKind:
  37517. this.tangents = data;
  37518. break;
  37519. case BABYLON.VertexBuffer.UVKind:
  37520. this.uvs = data;
  37521. break;
  37522. case BABYLON.VertexBuffer.UV2Kind:
  37523. this.uvs2 = data;
  37524. break;
  37525. case BABYLON.VertexBuffer.UV3Kind:
  37526. this.uvs3 = data;
  37527. break;
  37528. case BABYLON.VertexBuffer.UV4Kind:
  37529. this.uvs4 = data;
  37530. break;
  37531. case BABYLON.VertexBuffer.UV5Kind:
  37532. this.uvs5 = data;
  37533. break;
  37534. case BABYLON.VertexBuffer.UV6Kind:
  37535. this.uvs6 = data;
  37536. break;
  37537. case BABYLON.VertexBuffer.ColorKind:
  37538. this.colors = data;
  37539. break;
  37540. case BABYLON.VertexBuffer.MatricesIndicesKind:
  37541. this.matricesIndices = data;
  37542. break;
  37543. case BABYLON.VertexBuffer.MatricesWeightsKind:
  37544. this.matricesWeights = data;
  37545. break;
  37546. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  37547. this.matricesIndicesExtra = data;
  37548. break;
  37549. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  37550. this.matricesWeightsExtra = data;
  37551. break;
  37552. }
  37553. };
  37554. /**
  37555. * Associates the vertexData to the passed Mesh.
  37556. * Sets it as updatable or not (default `false`)
  37557. * @param mesh the mesh the vertexData is applied to
  37558. * @param updatable when used and having the value true allows new data to update the vertexData
  37559. * @returns the VertexData
  37560. */
  37561. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  37562. this._applyTo(mesh, updatable);
  37563. return this;
  37564. };
  37565. /**
  37566. * Associates the vertexData to the passed Geometry.
  37567. * Sets it as updatable or not (default `false`)
  37568. * @param geometry the geometry the vertexData is applied to
  37569. * @param updatable when used and having the value true allows new data to update the vertexData
  37570. * @returns VertexData
  37571. */
  37572. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  37573. this._applyTo(geometry, updatable);
  37574. return this;
  37575. };
  37576. /**
  37577. * Updates the associated mesh
  37578. * @param mesh the mesh to be updated
  37579. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  37580. * @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
  37581. * @returns VertexData
  37582. */
  37583. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  37584. this._update(mesh);
  37585. return this;
  37586. };
  37587. /**
  37588. * Updates the associated geometry
  37589. * @param geometry the geometry to be updated
  37590. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  37591. * @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
  37592. * @returns VertexData.
  37593. */
  37594. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  37595. this._update(geometry);
  37596. return this;
  37597. };
  37598. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  37599. if (updatable === void 0) { updatable = false; }
  37600. if (this.positions) {
  37601. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  37602. }
  37603. if (this.normals) {
  37604. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  37605. }
  37606. if (this.tangents) {
  37607. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  37608. }
  37609. if (this.uvs) {
  37610. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  37611. }
  37612. if (this.uvs2) {
  37613. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  37614. }
  37615. if (this.uvs3) {
  37616. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  37617. }
  37618. if (this.uvs4) {
  37619. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  37620. }
  37621. if (this.uvs5) {
  37622. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  37623. }
  37624. if (this.uvs6) {
  37625. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  37626. }
  37627. if (this.colors) {
  37628. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  37629. }
  37630. if (this.matricesIndices) {
  37631. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  37632. }
  37633. if (this.matricesWeights) {
  37634. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  37635. }
  37636. if (this.matricesIndicesExtra) {
  37637. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  37638. }
  37639. if (this.matricesWeightsExtra) {
  37640. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  37641. }
  37642. if (this.indices) {
  37643. meshOrGeometry.setIndices(this.indices, null, updatable);
  37644. }
  37645. else {
  37646. meshOrGeometry.setIndices([], null);
  37647. }
  37648. return this;
  37649. };
  37650. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  37651. if (this.positions) {
  37652. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  37653. }
  37654. if (this.normals) {
  37655. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  37656. }
  37657. if (this.tangents) {
  37658. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  37659. }
  37660. if (this.uvs) {
  37661. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  37662. }
  37663. if (this.uvs2) {
  37664. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  37665. }
  37666. if (this.uvs3) {
  37667. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  37668. }
  37669. if (this.uvs4) {
  37670. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  37671. }
  37672. if (this.uvs5) {
  37673. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  37674. }
  37675. if (this.uvs6) {
  37676. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  37677. }
  37678. if (this.colors) {
  37679. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  37680. }
  37681. if (this.matricesIndices) {
  37682. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  37683. }
  37684. if (this.matricesWeights) {
  37685. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  37686. }
  37687. if (this.matricesIndicesExtra) {
  37688. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  37689. }
  37690. if (this.matricesWeightsExtra) {
  37691. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  37692. }
  37693. if (this.indices) {
  37694. meshOrGeometry.setIndices(this.indices, null);
  37695. }
  37696. return this;
  37697. };
  37698. /**
  37699. * Transforms each position and each normal of the vertexData according to the passed Matrix
  37700. * @param matrix the transforming matrix
  37701. * @returns the VertexData
  37702. */
  37703. VertexData.prototype.transform = function (matrix) {
  37704. var flip = matrix.m[0] * matrix.m[5] * matrix.m[10] < 0;
  37705. var transformed = BABYLON.Vector3.Zero();
  37706. var index;
  37707. if (this.positions) {
  37708. var position = BABYLON.Vector3.Zero();
  37709. for (index = 0; index < this.positions.length; index += 3) {
  37710. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  37711. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  37712. this.positions[index] = transformed.x;
  37713. this.positions[index + 1] = transformed.y;
  37714. this.positions[index + 2] = transformed.z;
  37715. }
  37716. }
  37717. if (this.normals) {
  37718. var normal = BABYLON.Vector3.Zero();
  37719. for (index = 0; index < this.normals.length; index += 3) {
  37720. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  37721. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  37722. this.normals[index] = transformed.x;
  37723. this.normals[index + 1] = transformed.y;
  37724. this.normals[index + 2] = transformed.z;
  37725. }
  37726. }
  37727. if (this.tangents) {
  37728. var tangent = BABYLON.Vector4.Zero();
  37729. var tangentTransformed = BABYLON.Vector4.Zero();
  37730. for (index = 0; index < this.tangents.length; index += 4) {
  37731. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  37732. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  37733. this.tangents[index] = tangentTransformed.x;
  37734. this.tangents[index + 1] = tangentTransformed.y;
  37735. this.tangents[index + 2] = tangentTransformed.z;
  37736. this.tangents[index + 3] = tangentTransformed.w;
  37737. }
  37738. }
  37739. if (flip && this.indices) {
  37740. for (index = 0; index < this.indices.length; index += 3) {
  37741. var tmp = this.indices[index + 1];
  37742. this.indices[index + 1] = this.indices[index + 2];
  37743. this.indices[index + 2] = tmp;
  37744. }
  37745. }
  37746. return this;
  37747. };
  37748. /**
  37749. * Merges the passed VertexData into the current one
  37750. * @param other the VertexData to be merged into the current one
  37751. * @param use32BitsIndices defines a boolean indicating if indices must be store in a 32 bits array
  37752. * @returns the modified VertexData
  37753. */
  37754. VertexData.prototype.merge = function (other, use32BitsIndices) {
  37755. if (use32BitsIndices === void 0) { use32BitsIndices = false; }
  37756. this._validate();
  37757. other._validate();
  37758. if (!this.normals !== !other.normals ||
  37759. !this.tangents !== !other.tangents ||
  37760. !this.uvs !== !other.uvs ||
  37761. !this.uvs2 !== !other.uvs2 ||
  37762. !this.uvs3 !== !other.uvs3 ||
  37763. !this.uvs4 !== !other.uvs4 ||
  37764. !this.uvs5 !== !other.uvs5 ||
  37765. !this.uvs6 !== !other.uvs6 ||
  37766. !this.colors !== !other.colors ||
  37767. !this.matricesIndices !== !other.matricesIndices ||
  37768. !this.matricesWeights !== !other.matricesWeights ||
  37769. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  37770. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  37771. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  37772. }
  37773. if (other.indices) {
  37774. if (!this.indices) {
  37775. this.indices = [];
  37776. }
  37777. var offset = this.positions ? this.positions.length / 3 : 0;
  37778. var isSrcTypedArray = this.indices.BYTES_PER_ELEMENT !== undefined;
  37779. if (isSrcTypedArray) {
  37780. var len = this.indices.length + other.indices.length;
  37781. var temp = use32BitsIndices || this.indices instanceof Uint32Array ? new Uint32Array(len) : new Uint16Array(len);
  37782. temp.set(this.indices);
  37783. var decal = this.indices.length;
  37784. for (var index = 0; index < other.indices.length; index++) {
  37785. temp[decal + index] = other.indices[index] + offset;
  37786. }
  37787. this.indices = temp;
  37788. }
  37789. else {
  37790. for (var index = 0; index < other.indices.length; index++) {
  37791. this.indices.push(other.indices[index] + offset);
  37792. }
  37793. }
  37794. }
  37795. this.positions = this._mergeElement(this.positions, other.positions);
  37796. this.normals = this._mergeElement(this.normals, other.normals);
  37797. this.tangents = this._mergeElement(this.tangents, other.tangents);
  37798. this.uvs = this._mergeElement(this.uvs, other.uvs);
  37799. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  37800. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  37801. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  37802. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  37803. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  37804. this.colors = this._mergeElement(this.colors, other.colors);
  37805. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  37806. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  37807. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  37808. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  37809. return this;
  37810. };
  37811. VertexData.prototype._mergeElement = function (source, other) {
  37812. if (!source) {
  37813. return other;
  37814. }
  37815. if (!other) {
  37816. return source;
  37817. }
  37818. var len = other.length + source.length;
  37819. var isSrcTypedArray = source instanceof Float32Array;
  37820. var isOthTypedArray = other instanceof Float32Array;
  37821. // use non-loop method when the source is Float32Array
  37822. if (isSrcTypedArray) {
  37823. var ret32 = new Float32Array(len);
  37824. ret32.set(source);
  37825. ret32.set(other, source.length);
  37826. return ret32;
  37827. // source is number[], when other is also use concat
  37828. }
  37829. else if (!isOthTypedArray) {
  37830. return source.concat(other);
  37831. // source is a number[], but other is a Float32Array, loop required
  37832. }
  37833. else {
  37834. var ret = source.slice(0); // copy source to a separate array
  37835. for (var i = 0, len = other.length; i < len; i++) {
  37836. ret.push(other[i]);
  37837. }
  37838. return ret;
  37839. }
  37840. };
  37841. VertexData.prototype._validate = function () {
  37842. if (!this.positions) {
  37843. throw new Error("Positions are required");
  37844. }
  37845. var getElementCount = function (kind, values) {
  37846. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  37847. if ((values.length % stride) !== 0) {
  37848. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  37849. }
  37850. return values.length / stride;
  37851. };
  37852. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  37853. var validateElementCount = function (kind, values) {
  37854. var elementCount = getElementCount(kind, values);
  37855. if (elementCount !== positionsElementCount) {
  37856. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  37857. }
  37858. };
  37859. if (this.normals)
  37860. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  37861. if (this.tangents)
  37862. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  37863. if (this.uvs)
  37864. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  37865. if (this.uvs2)
  37866. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  37867. if (this.uvs3)
  37868. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  37869. if (this.uvs4)
  37870. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  37871. if (this.uvs5)
  37872. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  37873. if (this.uvs6)
  37874. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  37875. if (this.colors)
  37876. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  37877. if (this.matricesIndices)
  37878. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  37879. if (this.matricesWeights)
  37880. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  37881. if (this.matricesIndicesExtra)
  37882. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  37883. if (this.matricesWeightsExtra)
  37884. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  37885. };
  37886. /**
  37887. * Serializes the VertexData
  37888. * @returns a serialized object
  37889. */
  37890. VertexData.prototype.serialize = function () {
  37891. var serializationObject = this.serialize();
  37892. if (this.positions) {
  37893. serializationObject.positions = this.positions;
  37894. }
  37895. if (this.normals) {
  37896. serializationObject.normals = this.normals;
  37897. }
  37898. if (this.tangents) {
  37899. serializationObject.tangents = this.tangents;
  37900. }
  37901. if (this.uvs) {
  37902. serializationObject.uvs = this.uvs;
  37903. }
  37904. if (this.uvs2) {
  37905. serializationObject.uvs2 = this.uvs2;
  37906. }
  37907. if (this.uvs3) {
  37908. serializationObject.uvs3 = this.uvs3;
  37909. }
  37910. if (this.uvs4) {
  37911. serializationObject.uvs4 = this.uvs4;
  37912. }
  37913. if (this.uvs5) {
  37914. serializationObject.uvs5 = this.uvs5;
  37915. }
  37916. if (this.uvs6) {
  37917. serializationObject.uvs6 = this.uvs6;
  37918. }
  37919. if (this.colors) {
  37920. serializationObject.colors = this.colors;
  37921. }
  37922. if (this.matricesIndices) {
  37923. serializationObject.matricesIndices = this.matricesIndices;
  37924. serializationObject.matricesIndices._isExpanded = true;
  37925. }
  37926. if (this.matricesWeights) {
  37927. serializationObject.matricesWeights = this.matricesWeights;
  37928. }
  37929. if (this.matricesIndicesExtra) {
  37930. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  37931. serializationObject.matricesIndicesExtra._isExpanded = true;
  37932. }
  37933. if (this.matricesWeightsExtra) {
  37934. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  37935. }
  37936. serializationObject.indices = this.indices;
  37937. return serializationObject;
  37938. };
  37939. // Statics
  37940. /**
  37941. * Extracts the vertexData from a mesh
  37942. * @param mesh the mesh from which to extract the VertexData
  37943. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  37944. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  37945. * @returns the object VertexData associated to the passed mesh
  37946. */
  37947. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  37948. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  37949. };
  37950. /**
  37951. * Extracts the vertexData from the geometry
  37952. * @param geometry the geometry from which to extract the VertexData
  37953. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  37954. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  37955. * @returns the object VertexData associated to the passed mesh
  37956. */
  37957. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  37958. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  37959. };
  37960. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  37961. var result = new VertexData();
  37962. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  37963. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  37964. }
  37965. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  37966. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  37967. }
  37968. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  37969. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  37970. }
  37971. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  37972. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  37973. }
  37974. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  37975. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  37976. }
  37977. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  37978. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  37979. }
  37980. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  37981. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  37982. }
  37983. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  37984. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  37985. }
  37986. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  37987. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  37988. }
  37989. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  37990. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  37991. }
  37992. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  37993. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  37994. }
  37995. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  37996. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  37997. }
  37998. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  37999. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  38000. }
  38001. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  38002. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  38003. }
  38004. result.indices = meshOrGeometry.getIndices(copyWhenShared, forceCopy);
  38005. return result;
  38006. };
  38007. /**
  38008. * Creates the VertexData for a Ribbon
  38009. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  38010. * * pathArray array of paths, each of which an array of successive Vector3
  38011. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  38012. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  38013. * * 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
  38014. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38015. * * 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)
  38016. * * 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)
  38017. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  38018. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  38019. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  38020. * @returns the VertexData of the ribbon
  38021. */
  38022. VertexData.CreateRibbon = function (options) {
  38023. var pathArray = options.pathArray;
  38024. var closeArray = options.closeArray || false;
  38025. var closePath = options.closePath || false;
  38026. var invertUV = options.invertUV || false;
  38027. var defaultOffset = Math.floor(pathArray[0].length / 2);
  38028. var offset = options.offset || defaultOffset;
  38029. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  38030. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38031. var customUV = options.uvs;
  38032. var customColors = options.colors;
  38033. var positions = [];
  38034. var indices = [];
  38035. var normals = [];
  38036. var uvs = [];
  38037. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  38038. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  38039. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  38040. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  38041. var minlg; // minimal length among all paths from pathArray
  38042. var lg = []; // array of path lengths : nb of vertex per path
  38043. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  38044. var p; // path iterator
  38045. var i; // point iterator
  38046. var j; // point iterator
  38047. // if single path in pathArray
  38048. if (pathArray.length < 2) {
  38049. var ar1 = [];
  38050. var ar2 = [];
  38051. for (i = 0; i < pathArray[0].length - offset; i++) {
  38052. ar1.push(pathArray[0][i]);
  38053. ar2.push(pathArray[0][i + offset]);
  38054. }
  38055. pathArray = [ar1, ar2];
  38056. }
  38057. // positions and horizontal distances (u)
  38058. var idc = 0;
  38059. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  38060. var path;
  38061. var l;
  38062. minlg = pathArray[0].length;
  38063. var vectlg;
  38064. var dist;
  38065. for (p = 0; p < pathArray.length; p++) {
  38066. uTotalDistance[p] = 0;
  38067. us[p] = [0];
  38068. path = pathArray[p];
  38069. l = path.length;
  38070. minlg = (minlg < l) ? minlg : l;
  38071. j = 0;
  38072. while (j < l) {
  38073. positions.push(path[j].x, path[j].y, path[j].z);
  38074. if (j > 0) {
  38075. vectlg = path[j].subtract(path[j - 1]).length();
  38076. dist = vectlg + uTotalDistance[p];
  38077. us[p].push(dist);
  38078. uTotalDistance[p] = dist;
  38079. }
  38080. j++;
  38081. }
  38082. if (closePath) { // an extra hidden vertex is added in the "positions" array
  38083. j--;
  38084. positions.push(path[0].x, path[0].y, path[0].z);
  38085. vectlg = path[j].subtract(path[0]).length();
  38086. dist = vectlg + uTotalDistance[p];
  38087. us[p].push(dist);
  38088. uTotalDistance[p] = dist;
  38089. }
  38090. lg[p] = l + closePathCorr;
  38091. idx[p] = idc;
  38092. idc += (l + closePathCorr);
  38093. }
  38094. // vertical distances (v)
  38095. var path1;
  38096. var path2;
  38097. var vertex1 = null;
  38098. var vertex2 = null;
  38099. for (i = 0; i < minlg + closePathCorr; i++) {
  38100. vTotalDistance[i] = 0;
  38101. vs[i] = [0];
  38102. for (p = 0; p < pathArray.length - 1; p++) {
  38103. path1 = pathArray[p];
  38104. path2 = pathArray[p + 1];
  38105. if (i === minlg) { // closePath
  38106. vertex1 = path1[0];
  38107. vertex2 = path2[0];
  38108. }
  38109. else {
  38110. vertex1 = path1[i];
  38111. vertex2 = path2[i];
  38112. }
  38113. vectlg = vertex2.subtract(vertex1).length();
  38114. dist = vectlg + vTotalDistance[i];
  38115. vs[i].push(dist);
  38116. vTotalDistance[i] = dist;
  38117. }
  38118. if (closeArray && vertex2 && vertex1) {
  38119. path1 = pathArray[p];
  38120. path2 = pathArray[0];
  38121. if (i === minlg) { // closePath
  38122. vertex2 = path2[0];
  38123. }
  38124. vectlg = vertex2.subtract(vertex1).length();
  38125. dist = vectlg + vTotalDistance[i];
  38126. vTotalDistance[i] = dist;
  38127. }
  38128. }
  38129. // uvs
  38130. var u;
  38131. var v;
  38132. if (customUV) {
  38133. for (p = 0; p < customUV.length; p++) {
  38134. uvs.push(customUV[p].x, customUV[p].y);
  38135. }
  38136. }
  38137. else {
  38138. for (p = 0; p < pathArray.length; p++) {
  38139. for (i = 0; i < minlg + closePathCorr; i++) {
  38140. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  38141. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  38142. if (invertUV) {
  38143. uvs.push(v, u);
  38144. }
  38145. else {
  38146. uvs.push(u, v);
  38147. }
  38148. }
  38149. }
  38150. }
  38151. // indices
  38152. p = 0; // path index
  38153. var pi = 0; // positions array index
  38154. var l1 = lg[p] - 1; // path1 length
  38155. var l2 = lg[p + 1] - 1; // path2 length
  38156. var min = (l1 < l2) ? l1 : l2; // current path stop index
  38157. var shft = idx[1] - idx[0]; // shift
  38158. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  38159. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  38160. // 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
  38161. indices.push(pi, pi + shft, pi + 1);
  38162. indices.push(pi + shft + 1, pi + 1, pi + shft);
  38163. pi += 1;
  38164. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  38165. p++;
  38166. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  38167. shft = idx[0] - idx[p];
  38168. l1 = lg[p] - 1;
  38169. l2 = lg[0] - 1;
  38170. }
  38171. else {
  38172. shft = idx[p + 1] - idx[p];
  38173. l1 = lg[p] - 1;
  38174. l2 = lg[p + 1] - 1;
  38175. }
  38176. pi = idx[p];
  38177. min = (l1 < l2) ? l1 + pi : l2 + pi;
  38178. }
  38179. }
  38180. // normals
  38181. VertexData.ComputeNormals(positions, indices, normals);
  38182. if (closePath) { // update both the first and last vertex normals to their average value
  38183. var indexFirst = 0;
  38184. var indexLast = 0;
  38185. for (p = 0; p < pathArray.length; p++) {
  38186. indexFirst = idx[p] * 3;
  38187. if (p + 1 < pathArray.length) {
  38188. indexLast = (idx[p + 1] - 1) * 3;
  38189. }
  38190. else {
  38191. indexLast = normals.length - 3;
  38192. }
  38193. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  38194. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  38195. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  38196. normals[indexLast] = normals[indexFirst];
  38197. normals[indexLast + 1] = normals[indexFirst + 1];
  38198. normals[indexLast + 2] = normals[indexFirst + 2];
  38199. }
  38200. }
  38201. // sides
  38202. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38203. // Colors
  38204. var colors = null;
  38205. if (customColors) {
  38206. colors = new Float32Array(customColors.length * 4);
  38207. for (var c = 0; c < customColors.length; c++) {
  38208. colors[c * 4] = customColors[c].r;
  38209. colors[c * 4 + 1] = customColors[c].g;
  38210. colors[c * 4 + 2] = customColors[c].b;
  38211. colors[c * 4 + 3] = customColors[c].a;
  38212. }
  38213. }
  38214. // Result
  38215. var vertexData = new VertexData();
  38216. var positions32 = new Float32Array(positions);
  38217. var normals32 = new Float32Array(normals);
  38218. var uvs32 = new Float32Array(uvs);
  38219. vertexData.indices = indices;
  38220. vertexData.positions = positions32;
  38221. vertexData.normals = normals32;
  38222. vertexData.uvs = uvs32;
  38223. if (colors) {
  38224. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  38225. }
  38226. if (closePath) {
  38227. vertexData._idx = idx;
  38228. }
  38229. return vertexData;
  38230. };
  38231. /**
  38232. * Creates the VertexData for a box
  38233. * @param options an object used to set the following optional parameters for the box, required but can be empty
  38234. * * size sets the width, height and depth of the box to the value of size, optional default 1
  38235. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  38236. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  38237. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  38238. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  38239. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  38240. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38241. * * 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)
  38242. * * 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)
  38243. * @returns the VertexData of the box
  38244. */
  38245. VertexData.CreateBox = function (options) {
  38246. var normalsSource = [
  38247. new BABYLON.Vector3(0, 0, 1),
  38248. new BABYLON.Vector3(0, 0, -1),
  38249. new BABYLON.Vector3(1, 0, 0),
  38250. new BABYLON.Vector3(-1, 0, 0),
  38251. new BABYLON.Vector3(0, 1, 0),
  38252. new BABYLON.Vector3(0, -1, 0)
  38253. ];
  38254. var indices = [];
  38255. var positions = [];
  38256. var normals = [];
  38257. var uvs = [];
  38258. var width = options.width || options.size || 1;
  38259. var height = options.height || options.size || 1;
  38260. var depth = options.depth || options.size || 1;
  38261. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38262. var faceUV = options.faceUV || new Array(6);
  38263. var faceColors = options.faceColors;
  38264. var colors = [];
  38265. // default face colors and UV if undefined
  38266. for (var f = 0; f < 6; f++) {
  38267. if (faceUV[f] === undefined) {
  38268. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38269. }
  38270. if (faceColors && faceColors[f] === undefined) {
  38271. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38272. }
  38273. }
  38274. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  38275. // Create each face in turn.
  38276. for (var index = 0; index < normalsSource.length; index++) {
  38277. var normal = normalsSource[index];
  38278. // Get two vectors perpendicular to the face normal and to each other.
  38279. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  38280. var side2 = BABYLON.Vector3.Cross(normal, side1);
  38281. // Six indices (two triangles) per face.
  38282. var verticesLength = positions.length / 3;
  38283. indices.push(verticesLength);
  38284. indices.push(verticesLength + 1);
  38285. indices.push(verticesLength + 2);
  38286. indices.push(verticesLength);
  38287. indices.push(verticesLength + 2);
  38288. indices.push(verticesLength + 3);
  38289. // Four vertices per face.
  38290. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  38291. positions.push(vertex.x, vertex.y, vertex.z);
  38292. normals.push(normal.x, normal.y, normal.z);
  38293. uvs.push(faceUV[index].z, faceUV[index].w);
  38294. if (faceColors) {
  38295. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  38296. }
  38297. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  38298. positions.push(vertex.x, vertex.y, vertex.z);
  38299. normals.push(normal.x, normal.y, normal.z);
  38300. uvs.push(faceUV[index].x, faceUV[index].w);
  38301. if (faceColors) {
  38302. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  38303. }
  38304. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  38305. positions.push(vertex.x, vertex.y, vertex.z);
  38306. normals.push(normal.x, normal.y, normal.z);
  38307. uvs.push(faceUV[index].x, faceUV[index].y);
  38308. if (faceColors) {
  38309. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  38310. }
  38311. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  38312. positions.push(vertex.x, vertex.y, vertex.z);
  38313. normals.push(normal.x, normal.y, normal.z);
  38314. uvs.push(faceUV[index].z, faceUV[index].y);
  38315. if (faceColors) {
  38316. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  38317. }
  38318. }
  38319. // sides
  38320. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38321. // Result
  38322. var vertexData = new VertexData();
  38323. vertexData.indices = indices;
  38324. vertexData.positions = positions;
  38325. vertexData.normals = normals;
  38326. vertexData.uvs = uvs;
  38327. if (faceColors) {
  38328. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  38329. vertexData.colors = totalColors;
  38330. }
  38331. return vertexData;
  38332. };
  38333. /**
  38334. * Creates the VertexData for an ellipsoid, defaults to a sphere
  38335. * @param options an object used to set the following optional parameters for the box, required but can be empty
  38336. * * segments sets the number of horizontal strips optional, default 32
  38337. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  38338. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  38339. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  38340. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  38341. * * 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
  38342. * * 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
  38343. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38344. * * 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)
  38345. * * 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)
  38346. * @returns the VertexData of the ellipsoid
  38347. */
  38348. VertexData.CreateSphere = function (options) {
  38349. var segments = options.segments || 32;
  38350. var diameterX = options.diameterX || options.diameter || 1;
  38351. var diameterY = options.diameterY || options.diameter || 1;
  38352. var diameterZ = options.diameterZ || options.diameter || 1;
  38353. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  38354. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  38355. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38356. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  38357. var totalZRotationSteps = 2 + segments;
  38358. var totalYRotationSteps = 2 * totalZRotationSteps;
  38359. var indices = [];
  38360. var positions = [];
  38361. var normals = [];
  38362. var uvs = [];
  38363. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  38364. var normalizedZ = zRotationStep / totalZRotationSteps;
  38365. var angleZ = normalizedZ * Math.PI * slice;
  38366. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  38367. var normalizedY = yRotationStep / totalYRotationSteps;
  38368. var angleY = normalizedY * Math.PI * 2 * arc;
  38369. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  38370. var rotationY = BABYLON.Matrix.RotationY(angleY);
  38371. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  38372. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  38373. var vertex = complete.multiply(radius);
  38374. var normal = complete.divide(radius).normalize();
  38375. positions.push(vertex.x, vertex.y, vertex.z);
  38376. normals.push(normal.x, normal.y, normal.z);
  38377. uvs.push(normalizedY, normalizedZ);
  38378. }
  38379. if (zRotationStep > 0) {
  38380. var verticesCount = positions.length / 3;
  38381. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  38382. indices.push((firstIndex));
  38383. indices.push((firstIndex + 1));
  38384. indices.push(firstIndex + totalYRotationSteps + 1);
  38385. indices.push((firstIndex + totalYRotationSteps + 1));
  38386. indices.push((firstIndex + 1));
  38387. indices.push((firstIndex + totalYRotationSteps + 2));
  38388. }
  38389. }
  38390. }
  38391. // Sides
  38392. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38393. // Result
  38394. var vertexData = new VertexData();
  38395. vertexData.indices = indices;
  38396. vertexData.positions = positions;
  38397. vertexData.normals = normals;
  38398. vertexData.uvs = uvs;
  38399. return vertexData;
  38400. };
  38401. /**
  38402. * Creates the VertexData for a cylinder, cone or prism
  38403. * @param options an object used to set the following optional parameters for the box, required but can be empty
  38404. * * height sets the height (y direction) of the cylinder, optional, default 2
  38405. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  38406. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  38407. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  38408. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  38409. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  38410. * * 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
  38411. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38412. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38413. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  38414. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  38415. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38416. * * 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)
  38417. * * 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)
  38418. * @returns the VertexData of the cylinder, cone or prism
  38419. */
  38420. VertexData.CreateCylinder = function (options) {
  38421. var height = options.height || 2;
  38422. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  38423. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  38424. var tessellation = options.tessellation || 24;
  38425. var subdivisions = options.subdivisions || 1;
  38426. var hasRings = options.hasRings ? true : false;
  38427. var enclose = options.enclose ? true : false;
  38428. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  38429. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38430. var faceUV = options.faceUV || new Array(3);
  38431. var faceColors = options.faceColors;
  38432. // default face colors and UV if undefined
  38433. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  38434. var ringNb = (hasRings) ? subdivisions : 1;
  38435. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  38436. var f;
  38437. for (f = 0; f < surfaceNb; f++) {
  38438. if (faceColors && faceColors[f] === undefined) {
  38439. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38440. }
  38441. }
  38442. for (f = 0; f < surfaceNb; f++) {
  38443. if (faceUV && faceUV[f] === undefined) {
  38444. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38445. }
  38446. }
  38447. var indices = new Array();
  38448. var positions = new Array();
  38449. var normals = new Array();
  38450. var uvs = new Array();
  38451. var colors = new Array();
  38452. var angle_step = Math.PI * 2 * arc / tessellation;
  38453. var angle;
  38454. var h;
  38455. var radius;
  38456. var tan = (diameterBottom - diameterTop) / 2 / height;
  38457. var ringVertex = BABYLON.Vector3.Zero();
  38458. var ringNormal = BABYLON.Vector3.Zero();
  38459. var ringFirstVertex = BABYLON.Vector3.Zero();
  38460. var ringFirstNormal = BABYLON.Vector3.Zero();
  38461. var quadNormal = BABYLON.Vector3.Zero();
  38462. var Y = BABYLON.Axis.Y;
  38463. // positions, normals, uvs
  38464. var i;
  38465. var j;
  38466. var r;
  38467. var ringIdx = 1;
  38468. var s = 1; // surface index
  38469. var cs = 0;
  38470. var v = 0;
  38471. for (i = 0; i <= subdivisions; i++) {
  38472. h = i / subdivisions;
  38473. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  38474. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  38475. for (r = 0; r < ringIdx; r++) {
  38476. if (hasRings) {
  38477. s += r;
  38478. }
  38479. if (enclose) {
  38480. s += 2 * r;
  38481. }
  38482. for (j = 0; j <= tessellation; j++) {
  38483. angle = j * angle_step;
  38484. // position
  38485. ringVertex.x = Math.cos(-angle) * radius;
  38486. ringVertex.y = -height / 2 + h * height;
  38487. ringVertex.z = Math.sin(-angle) * radius;
  38488. // normal
  38489. if (diameterTop === 0 && i === subdivisions) {
  38490. // if no top cap, reuse former normals
  38491. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  38492. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  38493. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  38494. }
  38495. else {
  38496. ringNormal.x = ringVertex.x;
  38497. ringNormal.z = ringVertex.z;
  38498. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  38499. ringNormal.normalize();
  38500. }
  38501. // keep first ring vertex values for enclose
  38502. if (j === 0) {
  38503. ringFirstVertex.copyFrom(ringVertex);
  38504. ringFirstNormal.copyFrom(ringNormal);
  38505. }
  38506. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  38507. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  38508. if (hasRings) {
  38509. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  38510. }
  38511. else {
  38512. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  38513. }
  38514. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  38515. if (faceColors) {
  38516. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  38517. }
  38518. }
  38519. // if enclose, add four vertices and their dedicated normals
  38520. if (arc !== 1 && enclose) {
  38521. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  38522. positions.push(0, ringVertex.y, 0);
  38523. positions.push(0, ringVertex.y, 0);
  38524. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  38525. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  38526. quadNormal.normalize();
  38527. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  38528. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  38529. quadNormal.normalize();
  38530. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  38531. if (hasRings) {
  38532. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  38533. }
  38534. else {
  38535. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  38536. }
  38537. uvs.push(faceUV[s + 1].x, v);
  38538. uvs.push(faceUV[s + 1].z, v);
  38539. if (hasRings) {
  38540. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  38541. }
  38542. else {
  38543. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  38544. }
  38545. uvs.push(faceUV[s + 2].x, v);
  38546. uvs.push(faceUV[s + 2].z, v);
  38547. if (faceColors) {
  38548. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  38549. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  38550. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  38551. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  38552. }
  38553. }
  38554. if (cs !== s) {
  38555. cs = s;
  38556. }
  38557. }
  38558. }
  38559. // indices
  38560. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  38561. var s;
  38562. i = 0;
  38563. for (s = 0; s < subdivisions; s++) {
  38564. var i0 = 0;
  38565. var i1 = 0;
  38566. var i2 = 0;
  38567. var i3 = 0;
  38568. for (j = 0; j < tessellation; j++) {
  38569. i0 = i * (e + 1) + j;
  38570. i1 = (i + 1) * (e + 1) + j;
  38571. i2 = i * (e + 1) + (j + 1);
  38572. i3 = (i + 1) * (e + 1) + (j + 1);
  38573. indices.push(i0, i1, i2);
  38574. indices.push(i3, i2, i1);
  38575. }
  38576. if (arc !== 1 && enclose) { // if enclose, add two quads
  38577. indices.push(i0 + 2, i1 + 2, i2 + 2);
  38578. indices.push(i3 + 2, i2 + 2, i1 + 2);
  38579. indices.push(i0 + 4, i1 + 4, i2 + 4);
  38580. indices.push(i3 + 4, i2 + 4, i1 + 4);
  38581. }
  38582. i = (hasRings) ? (i + 2) : (i + 1);
  38583. }
  38584. // Caps
  38585. var createCylinderCap = function (isTop) {
  38586. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  38587. if (radius === 0) {
  38588. return;
  38589. }
  38590. // Cap positions, normals & uvs
  38591. var angle;
  38592. var circleVector;
  38593. var i;
  38594. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  38595. var c = null;
  38596. if (faceColors) {
  38597. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  38598. }
  38599. // cap center
  38600. var vbase = positions.length / 3;
  38601. var offset = isTop ? height / 2 : -height / 2;
  38602. var center = new BABYLON.Vector3(0, offset, 0);
  38603. positions.push(center.x, center.y, center.z);
  38604. normals.push(0, isTop ? 1 : -1, 0);
  38605. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  38606. if (c) {
  38607. colors.push(c.r, c.g, c.b, c.a);
  38608. }
  38609. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  38610. for (i = 0; i <= tessellation; i++) {
  38611. angle = Math.PI * 2 * i * arc / tessellation;
  38612. var cos = Math.cos(-angle);
  38613. var sin = Math.sin(-angle);
  38614. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  38615. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  38616. positions.push(circleVector.x, circleVector.y, circleVector.z);
  38617. normals.push(0, isTop ? 1 : -1, 0);
  38618. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  38619. if (c) {
  38620. colors.push(c.r, c.g, c.b, c.a);
  38621. }
  38622. }
  38623. // Cap indices
  38624. for (i = 0; i < tessellation; i++) {
  38625. if (!isTop) {
  38626. indices.push(vbase);
  38627. indices.push(vbase + (i + 1));
  38628. indices.push(vbase + (i + 2));
  38629. }
  38630. else {
  38631. indices.push(vbase);
  38632. indices.push(vbase + (i + 2));
  38633. indices.push(vbase + (i + 1));
  38634. }
  38635. }
  38636. };
  38637. // add caps to geometry
  38638. createCylinderCap(false);
  38639. createCylinderCap(true);
  38640. // Sides
  38641. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38642. var vertexData = new VertexData();
  38643. vertexData.indices = indices;
  38644. vertexData.positions = positions;
  38645. vertexData.normals = normals;
  38646. vertexData.uvs = uvs;
  38647. if (faceColors) {
  38648. vertexData.colors = colors;
  38649. }
  38650. return vertexData;
  38651. };
  38652. /**
  38653. * Creates the VertexData for a torus
  38654. * @param options an object used to set the following optional parameters for the box, required but can be empty
  38655. * * diameter the diameter of the torus, optional default 1
  38656. * * thickness the diameter of the tube forming the torus, optional default 0.5
  38657. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  38658. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38659. * * 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)
  38660. * * 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)
  38661. * @returns the VertexData of the torus
  38662. */
  38663. VertexData.CreateTorus = function (options) {
  38664. var indices = [];
  38665. var positions = [];
  38666. var normals = [];
  38667. var uvs = [];
  38668. var diameter = options.diameter || 1;
  38669. var thickness = options.thickness || 0.5;
  38670. var tessellation = options.tessellation || 16;
  38671. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38672. var stride = tessellation + 1;
  38673. for (var i = 0; i <= tessellation; i++) {
  38674. var u = i / tessellation;
  38675. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  38676. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  38677. for (var j = 0; j <= tessellation; j++) {
  38678. var v = 1 - j / tessellation;
  38679. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  38680. var dx = Math.cos(innerAngle);
  38681. var dy = Math.sin(innerAngle);
  38682. // Create a vertex.
  38683. var normal = new BABYLON.Vector3(dx, dy, 0);
  38684. var position = normal.scale(thickness / 2);
  38685. var textureCoordinate = new BABYLON.Vector2(u, v);
  38686. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  38687. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  38688. positions.push(position.x, position.y, position.z);
  38689. normals.push(normal.x, normal.y, normal.z);
  38690. uvs.push(textureCoordinate.x, textureCoordinate.y);
  38691. // And create indices for two triangles.
  38692. var nextI = (i + 1) % stride;
  38693. var nextJ = (j + 1) % stride;
  38694. indices.push(i * stride + j);
  38695. indices.push(i * stride + nextJ);
  38696. indices.push(nextI * stride + j);
  38697. indices.push(i * stride + nextJ);
  38698. indices.push(nextI * stride + nextJ);
  38699. indices.push(nextI * stride + j);
  38700. }
  38701. }
  38702. // Sides
  38703. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38704. // Result
  38705. var vertexData = new VertexData();
  38706. vertexData.indices = indices;
  38707. vertexData.positions = positions;
  38708. vertexData.normals = normals;
  38709. vertexData.uvs = uvs;
  38710. return vertexData;
  38711. };
  38712. /**
  38713. * Creates the VertexData of the LineSystem
  38714. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  38715. * - lines an array of lines, each line being an array of successive Vector3
  38716. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  38717. * @returns the VertexData of the LineSystem
  38718. */
  38719. VertexData.CreateLineSystem = function (options) {
  38720. var indices = [];
  38721. var positions = [];
  38722. var lines = options.lines;
  38723. var colors = options.colors;
  38724. var vertexColors = [];
  38725. var idx = 0;
  38726. for (var l = 0; l < lines.length; l++) {
  38727. var points = lines[l];
  38728. for (var index = 0; index < points.length; index++) {
  38729. positions.push(points[index].x, points[index].y, points[index].z);
  38730. if (colors) {
  38731. var color = colors[l];
  38732. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  38733. }
  38734. if (index > 0) {
  38735. indices.push(idx - 1);
  38736. indices.push(idx);
  38737. }
  38738. idx++;
  38739. }
  38740. }
  38741. var vertexData = new VertexData();
  38742. vertexData.indices = indices;
  38743. vertexData.positions = positions;
  38744. if (colors) {
  38745. vertexData.colors = vertexColors;
  38746. }
  38747. return vertexData;
  38748. };
  38749. /**
  38750. * Create the VertexData for a DashedLines
  38751. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  38752. * - points an array successive Vector3
  38753. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  38754. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  38755. * - dashNb the intended total number of dashes, optional, default 200
  38756. * @returns the VertexData for the DashedLines
  38757. */
  38758. VertexData.CreateDashedLines = function (options) {
  38759. var dashSize = options.dashSize || 3;
  38760. var gapSize = options.gapSize || 1;
  38761. var dashNb = options.dashNb || 200;
  38762. var points = options.points;
  38763. var positions = new Array();
  38764. var indices = new Array();
  38765. var curvect = BABYLON.Vector3.Zero();
  38766. var lg = 0;
  38767. var nb = 0;
  38768. var shft = 0;
  38769. var dashshft = 0;
  38770. var curshft = 0;
  38771. var idx = 0;
  38772. var i = 0;
  38773. for (i = 0; i < points.length - 1; i++) {
  38774. points[i + 1].subtractToRef(points[i], curvect);
  38775. lg += curvect.length();
  38776. }
  38777. shft = lg / dashNb;
  38778. dashshft = dashSize * shft / (dashSize + gapSize);
  38779. for (i = 0; i < points.length - 1; i++) {
  38780. points[i + 1].subtractToRef(points[i], curvect);
  38781. nb = Math.floor(curvect.length() / shft);
  38782. curvect.normalize();
  38783. for (var j = 0; j < nb; j++) {
  38784. curshft = shft * j;
  38785. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  38786. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  38787. indices.push(idx, idx + 1);
  38788. idx += 2;
  38789. }
  38790. }
  38791. // Result
  38792. var vertexData = new VertexData();
  38793. vertexData.positions = positions;
  38794. vertexData.indices = indices;
  38795. return vertexData;
  38796. };
  38797. /**
  38798. * Creates the VertexData for a Ground
  38799. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  38800. * - width the width (x direction) of the ground, optional, default 1
  38801. * - height the height (z direction) of the ground, optional, default 1
  38802. * - subdivisions the number of subdivisions per side, optional, default 1
  38803. * @returns the VertexData of the Ground
  38804. */
  38805. VertexData.CreateGround = function (options) {
  38806. var indices = [];
  38807. var positions = [];
  38808. var normals = [];
  38809. var uvs = [];
  38810. var row, col;
  38811. var width = options.width || 1;
  38812. var height = options.height || 1;
  38813. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  38814. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  38815. for (row = 0; row <= subdivisionsY; row++) {
  38816. for (col = 0; col <= subdivisionsX; col++) {
  38817. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  38818. var normal = new BABYLON.Vector3(0, 1.0, 0);
  38819. positions.push(position.x, position.y, position.z);
  38820. normals.push(normal.x, normal.y, normal.z);
  38821. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  38822. }
  38823. }
  38824. for (row = 0; row < subdivisionsY; row++) {
  38825. for (col = 0; col < subdivisionsX; col++) {
  38826. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  38827. indices.push(col + 1 + row * (subdivisionsX + 1));
  38828. indices.push(col + row * (subdivisionsX + 1));
  38829. indices.push(col + (row + 1) * (subdivisionsX + 1));
  38830. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  38831. indices.push(col + row * (subdivisionsX + 1));
  38832. }
  38833. }
  38834. // Result
  38835. var vertexData = new VertexData();
  38836. vertexData.indices = indices;
  38837. vertexData.positions = positions;
  38838. vertexData.normals = normals;
  38839. vertexData.uvs = uvs;
  38840. return vertexData;
  38841. };
  38842. /**
  38843. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  38844. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  38845. * * xmin the ground minimum X coordinate, optional, default -1
  38846. * * zmin the ground minimum Z coordinate, optional, default -1
  38847. * * xmax the ground maximum X coordinate, optional, default 1
  38848. * * zmax the ground maximum Z coordinate, optional, default 1
  38849. * * 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}
  38850. * * 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}
  38851. * @returns the VertexData of the TiledGround
  38852. */
  38853. VertexData.CreateTiledGround = function (options) {
  38854. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  38855. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  38856. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  38857. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  38858. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  38859. var precision = options.precision || { w: 1, h: 1 };
  38860. var indices = new Array();
  38861. var positions = new Array();
  38862. var normals = new Array();
  38863. var uvs = new Array();
  38864. var row, col, tileRow, tileCol;
  38865. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  38866. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  38867. precision.w = (precision.w < 1) ? 1 : precision.w;
  38868. precision.h = (precision.h < 1) ? 1 : precision.h;
  38869. var tileSize = {
  38870. 'w': (xmax - xmin) / subdivisions.w,
  38871. 'h': (zmax - zmin) / subdivisions.h
  38872. };
  38873. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  38874. // Indices
  38875. var base = positions.length / 3;
  38876. var rowLength = precision.w + 1;
  38877. for (row = 0; row < precision.h; row++) {
  38878. for (col = 0; col < precision.w; col++) {
  38879. var square = [
  38880. base + col + row * rowLength,
  38881. base + (col + 1) + row * rowLength,
  38882. base + (col + 1) + (row + 1) * rowLength,
  38883. base + col + (row + 1) * rowLength
  38884. ];
  38885. indices.push(square[1]);
  38886. indices.push(square[2]);
  38887. indices.push(square[3]);
  38888. indices.push(square[0]);
  38889. indices.push(square[1]);
  38890. indices.push(square[3]);
  38891. }
  38892. }
  38893. // Position, normals and uvs
  38894. var position = BABYLON.Vector3.Zero();
  38895. var normal = new BABYLON.Vector3(0, 1.0, 0);
  38896. for (row = 0; row <= precision.h; row++) {
  38897. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  38898. for (col = 0; col <= precision.w; col++) {
  38899. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  38900. position.y = 0;
  38901. positions.push(position.x, position.y, position.z);
  38902. normals.push(normal.x, normal.y, normal.z);
  38903. uvs.push(col / precision.w, row / precision.h);
  38904. }
  38905. }
  38906. }
  38907. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  38908. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  38909. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  38910. }
  38911. }
  38912. // Result
  38913. var vertexData = new VertexData();
  38914. vertexData.indices = indices;
  38915. vertexData.positions = positions;
  38916. vertexData.normals = normals;
  38917. vertexData.uvs = uvs;
  38918. return vertexData;
  38919. };
  38920. /**
  38921. * Creates the VertexData of the Ground designed from a heightmap
  38922. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  38923. * * width the width (x direction) of the ground
  38924. * * height the height (z direction) of the ground
  38925. * * subdivisions the number of subdivisions per side
  38926. * * minHeight the minimum altitude on the ground, optional, default 0
  38927. * * maxHeight the maximum altitude on the ground, optional default 1
  38928. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  38929. * * buffer the array holding the image color data
  38930. * * bufferWidth the width of image
  38931. * * bufferHeight the height of image
  38932. * * alphaFilter Remove any data where the alpha channel is below this value, defaults 0 (all data visible)
  38933. * @returns the VertexData of the Ground designed from a heightmap
  38934. */
  38935. VertexData.CreateGroundFromHeightMap = function (options) {
  38936. var indices = [];
  38937. var positions = [];
  38938. var normals = [];
  38939. var uvs = [];
  38940. var row, col;
  38941. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  38942. var alphaFilter = options.alphaFilter || 0.0;
  38943. // Vertices
  38944. for (row = 0; row <= options.subdivisions; row++) {
  38945. for (col = 0; col <= options.subdivisions; col++) {
  38946. 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));
  38947. // Compute height
  38948. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  38949. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  38950. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  38951. var r = options.buffer[pos] / 255.0;
  38952. var g = options.buffer[pos + 1] / 255.0;
  38953. var b = options.buffer[pos + 2] / 255.0;
  38954. var a = options.buffer[pos + 3] / 255.0;
  38955. var gradient = r * filter.r + g * filter.g + b * filter.b;
  38956. // If our alpha channel is not within our filter then we will assign a 'special' height
  38957. // Then when building the indices, we will ignore any vertex that is using the special height
  38958. if (a >= alphaFilter)
  38959. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  38960. else {
  38961. position.y = options.minHeight - BABYLON.Epsilon; // We can't have a height below minHeight, normally.
  38962. }
  38963. // Add vertex
  38964. positions.push(position.x, position.y, position.z);
  38965. normals.push(0, 0, 0);
  38966. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  38967. }
  38968. }
  38969. // Indices
  38970. for (row = 0; row < options.subdivisions; row++) {
  38971. for (col = 0; col < options.subdivisions; col++) {
  38972. // Calculate Indices
  38973. var idx1 = (col + 1 + (row + 1) * (options.subdivisions + 1));
  38974. var idx2 = (col + 1 + row * (options.subdivisions + 1));
  38975. var idx3 = (col + row * (options.subdivisions + 1));
  38976. var idx4 = (col + (row + 1) * (options.subdivisions + 1));
  38977. // Check that all indices are visible (based on our special height)
  38978. // Only display the vertex if all Indices are visible
  38979. // Positions are stored x,y,z for each vertex, hence the * 3 and + 1 for height
  38980. var isVisibleIdx1 = positions[idx1 * 3 + 1] >= options.minHeight;
  38981. var isVisibleIdx2 = positions[idx2 * 3 + 1] >= options.minHeight;
  38982. var isVisibleIdx3 = positions[idx3 * 3 + 1] >= options.minHeight;
  38983. if (isVisibleIdx1 && isVisibleIdx2 && isVisibleIdx3) {
  38984. indices.push(idx1);
  38985. indices.push(idx2);
  38986. indices.push(idx3);
  38987. }
  38988. var isVisibleIdx4 = positions[idx4 * 3 + 1] >= options.minHeight;
  38989. if (isVisibleIdx4 && isVisibleIdx1 && isVisibleIdx3) {
  38990. indices.push(idx4);
  38991. indices.push(idx1);
  38992. indices.push(idx3);
  38993. }
  38994. }
  38995. }
  38996. // Normals
  38997. VertexData.ComputeNormals(positions, indices, normals);
  38998. // Result
  38999. var vertexData = new VertexData();
  39000. vertexData.indices = indices;
  39001. vertexData.positions = positions;
  39002. vertexData.normals = normals;
  39003. vertexData.uvs = uvs;
  39004. return vertexData;
  39005. };
  39006. /**
  39007. * Creates the VertexData for a Plane
  39008. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  39009. * * size sets the width and height of the plane to the value of size, optional default 1
  39010. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  39011. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  39012. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39013. * * 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)
  39014. * * 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)
  39015. * @returns the VertexData of the box
  39016. */
  39017. VertexData.CreatePlane = function (options) {
  39018. var indices = [];
  39019. var positions = [];
  39020. var normals = [];
  39021. var uvs = [];
  39022. var width = options.width || options.size || 1;
  39023. var height = options.height || options.size || 1;
  39024. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39025. // Vertices
  39026. var halfWidth = width / 2.0;
  39027. var halfHeight = height / 2.0;
  39028. positions.push(-halfWidth, -halfHeight, 0);
  39029. normals.push(0, 0, -1.0);
  39030. uvs.push(0.0, 0.0);
  39031. positions.push(halfWidth, -halfHeight, 0);
  39032. normals.push(0, 0, -1.0);
  39033. uvs.push(1.0, 0.0);
  39034. positions.push(halfWidth, halfHeight, 0);
  39035. normals.push(0, 0, -1.0);
  39036. uvs.push(1.0, 1.0);
  39037. positions.push(-halfWidth, halfHeight, 0);
  39038. normals.push(0, 0, -1.0);
  39039. uvs.push(0.0, 1.0);
  39040. // Indices
  39041. indices.push(0);
  39042. indices.push(1);
  39043. indices.push(2);
  39044. indices.push(0);
  39045. indices.push(2);
  39046. indices.push(3);
  39047. // Sides
  39048. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  39049. // Result
  39050. var vertexData = new VertexData();
  39051. vertexData.indices = indices;
  39052. vertexData.positions = positions;
  39053. vertexData.normals = normals;
  39054. vertexData.uvs = uvs;
  39055. return vertexData;
  39056. };
  39057. /**
  39058. * Creates the VertexData of the Disc or regular Polygon
  39059. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  39060. * * radius the radius of the disc, optional default 0.5
  39061. * * tessellation the number of polygon sides, optional, default 64
  39062. * * 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
  39063. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39064. * * 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)
  39065. * * 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)
  39066. * @returns the VertexData of the box
  39067. */
  39068. VertexData.CreateDisc = function (options) {
  39069. var positions = new Array();
  39070. var indices = new Array();
  39071. var normals = new Array();
  39072. var uvs = new Array();
  39073. var radius = options.radius || 0.5;
  39074. var tessellation = options.tessellation || 64;
  39075. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  39076. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39077. // positions and uvs
  39078. positions.push(0, 0, 0); // disc center first
  39079. uvs.push(0.5, 0.5);
  39080. var theta = Math.PI * 2 * arc;
  39081. var step = theta / tessellation;
  39082. for (var a = 0; a < theta; a += step) {
  39083. var x = Math.cos(a);
  39084. var y = Math.sin(a);
  39085. var u = (x + 1) / 2;
  39086. var v = (1 - y) / 2;
  39087. positions.push(radius * x, radius * y, 0);
  39088. uvs.push(u, v);
  39089. }
  39090. if (arc === 1) {
  39091. positions.push(positions[3], positions[4], positions[5]); // close the circle
  39092. uvs.push(uvs[2], uvs[3]);
  39093. }
  39094. //indices
  39095. var vertexNb = positions.length / 3;
  39096. for (var i = 1; i < vertexNb - 1; i++) {
  39097. indices.push(i + 1, 0, i);
  39098. }
  39099. // result
  39100. VertexData.ComputeNormals(positions, indices, normals);
  39101. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  39102. var vertexData = new VertexData();
  39103. vertexData.indices = indices;
  39104. vertexData.positions = positions;
  39105. vertexData.normals = normals;
  39106. vertexData.uvs = uvs;
  39107. return vertexData;
  39108. };
  39109. /**
  39110. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  39111. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  39112. * @param polygon a mesh built from polygonTriangulation.build()
  39113. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39114. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  39115. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  39116. * @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)
  39117. * @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)
  39118. * @returns the VertexData of the Polygon
  39119. */
  39120. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  39121. var faceUV = fUV || new Array(3);
  39122. var faceColors = fColors;
  39123. var colors = [];
  39124. // default face colors and UV if undefined
  39125. for (var f = 0; f < 3; f++) {
  39126. if (faceUV[f] === undefined) {
  39127. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  39128. }
  39129. if (faceColors && faceColors[f] === undefined) {
  39130. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  39131. }
  39132. }
  39133. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39134. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  39135. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  39136. var indices = polygon.getIndices();
  39137. // set face colours and textures
  39138. var idx = 0;
  39139. var face = 0;
  39140. for (var index = 0; index < normals.length; index += 3) {
  39141. //Edge Face no. 1
  39142. if (Math.abs(normals[index + 1]) < 0.001) {
  39143. face = 1;
  39144. }
  39145. //Top Face no. 0
  39146. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  39147. face = 0;
  39148. }
  39149. //Bottom Face no. 2
  39150. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  39151. face = 2;
  39152. }
  39153. idx = index / 3;
  39154. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  39155. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  39156. if (faceColors) {
  39157. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  39158. }
  39159. }
  39160. // sides
  39161. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  39162. // Result
  39163. var vertexData = new VertexData();
  39164. vertexData.indices = indices;
  39165. vertexData.positions = positions;
  39166. vertexData.normals = normals;
  39167. vertexData.uvs = uvs;
  39168. if (faceColors) {
  39169. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  39170. vertexData.colors = totalColors;
  39171. }
  39172. return vertexData;
  39173. };
  39174. /**
  39175. * Creates the VertexData of the IcoSphere
  39176. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  39177. * * radius the radius of the IcoSphere, optional default 1
  39178. * * radiusX allows stretching in the x direction, optional, default radius
  39179. * * radiusY allows stretching in the y direction, optional, default radius
  39180. * * radiusZ allows stretching in the z direction, optional, default radius
  39181. * * flat when true creates a flat shaded mesh, optional, default true
  39182. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  39183. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39184. * * 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)
  39185. * * 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)
  39186. * @returns the VertexData of the IcoSphere
  39187. */
  39188. VertexData.CreateIcoSphere = function (options) {
  39189. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39190. var radius = options.radius || 1;
  39191. var flat = (options.flat === undefined) ? true : options.flat;
  39192. var subdivisions = options.subdivisions || 4;
  39193. var radiusX = options.radiusX || radius;
  39194. var radiusY = options.radiusY || radius;
  39195. var radiusZ = options.radiusZ || radius;
  39196. var t = (1 + Math.sqrt(5)) / 2;
  39197. // 12 vertex x,y,z
  39198. var ico_vertices = [
  39199. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  39200. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  39201. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  39202. ];
  39203. // index of 3 vertex makes a face of icopshere
  39204. var ico_indices = [
  39205. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  39206. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  39207. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  39208. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  39209. ];
  39210. // vertex for uv have aliased position, not for UV
  39211. var vertices_unalias_id = [
  39212. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  39213. // vertex alias
  39214. 0,
  39215. 2,
  39216. 3,
  39217. 3,
  39218. 3,
  39219. 4,
  39220. 7,
  39221. 8,
  39222. 9,
  39223. 9,
  39224. 10,
  39225. 11 // 23: B + 12
  39226. ];
  39227. // uv as integer step (not pixels !)
  39228. var ico_vertexuv = [
  39229. 5, 1, 3, 1, 6, 4, 0, 0,
  39230. 5, 3, 4, 2, 2, 2, 4, 0,
  39231. 2, 0, 1, 1, 6, 0, 6, 2,
  39232. // vertex alias (for same vertex on different faces)
  39233. 0, 4,
  39234. 3, 3,
  39235. 4, 4,
  39236. 3, 1,
  39237. 4, 2,
  39238. 4, 4,
  39239. 0, 2,
  39240. 1, 1,
  39241. 2, 2,
  39242. 3, 3,
  39243. 1, 3,
  39244. 2, 4 // 23: B + 12
  39245. ];
  39246. // Vertices[0, 1, ...9, A, B] : position on UV plane
  39247. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  39248. // First island of uv mapping
  39249. // v = 4h 3+ 2
  39250. // v = 3h 9+ 4
  39251. // v = 2h 9+ 5 B
  39252. // v = 1h 9 1 0
  39253. // v = 0h 3 8 7 A
  39254. // u = 0 1 2 3 4 5 6 *a
  39255. // Second island of uv mapping
  39256. // v = 4h 0+ B+ 4+
  39257. // v = 3h A+ 2+
  39258. // v = 2h 7+ 6 3+
  39259. // v = 1h 8+ 3+
  39260. // v = 0h
  39261. // u = 0 1 2 3 4 5 6 *a
  39262. // Face layout on texture UV mapping
  39263. // ============
  39264. // \ 4 /\ 16 / ======
  39265. // \ / \ / /\ 11 /
  39266. // \/ 7 \/ / \ /
  39267. // ======= / 10 \/
  39268. // /\ 17 /\ =======
  39269. // / \ / \ \ 15 /\
  39270. // / 8 \/ 12 \ \ / \
  39271. // ============ \/ 6 \
  39272. // \ 18 /\ ============
  39273. // \ / \ \ 5 /\ 0 /
  39274. // \/ 13 \ \ / \ /
  39275. // ======= \/ 1 \/
  39276. // =============
  39277. // /\ 19 /\ 2 /\
  39278. // / \ / \ / \
  39279. // / 14 \/ 9 \/ 3 \
  39280. // ===================
  39281. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  39282. var ustep = 138 / 1024;
  39283. var vstep = 239 / 1024;
  39284. var uoffset = 60 / 1024;
  39285. var voffset = 26 / 1024;
  39286. // Second island should have margin, not to touch the first island
  39287. // avoid any borderline artefact in pixel rounding
  39288. var island_u_offset = -40 / 1024;
  39289. var island_v_offset = +20 / 1024;
  39290. // face is either island 0 or 1 :
  39291. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  39292. var island = [
  39293. 0, 0, 0, 0, 1,
  39294. 0, 0, 1, 1, 0,
  39295. 0, 0, 1, 1, 0,
  39296. 0, 1, 1, 1, 0 // 15 - 19
  39297. ];
  39298. var indices = new Array();
  39299. var positions = new Array();
  39300. var normals = new Array();
  39301. var uvs = new Array();
  39302. var current_indice = 0;
  39303. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  39304. var face_vertex_pos = new Array(3);
  39305. var face_vertex_uv = new Array(3);
  39306. var v012;
  39307. for (v012 = 0; v012 < 3; v012++) {
  39308. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  39309. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  39310. }
  39311. // create all with normals
  39312. for (var face = 0; face < 20; face++) {
  39313. // 3 vertex per face
  39314. for (v012 = 0; v012 < 3; v012++) {
  39315. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  39316. var v_id = ico_indices[3 * face + v012];
  39317. // vertex have 3D position (x,y,z)
  39318. 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]);
  39319. // Normalize to get normal, then scale to radius
  39320. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  39321. // uv Coordinates from vertex ID
  39322. 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);
  39323. }
  39324. // Subdivide the face (interpolate pos, norm, uv)
  39325. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  39326. // - norm is linear interpolation of vertex corner normal
  39327. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  39328. // - uv is linear interpolation
  39329. //
  39330. // Topology is as below for sub-divide by 2
  39331. // vertex shown as v0,v1,v2
  39332. // interp index is i1 to progress in range [v0,v1[
  39333. // interp index is i2 to progress in range [v0,v2[
  39334. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  39335. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  39336. //
  39337. //
  39338. // i2 v2
  39339. // ^ ^
  39340. // / / \
  39341. // / / \
  39342. // / / \
  39343. // / / (0,1) \
  39344. // / #---------\
  39345. // / / \ (0,0)'/ \
  39346. // / / \ / \
  39347. // / / \ / \
  39348. // / / (0,0) \ / (1,0) \
  39349. // / #---------#---------\
  39350. // v0 v1
  39351. //
  39352. // --------------------> i1
  39353. //
  39354. // interp of (i1,i2):
  39355. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  39356. // along i1 : lerp(x0,x1, i1/(S-i2))
  39357. //
  39358. // centroid of triangle is needed to get help normal computation
  39359. // (c1,c2) are used for centroid location
  39360. var interp_vertex = function (i1, i2, c1, c2) {
  39361. // vertex is interpolated from
  39362. // - face_vertex_pos[0..2]
  39363. // - face_vertex_uv[0..2]
  39364. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  39365. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  39366. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  39367. pos_interp.normalize();
  39368. var vertex_normal;
  39369. if (flat) {
  39370. // in flat mode, recalculate normal as face centroid normal
  39371. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  39372. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  39373. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  39374. }
  39375. else {
  39376. // in smooth mode, recalculate normal from each single vertex position
  39377. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  39378. }
  39379. // Vertex normal need correction due to X,Y,Z radius scaling
  39380. vertex_normal.x /= radiusX;
  39381. vertex_normal.y /= radiusY;
  39382. vertex_normal.z /= radiusZ;
  39383. vertex_normal.normalize();
  39384. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  39385. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  39386. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  39387. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  39388. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  39389. uvs.push(uv_interp.x, uv_interp.y);
  39390. // push each vertex has member of a face
  39391. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  39392. indices.push(current_indice);
  39393. current_indice++;
  39394. };
  39395. for (var i2 = 0; i2 < subdivisions; i2++) {
  39396. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  39397. // face : (i1,i2) for /\ :
  39398. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  39399. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  39400. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  39401. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  39402. if (i1 + i2 + 1 < subdivisions) {
  39403. // face : (i1,i2)' for \/ :
  39404. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  39405. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  39406. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  39407. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  39408. }
  39409. }
  39410. }
  39411. }
  39412. // Sides
  39413. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  39414. // Result
  39415. var vertexData = new VertexData();
  39416. vertexData.indices = indices;
  39417. vertexData.positions = positions;
  39418. vertexData.normals = normals;
  39419. vertexData.uvs = uvs;
  39420. return vertexData;
  39421. };
  39422. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  39423. /**
  39424. * Creates the VertexData for a Polyhedron
  39425. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  39426. * * type provided types are:
  39427. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  39428. * * 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)
  39429. * * size the size of the IcoSphere, optional default 1
  39430. * * sizeX allows stretching in the x direction, optional, default size
  39431. * * sizeY allows stretching in the y direction, optional, default size
  39432. * * sizeZ allows stretching in the z direction, optional, default size
  39433. * * 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
  39434. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  39435. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  39436. * * flat when true creates a flat shaded mesh, optional, default true
  39437. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  39438. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39439. * * 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)
  39440. * * 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)
  39441. * @returns the VertexData of the Polyhedron
  39442. */
  39443. VertexData.CreatePolyhedron = function (options) {
  39444. // provided polyhedron types :
  39445. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  39446. // 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)
  39447. var polyhedra = [];
  39448. 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]] };
  39449. 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]] };
  39450. polyhedra[2] = {
  39451. 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]],
  39452. 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]]
  39453. };
  39454. polyhedra[3] = {
  39455. 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]],
  39456. 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]]
  39457. };
  39458. polyhedra[4] = {
  39459. 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]],
  39460. 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]]
  39461. };
  39462. 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]] };
  39463. 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]] };
  39464. 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]] };
  39465. 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]] };
  39466. 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]] };
  39467. 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]] };
  39468. 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]] };
  39469. 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]] };
  39470. 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]] };
  39471. polyhedra[14] = {
  39472. 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]],
  39473. 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]]
  39474. };
  39475. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  39476. var size = options.size;
  39477. var sizeX = options.sizeX || size || 1;
  39478. var sizeY = options.sizeY || size || 1;
  39479. var sizeZ = options.sizeZ || size || 1;
  39480. var data = options.custom || polyhedra[type];
  39481. var nbfaces = data.face.length;
  39482. var faceUV = options.faceUV || new Array(nbfaces);
  39483. var faceColors = options.faceColors;
  39484. var flat = (options.flat === undefined) ? true : options.flat;
  39485. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39486. var positions = new Array();
  39487. var indices = new Array();
  39488. var normals = new Array();
  39489. var uvs = new Array();
  39490. var colors = new Array();
  39491. var index = 0;
  39492. var faceIdx = 0; // face cursor in the array "indexes"
  39493. var indexes = new Array();
  39494. var i = 0;
  39495. var f = 0;
  39496. var u, v, ang, x, y, tmp;
  39497. // default face colors and UV if undefined
  39498. if (flat) {
  39499. for (f = 0; f < nbfaces; f++) {
  39500. if (faceColors && faceColors[f] === undefined) {
  39501. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  39502. }
  39503. if (faceUV && faceUV[f] === undefined) {
  39504. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  39505. }
  39506. }
  39507. }
  39508. if (!flat) {
  39509. for (i = 0; i < data.vertex.length; i++) {
  39510. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  39511. uvs.push(0, 0);
  39512. }
  39513. for (f = 0; f < nbfaces; f++) {
  39514. for (i = 0; i < data.face[f].length - 2; i++) {
  39515. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  39516. }
  39517. }
  39518. }
  39519. else {
  39520. for (f = 0; f < nbfaces; f++) {
  39521. var fl = data.face[f].length; // number of vertices of the current face
  39522. ang = 2 * Math.PI / fl;
  39523. x = 0.5 * Math.tan(ang / 2);
  39524. y = 0.5;
  39525. // positions, uvs, colors
  39526. for (i = 0; i < fl; i++) {
  39527. // positions
  39528. 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);
  39529. indexes.push(index);
  39530. index++;
  39531. // uvs
  39532. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  39533. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  39534. uvs.push(u, v);
  39535. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  39536. y = x * Math.sin(ang) + y * Math.cos(ang);
  39537. x = tmp;
  39538. // colors
  39539. if (faceColors) {
  39540. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  39541. }
  39542. }
  39543. // indices from indexes
  39544. for (i = 0; i < fl - 2; i++) {
  39545. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  39546. }
  39547. faceIdx += fl;
  39548. }
  39549. }
  39550. VertexData.ComputeNormals(positions, indices, normals);
  39551. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  39552. var vertexData = new VertexData();
  39553. vertexData.positions = positions;
  39554. vertexData.indices = indices;
  39555. vertexData.normals = normals;
  39556. vertexData.uvs = uvs;
  39557. if (faceColors && flat) {
  39558. vertexData.colors = colors;
  39559. }
  39560. return vertexData;
  39561. };
  39562. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  39563. /**
  39564. * Creates the VertexData for a TorusKnot
  39565. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  39566. * * radius the radius of the torus knot, optional, default 2
  39567. * * tube the thickness of the tube, optional, default 0.5
  39568. * * radialSegments the number of sides on each tube segments, optional, default 32
  39569. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  39570. * * p the number of windings around the z axis, optional, default 2
  39571. * * q the number of windings around the x axis, optional, default 3
  39572. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39573. * * 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)
  39574. * * 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)
  39575. * @returns the VertexData of the Torus Knot
  39576. */
  39577. VertexData.CreateTorusKnot = function (options) {
  39578. var indices = new Array();
  39579. var positions = new Array();
  39580. var normals = new Array();
  39581. var uvs = new Array();
  39582. var radius = options.radius || 2;
  39583. var tube = options.tube || 0.5;
  39584. var radialSegments = options.radialSegments || 32;
  39585. var tubularSegments = options.tubularSegments || 32;
  39586. var p = options.p || 2;
  39587. var q = options.q || 3;
  39588. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39589. // Helper
  39590. var getPos = function (angle) {
  39591. var cu = Math.cos(angle);
  39592. var su = Math.sin(angle);
  39593. var quOverP = q / p * angle;
  39594. var cs = Math.cos(quOverP);
  39595. var tx = radius * (2 + cs) * 0.5 * cu;
  39596. var ty = radius * (2 + cs) * su * 0.5;
  39597. var tz = radius * Math.sin(quOverP) * 0.5;
  39598. return new BABYLON.Vector3(tx, ty, tz);
  39599. };
  39600. // Vertices
  39601. var i;
  39602. var j;
  39603. for (i = 0; i <= radialSegments; i++) {
  39604. var modI = i % radialSegments;
  39605. var u = modI / radialSegments * 2 * p * Math.PI;
  39606. var p1 = getPos(u);
  39607. var p2 = getPos(u + 0.01);
  39608. var tang = p2.subtract(p1);
  39609. var n = p2.add(p1);
  39610. var bitan = BABYLON.Vector3.Cross(tang, n);
  39611. n = BABYLON.Vector3.Cross(bitan, tang);
  39612. bitan.normalize();
  39613. n.normalize();
  39614. for (j = 0; j < tubularSegments; j++) {
  39615. var modJ = j % tubularSegments;
  39616. var v = modJ / tubularSegments * 2 * Math.PI;
  39617. var cx = -tube * Math.cos(v);
  39618. var cy = tube * Math.sin(v);
  39619. positions.push(p1.x + cx * n.x + cy * bitan.x);
  39620. positions.push(p1.y + cx * n.y + cy * bitan.y);
  39621. positions.push(p1.z + cx * n.z + cy * bitan.z);
  39622. uvs.push(i / radialSegments);
  39623. uvs.push(j / tubularSegments);
  39624. }
  39625. }
  39626. for (i = 0; i < radialSegments; i++) {
  39627. for (j = 0; j < tubularSegments; j++) {
  39628. var jNext = (j + 1) % tubularSegments;
  39629. var a = i * tubularSegments + j;
  39630. var b = (i + 1) * tubularSegments + j;
  39631. var c = (i + 1) * tubularSegments + jNext;
  39632. var d = i * tubularSegments + jNext;
  39633. indices.push(d);
  39634. indices.push(b);
  39635. indices.push(a);
  39636. indices.push(d);
  39637. indices.push(c);
  39638. indices.push(b);
  39639. }
  39640. }
  39641. // Normals
  39642. VertexData.ComputeNormals(positions, indices, normals);
  39643. // Sides
  39644. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  39645. // Result
  39646. var vertexData = new VertexData();
  39647. vertexData.indices = indices;
  39648. vertexData.positions = positions;
  39649. vertexData.normals = normals;
  39650. vertexData.uvs = uvs;
  39651. return vertexData;
  39652. };
  39653. // Tools
  39654. /**
  39655. * Compute normals for given positions and indices
  39656. * @param positions an array of vertex positions, [...., x, y, z, ......]
  39657. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  39658. * @param normals an array of vertex normals, [...., x, y, z, ......]
  39659. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  39660. * * facetNormals : optional array of facet normals (vector3)
  39661. * * facetPositions : optional array of facet positions (vector3)
  39662. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  39663. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  39664. * * bInfo : optional bounding info, required for facetPartitioning computation
  39665. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  39666. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  39667. * * useRightHandedSystem: optional boolean to for right handed system computation
  39668. * * depthSort : optional boolean to enable the facet depth sort computation
  39669. * * distanceTo : optional Vector3 to compute the facet depth from this location
  39670. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  39671. */
  39672. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  39673. // temporary scalar variables
  39674. var index = 0; // facet index
  39675. var p1p2x = 0.0; // p1p2 vector x coordinate
  39676. var p1p2y = 0.0; // p1p2 vector y coordinate
  39677. var p1p2z = 0.0; // p1p2 vector z coordinate
  39678. var p3p2x = 0.0; // p3p2 vector x coordinate
  39679. var p3p2y = 0.0; // p3p2 vector y coordinate
  39680. var p3p2z = 0.0; // p3p2 vector z coordinate
  39681. var faceNormalx = 0.0; // facet normal x coordinate
  39682. var faceNormaly = 0.0; // facet normal y coordinate
  39683. var faceNormalz = 0.0; // facet normal z coordinate
  39684. var length = 0.0; // facet normal length before normalization
  39685. var v1x = 0; // vector1 x index in the positions array
  39686. var v1y = 0; // vector1 y index in the positions array
  39687. var v1z = 0; // vector1 z index in the positions array
  39688. var v2x = 0; // vector2 x index in the positions array
  39689. var v2y = 0; // vector2 y index in the positions array
  39690. var v2z = 0; // vector2 z index in the positions array
  39691. var v3x = 0; // vector3 x index in the positions array
  39692. var v3y = 0; // vector3 y index in the positions array
  39693. var v3z = 0; // vector3 z index in the positions array
  39694. var computeFacetNormals = false;
  39695. var computeFacetPositions = false;
  39696. var computeFacetPartitioning = false;
  39697. var computeDepthSort = false;
  39698. var faceNormalSign = 1;
  39699. var ratio = 0;
  39700. var distanceTo = null;
  39701. if (options) {
  39702. computeFacetNormals = (options.facetNormals) ? true : false;
  39703. computeFacetPositions = (options.facetPositions) ? true : false;
  39704. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  39705. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  39706. ratio = options.ratio || 0;
  39707. computeDepthSort = (options.depthSort) ? true : false;
  39708. distanceTo = (options.distanceTo);
  39709. if (computeDepthSort) {
  39710. if (distanceTo === undefined) {
  39711. distanceTo = BABYLON.Vector3.Zero();
  39712. }
  39713. var depthSortedFacets = options.depthSortedFacets;
  39714. }
  39715. }
  39716. // facetPartitioning reinit if needed
  39717. var xSubRatio = 0;
  39718. var ySubRatio = 0;
  39719. var zSubRatio = 0;
  39720. var subSq = 0;
  39721. if (computeFacetPartitioning && options && options.bbSize) {
  39722. var ox = 0; // X partitioning index for facet position
  39723. var oy = 0; // Y partinioning index for facet position
  39724. var oz = 0; // Z partinioning index for facet position
  39725. var b1x = 0; // X partitioning index for facet v1 vertex
  39726. var b1y = 0; // Y partitioning index for facet v1 vertex
  39727. var b1z = 0; // z partitioning index for facet v1 vertex
  39728. var b2x = 0; // X partitioning index for facet v2 vertex
  39729. var b2y = 0; // Y partitioning index for facet v2 vertex
  39730. var b2z = 0; // Z partitioning index for facet v2 vertex
  39731. var b3x = 0; // X partitioning index for facet v3 vertex
  39732. var b3y = 0; // Y partitioning index for facet v3 vertex
  39733. var b3z = 0; // Z partitioning index for facet v3 vertex
  39734. var block_idx_o = 0; // facet barycenter block index
  39735. var block_idx_v1 = 0; // v1 vertex block index
  39736. var block_idx_v2 = 0; // v2 vertex block index
  39737. var block_idx_v3 = 0; // v3 vertex block index
  39738. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  39739. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  39740. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  39741. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  39742. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  39743. subSq = options.subDiv.max * options.subDiv.max;
  39744. options.facetPartitioning.length = 0;
  39745. }
  39746. // reset the normals
  39747. for (index = 0; index < positions.length; index++) {
  39748. normals[index] = 0.0;
  39749. }
  39750. // Loop : 1 indice triplet = 1 facet
  39751. var nbFaces = (indices.length / 3) | 0;
  39752. for (index = 0; index < nbFaces; index++) {
  39753. // get the indexes of the coordinates of each vertex of the facet
  39754. v1x = indices[index * 3] * 3;
  39755. v1y = v1x + 1;
  39756. v1z = v1x + 2;
  39757. v2x = indices[index * 3 + 1] * 3;
  39758. v2y = v2x + 1;
  39759. v2z = v2x + 2;
  39760. v3x = indices[index * 3 + 2] * 3;
  39761. v3y = v3x + 1;
  39762. v3z = v3x + 2;
  39763. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  39764. p1p2y = positions[v1y] - positions[v2y];
  39765. p1p2z = positions[v1z] - positions[v2z];
  39766. p3p2x = positions[v3x] - positions[v2x];
  39767. p3p2y = positions[v3y] - positions[v2y];
  39768. p3p2z = positions[v3z] - positions[v2z];
  39769. // compute the face normal with the cross product
  39770. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  39771. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  39772. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  39773. // normalize this normal and store it in the array facetData
  39774. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  39775. length = (length === 0) ? 1.0 : length;
  39776. faceNormalx /= length;
  39777. faceNormaly /= length;
  39778. faceNormalz /= length;
  39779. if (computeFacetNormals && options) {
  39780. options.facetNormals[index].x = faceNormalx;
  39781. options.facetNormals[index].y = faceNormaly;
  39782. options.facetNormals[index].z = faceNormalz;
  39783. }
  39784. if (computeFacetPositions && options) {
  39785. // compute and the facet barycenter coordinates in the array facetPositions
  39786. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  39787. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  39788. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  39789. }
  39790. if (computeFacetPartitioning && options) {
  39791. // store the facet indexes in arrays in the main facetPartitioning array :
  39792. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  39793. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  39794. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  39795. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  39796. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  39797. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  39798. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  39799. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  39800. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  39801. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  39802. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  39803. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  39804. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  39805. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  39806. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  39807. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  39808. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  39809. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  39810. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  39811. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  39812. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  39813. // push each facet index in each block containing the vertex
  39814. options.facetPartitioning[block_idx_v1].push(index);
  39815. if (block_idx_v2 != block_idx_v1) {
  39816. options.facetPartitioning[block_idx_v2].push(index);
  39817. }
  39818. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  39819. options.facetPartitioning[block_idx_v3].push(index);
  39820. }
  39821. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  39822. options.facetPartitioning[block_idx_o].push(index);
  39823. }
  39824. }
  39825. if (computeDepthSort && options && options.facetPositions) {
  39826. var dsf = depthSortedFacets[index];
  39827. dsf.ind = index * 3;
  39828. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  39829. }
  39830. // compute the normals anyway
  39831. normals[v1x] += faceNormalx; // accumulate all the normals per face
  39832. normals[v1y] += faceNormaly;
  39833. normals[v1z] += faceNormalz;
  39834. normals[v2x] += faceNormalx;
  39835. normals[v2y] += faceNormaly;
  39836. normals[v2z] += faceNormalz;
  39837. normals[v3x] += faceNormalx;
  39838. normals[v3y] += faceNormaly;
  39839. normals[v3z] += faceNormalz;
  39840. }
  39841. // last normalization of each normal
  39842. for (index = 0; index < normals.length / 3; index++) {
  39843. faceNormalx = normals[index * 3];
  39844. faceNormaly = normals[index * 3 + 1];
  39845. faceNormalz = normals[index * 3 + 2];
  39846. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  39847. length = (length === 0) ? 1.0 : length;
  39848. faceNormalx /= length;
  39849. faceNormaly /= length;
  39850. faceNormalz /= length;
  39851. normals[index * 3] = faceNormalx;
  39852. normals[index * 3 + 1] = faceNormaly;
  39853. normals[index * 3 + 2] = faceNormalz;
  39854. }
  39855. };
  39856. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  39857. var li = indices.length;
  39858. var ln = normals.length;
  39859. var i;
  39860. var n;
  39861. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39862. switch (sideOrientation) {
  39863. case BABYLON.Mesh.FRONTSIDE:
  39864. // nothing changed
  39865. break;
  39866. case BABYLON.Mesh.BACKSIDE:
  39867. var tmp;
  39868. // indices
  39869. for (i = 0; i < li; i += 3) {
  39870. tmp = indices[i];
  39871. indices[i] = indices[i + 2];
  39872. indices[i + 2] = tmp;
  39873. }
  39874. // normals
  39875. for (n = 0; n < ln; n++) {
  39876. normals[n] = -normals[n];
  39877. }
  39878. break;
  39879. case BABYLON.Mesh.DOUBLESIDE:
  39880. // positions
  39881. var lp = positions.length;
  39882. var l = lp / 3;
  39883. for (var p = 0; p < lp; p++) {
  39884. positions[lp + p] = positions[p];
  39885. }
  39886. // indices
  39887. for (i = 0; i < li; i += 3) {
  39888. indices[i + li] = indices[i + 2] + l;
  39889. indices[i + 1 + li] = indices[i + 1] + l;
  39890. indices[i + 2 + li] = indices[i] + l;
  39891. }
  39892. // normals
  39893. for (n = 0; n < ln; n++) {
  39894. normals[ln + n] = -normals[n];
  39895. }
  39896. // uvs
  39897. var lu = uvs.length;
  39898. var u = 0;
  39899. for (u = 0; u < lu; u++) {
  39900. uvs[u + lu] = uvs[u];
  39901. }
  39902. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  39903. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  39904. u = 0;
  39905. for (i = 0; i < lu / 2; i++) {
  39906. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  39907. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  39908. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  39909. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  39910. u += 2;
  39911. }
  39912. break;
  39913. }
  39914. };
  39915. /**
  39916. * Applies VertexData created from the imported parameters to the geometry
  39917. * @param parsedVertexData the parsed data from an imported file
  39918. * @param geometry the geometry to apply the VertexData to
  39919. */
  39920. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  39921. var vertexData = new VertexData();
  39922. // positions
  39923. var positions = parsedVertexData.positions;
  39924. if (positions) {
  39925. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  39926. }
  39927. // normals
  39928. var normals = parsedVertexData.normals;
  39929. if (normals) {
  39930. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  39931. }
  39932. // tangents
  39933. var tangents = parsedVertexData.tangents;
  39934. if (tangents) {
  39935. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  39936. }
  39937. // uvs
  39938. var uvs = parsedVertexData.uvs;
  39939. if (uvs) {
  39940. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  39941. }
  39942. // uv2s
  39943. var uv2s = parsedVertexData.uv2s;
  39944. if (uv2s) {
  39945. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  39946. }
  39947. // uv3s
  39948. var uv3s = parsedVertexData.uv3s;
  39949. if (uv3s) {
  39950. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  39951. }
  39952. // uv4s
  39953. var uv4s = parsedVertexData.uv4s;
  39954. if (uv4s) {
  39955. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  39956. }
  39957. // uv5s
  39958. var uv5s = parsedVertexData.uv5s;
  39959. if (uv5s) {
  39960. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  39961. }
  39962. // uv6s
  39963. var uv6s = parsedVertexData.uv6s;
  39964. if (uv6s) {
  39965. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  39966. }
  39967. // colors
  39968. var colors = parsedVertexData.colors;
  39969. if (colors) {
  39970. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  39971. }
  39972. // matricesIndices
  39973. var matricesIndices = parsedVertexData.matricesIndices;
  39974. if (matricesIndices) {
  39975. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  39976. }
  39977. // matricesWeights
  39978. var matricesWeights = parsedVertexData.matricesWeights;
  39979. if (matricesWeights) {
  39980. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  39981. }
  39982. // indices
  39983. var indices = parsedVertexData.indices;
  39984. if (indices) {
  39985. vertexData.indices = indices;
  39986. }
  39987. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  39988. };
  39989. return VertexData;
  39990. }());
  39991. BABYLON.VertexData = VertexData;
  39992. })(BABYLON || (BABYLON = {}));
  39993. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  39994. var BABYLON;
  39995. (function (BABYLON) {
  39996. /**
  39997. * Class used to store geometry data (vertex buffers + index buffer)
  39998. */
  39999. var Geometry = /** @class */ (function () {
  40000. /**
  40001. * Creates a new geometry
  40002. * @param id defines the unique ID
  40003. * @param scene defines the hosting scene
  40004. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  40005. * @param updatable defines if geometry must be updatable (false by default)
  40006. * @param mesh defines the mesh that will be associated with the geometry
  40007. */
  40008. function Geometry(id, scene, vertexData, updatable, mesh) {
  40009. if (updatable === void 0) { updatable = false; }
  40010. if (mesh === void 0) { mesh = null; }
  40011. /**
  40012. * Gets the delay loading state of the geometry (none by default which means not delayed)
  40013. */
  40014. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  40015. this._totalVertices = 0;
  40016. this._isDisposed = false;
  40017. this._indexBufferIsUpdatable = false;
  40018. this.id = id;
  40019. this._engine = scene.getEngine();
  40020. this._meshes = [];
  40021. this._scene = scene;
  40022. //Init vertex buffer cache
  40023. this._vertexBuffers = {};
  40024. this._indices = [];
  40025. this._updatable = updatable;
  40026. // vertexData
  40027. if (vertexData) {
  40028. this.setAllVerticesData(vertexData, updatable);
  40029. }
  40030. else {
  40031. this._totalVertices = 0;
  40032. this._indices = [];
  40033. }
  40034. if (this._engine.getCaps().vertexArrayObject) {
  40035. this._vertexArrayObjects = {};
  40036. }
  40037. // applyToMesh
  40038. if (mesh) {
  40039. if (mesh.getClassName() === "LinesMesh") {
  40040. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  40041. this._updateExtend();
  40042. }
  40043. this.applyToMesh(mesh);
  40044. mesh.computeWorldMatrix(true);
  40045. }
  40046. }
  40047. Object.defineProperty(Geometry.prototype, "boundingBias", {
  40048. /**
  40049. * 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
  40050. */
  40051. get: function () {
  40052. return this._boundingBias;
  40053. },
  40054. /**
  40055. * 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
  40056. */
  40057. set: function (value) {
  40058. if (this._boundingBias) {
  40059. if (this._boundingBias.equals(value)) {
  40060. return;
  40061. }
  40062. this._boundingBias.copyFrom(value);
  40063. }
  40064. else {
  40065. this._boundingBias = value.clone();
  40066. }
  40067. this._updateBoundingInfo(true, null);
  40068. },
  40069. enumerable: true,
  40070. configurable: true
  40071. });
  40072. /**
  40073. * Static function used to attach a new empty geometry to a mesh
  40074. * @param mesh defines the mesh to attach the geometry to
  40075. * @returns the new {BABYLON.Geometry}
  40076. */
  40077. Geometry.CreateGeometryForMesh = function (mesh) {
  40078. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  40079. geometry.applyToMesh(mesh);
  40080. return geometry;
  40081. };
  40082. Object.defineProperty(Geometry.prototype, "extend", {
  40083. /**
  40084. * Gets the current extend of the geometry
  40085. */
  40086. get: function () {
  40087. return this._extend;
  40088. },
  40089. enumerable: true,
  40090. configurable: true
  40091. });
  40092. /**
  40093. * Gets the hosting scene
  40094. * @returns the hosting {BABYLON.Scene}
  40095. */
  40096. Geometry.prototype.getScene = function () {
  40097. return this._scene;
  40098. };
  40099. /**
  40100. * Gets the hosting engine
  40101. * @returns the hosting {BABYLON.Engine}
  40102. */
  40103. Geometry.prototype.getEngine = function () {
  40104. return this._engine;
  40105. };
  40106. /**
  40107. * Defines if the geometry is ready to use
  40108. * @returns true if the geometry is ready to be used
  40109. */
  40110. Geometry.prototype.isReady = function () {
  40111. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  40112. };
  40113. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  40114. /**
  40115. * Gets a value indicating that the geometry should not be serialized
  40116. */
  40117. get: function () {
  40118. for (var index = 0; index < this._meshes.length; index++) {
  40119. if (!this._meshes[index].doNotSerialize) {
  40120. return false;
  40121. }
  40122. }
  40123. return true;
  40124. },
  40125. enumerable: true,
  40126. configurable: true
  40127. });
  40128. /** @hidden */
  40129. Geometry.prototype._rebuild = function () {
  40130. if (this._vertexArrayObjects) {
  40131. this._vertexArrayObjects = {};
  40132. }
  40133. // Index buffer
  40134. if (this._meshes.length !== 0 && this._indices) {
  40135. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  40136. }
  40137. // Vertex buffers
  40138. for (var key in this._vertexBuffers) {
  40139. var vertexBuffer = this._vertexBuffers[key];
  40140. vertexBuffer._rebuild();
  40141. }
  40142. };
  40143. /**
  40144. * Affects all geometry data in one call
  40145. * @param vertexData defines the geometry data
  40146. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  40147. */
  40148. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  40149. vertexData.applyToGeometry(this, updatable);
  40150. this.notifyUpdate();
  40151. };
  40152. /**
  40153. * Set specific vertex data
  40154. * @param kind defines the data kind (Position, normal, etc...)
  40155. * @param data defines the vertex data to use
  40156. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  40157. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  40158. */
  40159. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  40160. if (updatable === void 0) { updatable = false; }
  40161. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  40162. this.setVerticesBuffer(buffer);
  40163. };
  40164. /**
  40165. * Removes a specific vertex data
  40166. * @param kind defines the data kind (Position, normal, etc...)
  40167. */
  40168. Geometry.prototype.removeVerticesData = function (kind) {
  40169. if (this._vertexBuffers[kind]) {
  40170. this._vertexBuffers[kind].dispose();
  40171. delete this._vertexBuffers[kind];
  40172. }
  40173. };
  40174. /**
  40175. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  40176. * @param buffer defines the vertex buffer to use
  40177. * @param totalVertices defines the total number of vertices for position kind (could be null)
  40178. */
  40179. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  40180. if (totalVertices === void 0) { totalVertices = null; }
  40181. var kind = buffer.getKind();
  40182. if (this._vertexBuffers[kind]) {
  40183. this._vertexBuffers[kind].dispose();
  40184. }
  40185. this._vertexBuffers[kind] = buffer;
  40186. if (kind === BABYLON.VertexBuffer.PositionKind) {
  40187. var data = buffer.getData();
  40188. if (totalVertices != null) {
  40189. this._totalVertices = totalVertices;
  40190. }
  40191. else {
  40192. if (data != null) {
  40193. this._totalVertices = data.length / (buffer.byteStride / 4);
  40194. }
  40195. }
  40196. this._updateExtend(data);
  40197. this._resetPointsArrayCache();
  40198. var meshes = this._meshes;
  40199. var numOfMeshes = meshes.length;
  40200. for (var index = 0; index < numOfMeshes; index++) {
  40201. var mesh = meshes[index];
  40202. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  40203. mesh._createGlobalSubMesh(false);
  40204. mesh.computeWorldMatrix(true);
  40205. }
  40206. }
  40207. this.notifyUpdate(kind);
  40208. if (this._vertexArrayObjects) {
  40209. this._disposeVertexArrayObjects();
  40210. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  40211. }
  40212. };
  40213. /**
  40214. * Update a specific vertex buffer
  40215. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  40216. * It will do nothing if the buffer is not updatable
  40217. * @param kind defines the data kind (Position, normal, etc...)
  40218. * @param data defines the data to use
  40219. * @param offset defines the offset in the target buffer where to store the data
  40220. * @param useBytes set to true if the offset is in bytes
  40221. */
  40222. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  40223. if (useBytes === void 0) { useBytes = false; }
  40224. var vertexBuffer = this.getVertexBuffer(kind);
  40225. if (!vertexBuffer) {
  40226. return;
  40227. }
  40228. vertexBuffer.updateDirectly(data, offset, useBytes);
  40229. this.notifyUpdate(kind);
  40230. };
  40231. /**
  40232. * Update a specific vertex buffer
  40233. * This function will create a new buffer if the current one is not updatable
  40234. * @param kind defines the data kind (Position, normal, etc...)
  40235. * @param data defines the data to use
  40236. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  40237. */
  40238. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  40239. if (updateExtends === void 0) { updateExtends = false; }
  40240. var vertexBuffer = this.getVertexBuffer(kind);
  40241. if (!vertexBuffer) {
  40242. return;
  40243. }
  40244. vertexBuffer.update(data);
  40245. if (kind === BABYLON.VertexBuffer.PositionKind) {
  40246. this._updateBoundingInfo(updateExtends, data);
  40247. }
  40248. this.notifyUpdate(kind);
  40249. };
  40250. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  40251. if (updateExtends) {
  40252. this._updateExtend(data);
  40253. }
  40254. var meshes = this._meshes;
  40255. var numOfMeshes = meshes.length;
  40256. this._resetPointsArrayCache();
  40257. for (var index = 0; index < numOfMeshes; index++) {
  40258. var mesh = meshes[index];
  40259. if (updateExtends) {
  40260. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  40261. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  40262. var subMesh = mesh.subMeshes[subIndex];
  40263. subMesh.refreshBoundingInfo();
  40264. }
  40265. }
  40266. }
  40267. };
  40268. /** @hidden */
  40269. Geometry.prototype._bind = function (effect, indexToBind) {
  40270. if (!effect) {
  40271. return;
  40272. }
  40273. if (indexToBind === undefined) {
  40274. indexToBind = this._indexBuffer;
  40275. }
  40276. var vbs = this.getVertexBuffers();
  40277. if (!vbs) {
  40278. return;
  40279. }
  40280. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  40281. this._engine.bindBuffers(vbs, indexToBind, effect);
  40282. return;
  40283. }
  40284. // Using VAO
  40285. if (!this._vertexArrayObjects[effect.key]) {
  40286. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  40287. }
  40288. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  40289. };
  40290. /**
  40291. * Gets total number of vertices
  40292. * @returns the total number of vertices
  40293. */
  40294. Geometry.prototype.getTotalVertices = function () {
  40295. if (!this.isReady()) {
  40296. return 0;
  40297. }
  40298. return this._totalVertices;
  40299. };
  40300. /**
  40301. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  40302. * @param kind defines the data kind (Position, normal, etc...)
  40303. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  40304. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  40305. * @returns a float array containing vertex data
  40306. */
  40307. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  40308. var vertexBuffer = this.getVertexBuffer(kind);
  40309. if (!vertexBuffer) {
  40310. return null;
  40311. }
  40312. var data = vertexBuffer.getData();
  40313. if (!data) {
  40314. return null;
  40315. }
  40316. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  40317. var count = this._totalVertices * vertexBuffer.getSize();
  40318. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  40319. var copy_1 = new Array(count);
  40320. vertexBuffer.forEach(count, function (value, index) {
  40321. copy_1[index] = value;
  40322. });
  40323. return copy_1;
  40324. }
  40325. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  40326. if (data instanceof Array) {
  40327. var offset = vertexBuffer.byteOffset / 4;
  40328. return BABYLON.Tools.Slice(data, offset, offset + count);
  40329. }
  40330. else if (data instanceof ArrayBuffer) {
  40331. return new Float32Array(data, vertexBuffer.byteOffset, count);
  40332. }
  40333. else {
  40334. var offset = data.byteOffset + vertexBuffer.byteOffset;
  40335. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  40336. var result = new Float32Array(count);
  40337. var source = new Float32Array(data.buffer, offset, count);
  40338. result.set(source);
  40339. return result;
  40340. }
  40341. return new Float32Array(data.buffer, offset, count);
  40342. }
  40343. }
  40344. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  40345. return BABYLON.Tools.Slice(data);
  40346. }
  40347. return data;
  40348. };
  40349. /**
  40350. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  40351. * @param kind defines the data kind (Position, normal, etc...)
  40352. * @returns true if the vertex buffer with the specified kind is updatable
  40353. */
  40354. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  40355. var vb = this._vertexBuffers[kind];
  40356. if (!vb) {
  40357. return false;
  40358. }
  40359. return vb.isUpdatable();
  40360. };
  40361. /**
  40362. * Gets a specific vertex buffer
  40363. * @param kind defines the data kind (Position, normal, etc...)
  40364. * @returns a {BABYLON.VertexBuffer}
  40365. */
  40366. Geometry.prototype.getVertexBuffer = function (kind) {
  40367. if (!this.isReady()) {
  40368. return null;
  40369. }
  40370. return this._vertexBuffers[kind];
  40371. };
  40372. /**
  40373. * Returns all vertex buffers
  40374. * @return an object holding all vertex buffers indexed by kind
  40375. */
  40376. Geometry.prototype.getVertexBuffers = function () {
  40377. if (!this.isReady()) {
  40378. return null;
  40379. }
  40380. return this._vertexBuffers;
  40381. };
  40382. /**
  40383. * Gets a boolean indicating if specific vertex buffer is present
  40384. * @param kind defines the data kind (Position, normal, etc...)
  40385. * @returns true if data is present
  40386. */
  40387. Geometry.prototype.isVerticesDataPresent = function (kind) {
  40388. if (!this._vertexBuffers) {
  40389. if (this._delayInfo) {
  40390. return this._delayInfo.indexOf(kind) !== -1;
  40391. }
  40392. return false;
  40393. }
  40394. return this._vertexBuffers[kind] !== undefined;
  40395. };
  40396. /**
  40397. * Gets a list of all attached data kinds (Position, normal, etc...)
  40398. * @returns a list of string containing all kinds
  40399. */
  40400. Geometry.prototype.getVerticesDataKinds = function () {
  40401. var result = [];
  40402. var kind;
  40403. if (!this._vertexBuffers && this._delayInfo) {
  40404. for (kind in this._delayInfo) {
  40405. result.push(kind);
  40406. }
  40407. }
  40408. else {
  40409. for (kind in this._vertexBuffers) {
  40410. result.push(kind);
  40411. }
  40412. }
  40413. return result;
  40414. };
  40415. /**
  40416. * Update index buffer
  40417. * @param indices defines the indices to store in the index buffer
  40418. * @param offset defines the offset in the target buffer where to store the data
  40419. */
  40420. Geometry.prototype.updateIndices = function (indices, offset) {
  40421. if (!this._indexBuffer) {
  40422. return;
  40423. }
  40424. if (!this._indexBufferIsUpdatable) {
  40425. this.setIndices(indices, null, true);
  40426. }
  40427. else {
  40428. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  40429. }
  40430. };
  40431. /**
  40432. * Creates a new index buffer
  40433. * @param indices defines the indices to store in the index buffer
  40434. * @param totalVertices defines the total number of vertices (could be null)
  40435. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  40436. */
  40437. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  40438. if (totalVertices === void 0) { totalVertices = null; }
  40439. if (updatable === void 0) { updatable = false; }
  40440. if (this._indexBuffer) {
  40441. this._engine._releaseBuffer(this._indexBuffer);
  40442. }
  40443. this._disposeVertexArrayObjects();
  40444. this._indices = indices;
  40445. this._indexBufferIsUpdatable = updatable;
  40446. if (this._meshes.length !== 0 && this._indices) {
  40447. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  40448. }
  40449. if (totalVertices != undefined) { // including null and undefined
  40450. this._totalVertices = totalVertices;
  40451. }
  40452. var meshes = this._meshes;
  40453. var numOfMeshes = meshes.length;
  40454. for (var index = 0; index < numOfMeshes; index++) {
  40455. meshes[index]._createGlobalSubMesh(true);
  40456. }
  40457. this.notifyUpdate();
  40458. };
  40459. /**
  40460. * Return the total number of indices
  40461. * @returns the total number of indices
  40462. */
  40463. Geometry.prototype.getTotalIndices = function () {
  40464. if (!this.isReady()) {
  40465. return 0;
  40466. }
  40467. return this._indices.length;
  40468. };
  40469. /**
  40470. * Gets the index buffer array
  40471. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  40472. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  40473. * @returns the index buffer array
  40474. */
  40475. Geometry.prototype.getIndices = function (copyWhenShared, forceCopy) {
  40476. if (!this.isReady()) {
  40477. return null;
  40478. }
  40479. var orig = this._indices;
  40480. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  40481. return orig;
  40482. }
  40483. else {
  40484. var len = orig.length;
  40485. var copy = [];
  40486. for (var i = 0; i < len; i++) {
  40487. copy.push(orig[i]);
  40488. }
  40489. return copy;
  40490. }
  40491. };
  40492. /**
  40493. * Gets the index buffer
  40494. * @return the index buffer
  40495. */
  40496. Geometry.prototype.getIndexBuffer = function () {
  40497. if (!this.isReady()) {
  40498. return null;
  40499. }
  40500. return this._indexBuffer;
  40501. };
  40502. /** @hidden */
  40503. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  40504. if (effect === void 0) { effect = null; }
  40505. if (!effect || !this._vertexArrayObjects) {
  40506. return;
  40507. }
  40508. if (this._vertexArrayObjects[effect.key]) {
  40509. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  40510. delete this._vertexArrayObjects[effect.key];
  40511. }
  40512. };
  40513. /**
  40514. * Release the associated resources for a specific mesh
  40515. * @param mesh defines the source mesh
  40516. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  40517. */
  40518. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  40519. var meshes = this._meshes;
  40520. var index = meshes.indexOf(mesh);
  40521. if (index === -1) {
  40522. return;
  40523. }
  40524. meshes.splice(index, 1);
  40525. mesh._geometry = null;
  40526. if (meshes.length === 0 && shouldDispose) {
  40527. this.dispose();
  40528. }
  40529. };
  40530. /**
  40531. * Apply current geometry to a given mesh
  40532. * @param mesh defines the mesh to apply geometry to
  40533. */
  40534. Geometry.prototype.applyToMesh = function (mesh) {
  40535. if (mesh._geometry === this) {
  40536. return;
  40537. }
  40538. var previousGeometry = mesh._geometry;
  40539. if (previousGeometry) {
  40540. previousGeometry.releaseForMesh(mesh);
  40541. }
  40542. var meshes = this._meshes;
  40543. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  40544. mesh._geometry = this;
  40545. this._scene.pushGeometry(this);
  40546. meshes.push(mesh);
  40547. if (this.isReady()) {
  40548. this._applyToMesh(mesh);
  40549. }
  40550. else {
  40551. mesh._boundingInfo = this._boundingInfo;
  40552. }
  40553. };
  40554. Geometry.prototype._updateExtend = function (data) {
  40555. if (data === void 0) { data = null; }
  40556. if (!data) {
  40557. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  40558. }
  40559. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  40560. };
  40561. Geometry.prototype._applyToMesh = function (mesh) {
  40562. var numOfMeshes = this._meshes.length;
  40563. // vertexBuffers
  40564. for (var kind in this._vertexBuffers) {
  40565. if (numOfMeshes === 1) {
  40566. this._vertexBuffers[kind].create();
  40567. }
  40568. var buffer = this._vertexBuffers[kind].getBuffer();
  40569. if (buffer)
  40570. buffer.references = numOfMeshes;
  40571. if (kind === BABYLON.VertexBuffer.PositionKind) {
  40572. if (!this._extend) {
  40573. this._updateExtend();
  40574. }
  40575. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  40576. mesh._createGlobalSubMesh(false);
  40577. //bounding info was just created again, world matrix should be applied again.
  40578. mesh._updateBoundingInfo();
  40579. }
  40580. }
  40581. // indexBuffer
  40582. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  40583. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  40584. }
  40585. if (this._indexBuffer) {
  40586. this._indexBuffer.references = numOfMeshes;
  40587. }
  40588. };
  40589. Geometry.prototype.notifyUpdate = function (kind) {
  40590. if (this.onGeometryUpdated) {
  40591. this.onGeometryUpdated(this, kind);
  40592. }
  40593. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  40594. var mesh = _a[_i];
  40595. mesh._markSubMeshesAsAttributesDirty();
  40596. }
  40597. };
  40598. /**
  40599. * Load the geometry if it was flagged as delay loaded
  40600. * @param scene defines the hosting scene
  40601. * @param onLoaded defines a callback called when the geometry is loaded
  40602. */
  40603. Geometry.prototype.load = function (scene, onLoaded) {
  40604. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  40605. return;
  40606. }
  40607. if (this.isReady()) {
  40608. if (onLoaded) {
  40609. onLoaded();
  40610. }
  40611. return;
  40612. }
  40613. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  40614. this._queueLoad(scene, onLoaded);
  40615. };
  40616. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  40617. var _this = this;
  40618. if (!this.delayLoadingFile) {
  40619. return;
  40620. }
  40621. scene._addPendingData(this);
  40622. scene._loadFile(this.delayLoadingFile, function (data) {
  40623. if (!_this._delayLoadingFunction) {
  40624. return;
  40625. }
  40626. _this._delayLoadingFunction(JSON.parse(data), _this);
  40627. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  40628. _this._delayInfo = [];
  40629. scene._removePendingData(_this);
  40630. var meshes = _this._meshes;
  40631. var numOfMeshes = meshes.length;
  40632. for (var index = 0; index < numOfMeshes; index++) {
  40633. _this._applyToMesh(meshes[index]);
  40634. }
  40635. if (onLoaded) {
  40636. onLoaded();
  40637. }
  40638. }, undefined, true);
  40639. };
  40640. /**
  40641. * Invert the geometry to move from a right handed system to a left handed one.
  40642. */
  40643. Geometry.prototype.toLeftHanded = function () {
  40644. // Flip faces
  40645. var tIndices = this.getIndices(false);
  40646. if (tIndices != null && tIndices.length > 0) {
  40647. for (var i = 0; i < tIndices.length; i += 3) {
  40648. var tTemp = tIndices[i + 0];
  40649. tIndices[i + 0] = tIndices[i + 2];
  40650. tIndices[i + 2] = tTemp;
  40651. }
  40652. this.setIndices(tIndices);
  40653. }
  40654. // Negate position.z
  40655. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  40656. if (tPositions != null && tPositions.length > 0) {
  40657. for (var i = 0; i < tPositions.length; i += 3) {
  40658. tPositions[i + 2] = -tPositions[i + 2];
  40659. }
  40660. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  40661. }
  40662. // Negate normal.z
  40663. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  40664. if (tNormals != null && tNormals.length > 0) {
  40665. for (var i = 0; i < tNormals.length; i += 3) {
  40666. tNormals[i + 2] = -tNormals[i + 2];
  40667. }
  40668. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  40669. }
  40670. };
  40671. // Cache
  40672. /** @hidden */
  40673. Geometry.prototype._resetPointsArrayCache = function () {
  40674. this._positions = null;
  40675. };
  40676. /** @hidden */
  40677. Geometry.prototype._generatePointsArray = function () {
  40678. if (this._positions)
  40679. return true;
  40680. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  40681. if (!data || data.length === 0) {
  40682. return false;
  40683. }
  40684. this._positions = [];
  40685. for (var index = 0; index < data.length; index += 3) {
  40686. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  40687. }
  40688. return true;
  40689. };
  40690. /**
  40691. * Gets a value indicating if the geometry is disposed
  40692. * @returns true if the geometry was disposed
  40693. */
  40694. Geometry.prototype.isDisposed = function () {
  40695. return this._isDisposed;
  40696. };
  40697. Geometry.prototype._disposeVertexArrayObjects = function () {
  40698. if (this._vertexArrayObjects) {
  40699. for (var kind in this._vertexArrayObjects) {
  40700. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  40701. }
  40702. this._vertexArrayObjects = {};
  40703. }
  40704. };
  40705. /**
  40706. * Free all associated resources
  40707. */
  40708. Geometry.prototype.dispose = function () {
  40709. var meshes = this._meshes;
  40710. var numOfMeshes = meshes.length;
  40711. var index;
  40712. for (index = 0; index < numOfMeshes; index++) {
  40713. this.releaseForMesh(meshes[index]);
  40714. }
  40715. this._meshes = [];
  40716. this._disposeVertexArrayObjects();
  40717. for (var kind in this._vertexBuffers) {
  40718. this._vertexBuffers[kind].dispose();
  40719. }
  40720. this._vertexBuffers = {};
  40721. this._totalVertices = 0;
  40722. if (this._indexBuffer) {
  40723. this._engine._releaseBuffer(this._indexBuffer);
  40724. }
  40725. this._indexBuffer = null;
  40726. this._indices = [];
  40727. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  40728. this.delayLoadingFile = null;
  40729. this._delayLoadingFunction = null;
  40730. this._delayInfo = [];
  40731. this._boundingInfo = null;
  40732. this._scene.removeGeometry(this);
  40733. this._isDisposed = true;
  40734. };
  40735. /**
  40736. * Clone the current geometry into a new geometry
  40737. * @param id defines the unique ID of the new geometry
  40738. * @returns a new geometry object
  40739. */
  40740. Geometry.prototype.copy = function (id) {
  40741. var vertexData = new BABYLON.VertexData();
  40742. vertexData.indices = [];
  40743. var indices = this.getIndices();
  40744. if (indices) {
  40745. for (var index = 0; index < indices.length; index++) {
  40746. vertexData.indices.push(indices[index]);
  40747. }
  40748. }
  40749. var updatable = false;
  40750. var stopChecking = false;
  40751. var kind;
  40752. for (kind in this._vertexBuffers) {
  40753. // using slice() to make a copy of the array and not just reference it
  40754. var data = this.getVerticesData(kind);
  40755. if (data instanceof Float32Array) {
  40756. vertexData.set(new Float32Array(data), kind);
  40757. }
  40758. else {
  40759. vertexData.set(data.slice(0), kind);
  40760. }
  40761. if (!stopChecking) {
  40762. var vb = this.getVertexBuffer(kind);
  40763. if (vb) {
  40764. updatable = vb.isUpdatable();
  40765. stopChecking = !updatable;
  40766. }
  40767. }
  40768. }
  40769. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  40770. geometry.delayLoadState = this.delayLoadState;
  40771. geometry.delayLoadingFile = this.delayLoadingFile;
  40772. geometry._delayLoadingFunction = this._delayLoadingFunction;
  40773. for (kind in this._delayInfo) {
  40774. geometry._delayInfo = geometry._delayInfo || [];
  40775. geometry._delayInfo.push(kind);
  40776. }
  40777. // Bounding info
  40778. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  40779. return geometry;
  40780. };
  40781. /**
  40782. * Serialize the current geometry info (and not the vertices data) into a JSON object
  40783. * @return a JSON representation of the current geometry data (without the vertices data)
  40784. */
  40785. Geometry.prototype.serialize = function () {
  40786. var serializationObject = {};
  40787. serializationObject.id = this.id;
  40788. serializationObject.updatable = this._updatable;
  40789. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  40790. serializationObject.tags = BABYLON.Tags.GetTags(this);
  40791. }
  40792. return serializationObject;
  40793. };
  40794. Geometry.prototype.toNumberArray = function (origin) {
  40795. if (Array.isArray(origin)) {
  40796. return origin;
  40797. }
  40798. else {
  40799. return Array.prototype.slice.call(origin);
  40800. }
  40801. };
  40802. /**
  40803. * Serialize all vertices data into a JSON oject
  40804. * @returns a JSON representation of the current geometry data
  40805. */
  40806. Geometry.prototype.serializeVerticeData = function () {
  40807. var serializationObject = this.serialize();
  40808. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  40809. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  40810. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  40811. serializationObject.positions._updatable = true;
  40812. }
  40813. }
  40814. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  40815. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  40816. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  40817. serializationObject.normals._updatable = true;
  40818. }
  40819. }
  40820. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  40821. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  40822. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  40823. serializationObject.tangets._updatable = true;
  40824. }
  40825. }
  40826. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  40827. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  40828. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  40829. serializationObject.uvs._updatable = true;
  40830. }
  40831. }
  40832. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  40833. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  40834. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  40835. serializationObject.uv2s._updatable = true;
  40836. }
  40837. }
  40838. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  40839. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  40840. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  40841. serializationObject.uv3s._updatable = true;
  40842. }
  40843. }
  40844. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  40845. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  40846. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  40847. serializationObject.uv4s._updatable = true;
  40848. }
  40849. }
  40850. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  40851. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  40852. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  40853. serializationObject.uv5s._updatable = true;
  40854. }
  40855. }
  40856. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  40857. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  40858. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  40859. serializationObject.uv6s._updatable = true;
  40860. }
  40861. }
  40862. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  40863. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  40864. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  40865. serializationObject.colors._updatable = true;
  40866. }
  40867. }
  40868. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  40869. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  40870. serializationObject.matricesIndices._isExpanded = true;
  40871. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  40872. serializationObject.matricesIndices._updatable = true;
  40873. }
  40874. }
  40875. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  40876. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  40877. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  40878. serializationObject.matricesWeights._updatable = true;
  40879. }
  40880. }
  40881. serializationObject.indices = this.toNumberArray(this.getIndices());
  40882. return serializationObject;
  40883. };
  40884. // Statics
  40885. /**
  40886. * Extracts a clone of a mesh geometry
  40887. * @param mesh defines the source mesh
  40888. * @param id defines the unique ID of the new geometry object
  40889. * @returns the new geometry object
  40890. */
  40891. Geometry.ExtractFromMesh = function (mesh, id) {
  40892. var geometry = mesh._geometry;
  40893. if (!geometry) {
  40894. return null;
  40895. }
  40896. return geometry.copy(id);
  40897. };
  40898. /**
  40899. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  40900. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  40901. * Be aware Math.random() could cause collisions, but:
  40902. * "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"
  40903. * @returns a string containing a new GUID
  40904. */
  40905. Geometry.RandomId = function () {
  40906. return BABYLON.Tools.RandomId();
  40907. };
  40908. /** @hidden */
  40909. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  40910. var scene = mesh.getScene();
  40911. // Geometry
  40912. var geometryId = parsedGeometry.geometryId;
  40913. if (geometryId) {
  40914. var geometry = scene.getGeometryByID(geometryId);
  40915. if (geometry) {
  40916. geometry.applyToMesh(mesh);
  40917. }
  40918. }
  40919. else if (parsedGeometry instanceof ArrayBuffer) {
  40920. var binaryInfo = mesh._binaryInfo;
  40921. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  40922. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  40923. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  40924. }
  40925. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  40926. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  40927. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  40928. }
  40929. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  40930. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  40931. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  40932. }
  40933. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  40934. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  40935. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  40936. }
  40937. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  40938. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  40939. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  40940. }
  40941. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  40942. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  40943. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  40944. }
  40945. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  40946. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  40947. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  40948. }
  40949. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  40950. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  40951. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  40952. }
  40953. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  40954. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  40955. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  40956. }
  40957. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  40958. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  40959. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  40960. }
  40961. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  40962. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  40963. var floatIndices = [];
  40964. for (var i = 0; i < matricesIndicesData.length; i++) {
  40965. var index = matricesIndicesData[i];
  40966. floatIndices.push(index & 0x000000FF);
  40967. floatIndices.push((index & 0x0000FF00) >> 8);
  40968. floatIndices.push((index & 0x00FF0000) >> 16);
  40969. floatIndices.push(index >> 24);
  40970. }
  40971. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  40972. }
  40973. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  40974. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  40975. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  40976. }
  40977. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  40978. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  40979. mesh.setIndices(indicesData, null);
  40980. }
  40981. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  40982. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  40983. mesh.subMeshes = [];
  40984. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  40985. var materialIndex = subMeshesData[(i * 5) + 0];
  40986. var verticesStart = subMeshesData[(i * 5) + 1];
  40987. var verticesCount = subMeshesData[(i * 5) + 2];
  40988. var indexStart = subMeshesData[(i * 5) + 3];
  40989. var indexCount = subMeshesData[(i * 5) + 4];
  40990. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  40991. }
  40992. }
  40993. }
  40994. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  40995. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  40996. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  40997. if (parsedGeometry.tangents) {
  40998. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  40999. }
  41000. if (parsedGeometry.uvs) {
  41001. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  41002. }
  41003. if (parsedGeometry.uvs2) {
  41004. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  41005. }
  41006. if (parsedGeometry.uvs3) {
  41007. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  41008. }
  41009. if (parsedGeometry.uvs4) {
  41010. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  41011. }
  41012. if (parsedGeometry.uvs5) {
  41013. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  41014. }
  41015. if (parsedGeometry.uvs6) {
  41016. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  41017. }
  41018. if (parsedGeometry.colors) {
  41019. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  41020. }
  41021. if (parsedGeometry.matricesIndices) {
  41022. if (!parsedGeometry.matricesIndices._isExpanded) {
  41023. var floatIndices = [];
  41024. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  41025. var matricesIndex = parsedGeometry.matricesIndices[i];
  41026. floatIndices.push(matricesIndex & 0x000000FF);
  41027. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  41028. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  41029. floatIndices.push(matricesIndex >> 24);
  41030. }
  41031. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  41032. }
  41033. else {
  41034. delete parsedGeometry.matricesIndices._isExpanded;
  41035. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  41036. }
  41037. }
  41038. if (parsedGeometry.matricesIndicesExtra) {
  41039. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  41040. var floatIndices = [];
  41041. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  41042. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  41043. floatIndices.push(matricesIndex & 0x000000FF);
  41044. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  41045. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  41046. floatIndices.push(matricesIndex >> 24);
  41047. }
  41048. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  41049. }
  41050. else {
  41051. delete parsedGeometry.matricesIndices._isExpanded;
  41052. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  41053. }
  41054. }
  41055. if (parsedGeometry.matricesWeights) {
  41056. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  41057. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  41058. }
  41059. if (parsedGeometry.matricesWeightsExtra) {
  41060. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  41061. }
  41062. mesh.setIndices(parsedGeometry.indices, null);
  41063. }
  41064. // SubMeshes
  41065. if (parsedGeometry.subMeshes) {
  41066. mesh.subMeshes = [];
  41067. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  41068. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  41069. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  41070. }
  41071. }
  41072. // Flat shading
  41073. if (mesh._shouldGenerateFlatShading) {
  41074. mesh.convertToFlatShadedMesh();
  41075. delete mesh._shouldGenerateFlatShading;
  41076. }
  41077. // Update
  41078. mesh.computeWorldMatrix(true);
  41079. scene.onMeshImportedObservable.notifyObservers(mesh);
  41080. };
  41081. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  41082. var epsilon = 1e-3;
  41083. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  41084. return;
  41085. }
  41086. var noInfluenceBoneIndex = 0.0;
  41087. if (parsedGeometry.skeletonId > -1) {
  41088. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  41089. if (!skeleton) {
  41090. return;
  41091. }
  41092. noInfluenceBoneIndex = skeleton.bones.length;
  41093. }
  41094. else {
  41095. return;
  41096. }
  41097. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  41098. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  41099. var matricesWeights = parsedGeometry.matricesWeights;
  41100. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  41101. var influencers = parsedGeometry.numBoneInfluencer;
  41102. var size = matricesWeights.length;
  41103. for (var i = 0; i < size; i += 4) {
  41104. var weight = 0.0;
  41105. var firstZeroWeight = -1;
  41106. for (var j = 0; j < 4; j++) {
  41107. var w = matricesWeights[i + j];
  41108. weight += w;
  41109. if (w < epsilon && firstZeroWeight < 0) {
  41110. firstZeroWeight = j;
  41111. }
  41112. }
  41113. if (matricesWeightsExtra) {
  41114. for (var j = 0; j < 4; j++) {
  41115. var w = matricesWeightsExtra[i + j];
  41116. weight += w;
  41117. if (w < epsilon && firstZeroWeight < 0) {
  41118. firstZeroWeight = j + 4;
  41119. }
  41120. }
  41121. }
  41122. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  41123. firstZeroWeight = influencers - 1;
  41124. }
  41125. if (weight > epsilon) {
  41126. var mweight = 1.0 / weight;
  41127. for (var j = 0; j < 4; j++) {
  41128. matricesWeights[i + j] *= mweight;
  41129. }
  41130. if (matricesWeightsExtra) {
  41131. for (var j = 0; j < 4; j++) {
  41132. matricesWeightsExtra[i + j] *= mweight;
  41133. }
  41134. }
  41135. }
  41136. else {
  41137. if (firstZeroWeight >= 4) {
  41138. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  41139. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  41140. }
  41141. else {
  41142. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  41143. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  41144. }
  41145. }
  41146. }
  41147. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  41148. if (parsedGeometry.matricesWeightsExtra) {
  41149. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  41150. }
  41151. };
  41152. /**
  41153. * Create a new geometry from persisted data (Using .babylon file format)
  41154. * @param parsedVertexData defines the persisted data
  41155. * @param scene defines the hosting scene
  41156. * @param rootUrl defines the root url to use to load assets (like delayed data)
  41157. * @returns the new geometry object
  41158. */
  41159. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  41160. if (scene.getGeometryByID(parsedVertexData.id)) {
  41161. return null; // null since geometry could be something else than a box...
  41162. }
  41163. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  41164. if (BABYLON.Tags) {
  41165. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  41166. }
  41167. if (parsedVertexData.delayLoadingFile) {
  41168. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  41169. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  41170. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  41171. geometry._delayInfo = [];
  41172. if (parsedVertexData.hasUVs) {
  41173. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  41174. }
  41175. if (parsedVertexData.hasUVs2) {
  41176. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  41177. }
  41178. if (parsedVertexData.hasUVs3) {
  41179. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  41180. }
  41181. if (parsedVertexData.hasUVs4) {
  41182. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  41183. }
  41184. if (parsedVertexData.hasUVs5) {
  41185. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  41186. }
  41187. if (parsedVertexData.hasUVs6) {
  41188. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  41189. }
  41190. if (parsedVertexData.hasColors) {
  41191. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  41192. }
  41193. if (parsedVertexData.hasMatricesIndices) {
  41194. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  41195. }
  41196. if (parsedVertexData.hasMatricesWeights) {
  41197. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  41198. }
  41199. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  41200. }
  41201. else {
  41202. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  41203. }
  41204. scene.pushGeometry(geometry, true);
  41205. return geometry;
  41206. };
  41207. return Geometry;
  41208. }());
  41209. BABYLON.Geometry = Geometry;
  41210. // Primitives
  41211. /// Abstract class
  41212. /**
  41213. * Abstract class used to provide common services for all typed geometries
  41214. * @hidden
  41215. */
  41216. var _PrimitiveGeometry = /** @class */ (function (_super) {
  41217. __extends(_PrimitiveGeometry, _super);
  41218. /**
  41219. * Creates a new typed geometry
  41220. * @param id defines the unique ID of the geometry
  41221. * @param scene defines the hosting scene
  41222. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41223. * @param mesh defines the hosting mesh (can be null)
  41224. */
  41225. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  41226. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  41227. if (mesh === void 0) { mesh = null; }
  41228. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  41229. _this._canBeRegenerated = _canBeRegenerated;
  41230. _this._beingRegenerated = true;
  41231. _this.regenerate();
  41232. _this._beingRegenerated = false;
  41233. return _this;
  41234. }
  41235. /**
  41236. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  41237. * @returns true if the geometry can be regenerated
  41238. */
  41239. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  41240. return this._canBeRegenerated;
  41241. };
  41242. /**
  41243. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  41244. */
  41245. _PrimitiveGeometry.prototype.regenerate = function () {
  41246. if (!this._canBeRegenerated) {
  41247. return;
  41248. }
  41249. this._beingRegenerated = true;
  41250. this.setAllVerticesData(this._regenerateVertexData(), false);
  41251. this._beingRegenerated = false;
  41252. };
  41253. /**
  41254. * Clone the geometry
  41255. * @param id defines the unique ID of the new geometry
  41256. * @returns the new geometry
  41257. */
  41258. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  41259. return _super.prototype.copy.call(this, id);
  41260. };
  41261. // overrides
  41262. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  41263. if (!this._beingRegenerated) {
  41264. return;
  41265. }
  41266. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  41267. };
  41268. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  41269. if (!this._beingRegenerated) {
  41270. return;
  41271. }
  41272. _super.prototype.setVerticesData.call(this, kind, data, false);
  41273. };
  41274. // to override
  41275. /** @hidden */
  41276. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  41277. throw new Error("Abstract method");
  41278. };
  41279. _PrimitiveGeometry.prototype.copy = function (id) {
  41280. throw new Error("Must be overriden in sub-classes.");
  41281. };
  41282. _PrimitiveGeometry.prototype.serialize = function () {
  41283. var serializationObject = _super.prototype.serialize.call(this);
  41284. serializationObject.canBeRegenerated = this.canBeRegenerated();
  41285. return serializationObject;
  41286. };
  41287. return _PrimitiveGeometry;
  41288. }(Geometry));
  41289. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  41290. /**
  41291. * Creates a ribbon geometry
  41292. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  41293. */
  41294. var RibbonGeometry = /** @class */ (function (_super) {
  41295. __extends(RibbonGeometry, _super);
  41296. /**
  41297. * Creates a ribbon geometry
  41298. * @param id defines the unique ID of the geometry
  41299. * @param scene defines the hosting scene
  41300. * @param pathArray defines the array of paths to use
  41301. * @param closeArray defines if the last path and the first path must be joined
  41302. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  41303. * @param offset defines the offset between points
  41304. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41305. * @param mesh defines the hosting mesh (can be null)
  41306. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41307. */
  41308. function RibbonGeometry(id, scene,
  41309. /**
  41310. * Defines the array of paths to use
  41311. */
  41312. pathArray,
  41313. /**
  41314. * Defines if the last and first points of each path in your pathArray must be joined
  41315. */
  41316. closeArray,
  41317. /**
  41318. * Defines if the last and first points of each path in your pathArray must be joined
  41319. */
  41320. closePath,
  41321. /**
  41322. * Defines the offset between points
  41323. */
  41324. offset, canBeRegenerated, mesh,
  41325. /**
  41326. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41327. */
  41328. side) {
  41329. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41330. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41331. _this.pathArray = pathArray;
  41332. _this.closeArray = closeArray;
  41333. _this.closePath = closePath;
  41334. _this.offset = offset;
  41335. _this.side = side;
  41336. return _this;
  41337. }
  41338. /** @hidden */
  41339. RibbonGeometry.prototype._regenerateVertexData = function () {
  41340. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  41341. };
  41342. RibbonGeometry.prototype.copy = function (id) {
  41343. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  41344. };
  41345. return RibbonGeometry;
  41346. }(_PrimitiveGeometry));
  41347. BABYLON.RibbonGeometry = RibbonGeometry;
  41348. /**
  41349. * Creates a box geometry
  41350. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  41351. */
  41352. var BoxGeometry = /** @class */ (function (_super) {
  41353. __extends(BoxGeometry, _super);
  41354. /**
  41355. * Creates a box geometry
  41356. * @param id defines the unique ID of the geometry
  41357. * @param scene defines the hosting scene
  41358. * @param size defines the zise of the box (width, height and depth are the same)
  41359. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41360. * @param mesh defines the hosting mesh (can be null)
  41361. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41362. */
  41363. function BoxGeometry(id, scene,
  41364. /**
  41365. * Defines the zise of the box (width, height and depth are the same)
  41366. */
  41367. size, canBeRegenerated, mesh,
  41368. /**
  41369. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41370. */
  41371. side) {
  41372. if (mesh === void 0) { mesh = null; }
  41373. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41374. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41375. _this.size = size;
  41376. _this.side = side;
  41377. return _this;
  41378. }
  41379. /** @hidden */
  41380. BoxGeometry.prototype._regenerateVertexData = function () {
  41381. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  41382. };
  41383. BoxGeometry.prototype.copy = function (id) {
  41384. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  41385. };
  41386. BoxGeometry.prototype.serialize = function () {
  41387. var serializationObject = _super.prototype.serialize.call(this);
  41388. serializationObject.size = this.size;
  41389. return serializationObject;
  41390. };
  41391. BoxGeometry.Parse = function (parsedBox, scene) {
  41392. if (scene.getGeometryByID(parsedBox.id)) {
  41393. return null; // null since geometry could be something else than a box...
  41394. }
  41395. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  41396. if (BABYLON.Tags) {
  41397. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  41398. }
  41399. scene.pushGeometry(box, true);
  41400. return box;
  41401. };
  41402. return BoxGeometry;
  41403. }(_PrimitiveGeometry));
  41404. BABYLON.BoxGeometry = BoxGeometry;
  41405. /**
  41406. * Creates a sphere geometry
  41407. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  41408. */
  41409. var SphereGeometry = /** @class */ (function (_super) {
  41410. __extends(SphereGeometry, _super);
  41411. /**
  41412. * Create a new sphere geometry
  41413. * @param id defines the unique ID of the geometry
  41414. * @param scene defines the hosting scene
  41415. * @param segments defines the number of segments to use to create the sphere
  41416. * @param diameter defines the diameter of the sphere
  41417. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41418. * @param mesh defines the hosting mesh (can be null)
  41419. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41420. */
  41421. function SphereGeometry(id, scene,
  41422. /**
  41423. * Defines the number of segments to use to create the sphere
  41424. */
  41425. segments,
  41426. /**
  41427. * Defines the diameter of the sphere
  41428. */
  41429. diameter, canBeRegenerated, mesh,
  41430. /**
  41431. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41432. */
  41433. side) {
  41434. if (mesh === void 0) { mesh = null; }
  41435. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41436. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41437. _this.segments = segments;
  41438. _this.diameter = diameter;
  41439. _this.side = side;
  41440. return _this;
  41441. }
  41442. /** @hidden */
  41443. SphereGeometry.prototype._regenerateVertexData = function () {
  41444. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  41445. };
  41446. SphereGeometry.prototype.copy = function (id) {
  41447. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  41448. };
  41449. SphereGeometry.prototype.serialize = function () {
  41450. var serializationObject = _super.prototype.serialize.call(this);
  41451. serializationObject.segments = this.segments;
  41452. serializationObject.diameter = this.diameter;
  41453. return serializationObject;
  41454. };
  41455. SphereGeometry.Parse = function (parsedSphere, scene) {
  41456. if (scene.getGeometryByID(parsedSphere.id)) {
  41457. return null; // null since geometry could be something else than a sphere...
  41458. }
  41459. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  41460. if (BABYLON.Tags) {
  41461. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  41462. }
  41463. scene.pushGeometry(sphere, true);
  41464. return sphere;
  41465. };
  41466. return SphereGeometry;
  41467. }(_PrimitiveGeometry));
  41468. BABYLON.SphereGeometry = SphereGeometry;
  41469. /**
  41470. * Creates a disc geometry
  41471. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  41472. */
  41473. var DiscGeometry = /** @class */ (function (_super) {
  41474. __extends(DiscGeometry, _super);
  41475. /**
  41476. * Creates a new disc geometry
  41477. * @param id defines the unique ID of the geometry
  41478. * @param scene defines the hosting scene
  41479. * @param radius defines the radius of the disc
  41480. * @param tessellation defines the tesselation factor to apply to the disc
  41481. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41482. * @param mesh defines the hosting mesh (can be null)
  41483. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41484. */
  41485. function DiscGeometry(id, scene,
  41486. /**
  41487. * Defines the radius of the disc
  41488. */
  41489. radius,
  41490. /**
  41491. * Defines the tesselation factor to apply to the disc
  41492. */
  41493. tessellation, canBeRegenerated, mesh,
  41494. /**
  41495. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41496. */
  41497. side) {
  41498. if (mesh === void 0) { mesh = null; }
  41499. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41500. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41501. _this.radius = radius;
  41502. _this.tessellation = tessellation;
  41503. _this.side = side;
  41504. return _this;
  41505. }
  41506. /** @hidden */
  41507. DiscGeometry.prototype._regenerateVertexData = function () {
  41508. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  41509. };
  41510. DiscGeometry.prototype.copy = function (id) {
  41511. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  41512. };
  41513. return DiscGeometry;
  41514. }(_PrimitiveGeometry));
  41515. BABYLON.DiscGeometry = DiscGeometry;
  41516. /**
  41517. * Creates a new cylinder geometry
  41518. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  41519. */
  41520. var CylinderGeometry = /** @class */ (function (_super) {
  41521. __extends(CylinderGeometry, _super);
  41522. /**
  41523. * Creates a new cylinder geometry
  41524. * @param id defines the unique ID of the geometry
  41525. * @param scene defines the hosting scene
  41526. * @param height defines the height of the cylinder
  41527. * @param diameterTop defines the diameter of the cylinder's top cap
  41528. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  41529. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  41530. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  41531. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41532. * @param mesh defines the hosting mesh (can be null)
  41533. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41534. */
  41535. function CylinderGeometry(id, scene,
  41536. /**
  41537. * Defines the height of the cylinder
  41538. */
  41539. height,
  41540. /**
  41541. * Defines the diameter of the cylinder's top cap
  41542. */
  41543. diameterTop,
  41544. /**
  41545. * Defines the diameter of the cylinder's bottom cap
  41546. */
  41547. diameterBottom,
  41548. /**
  41549. * Defines the tessellation factor to apply to the cylinder
  41550. */
  41551. tessellation,
  41552. /**
  41553. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  41554. */
  41555. subdivisions, canBeRegenerated, mesh,
  41556. /**
  41557. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41558. */
  41559. side) {
  41560. if (subdivisions === void 0) { subdivisions = 1; }
  41561. if (mesh === void 0) { mesh = null; }
  41562. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41563. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41564. _this.height = height;
  41565. _this.diameterTop = diameterTop;
  41566. _this.diameterBottom = diameterBottom;
  41567. _this.tessellation = tessellation;
  41568. _this.subdivisions = subdivisions;
  41569. _this.side = side;
  41570. return _this;
  41571. }
  41572. /** @hidden */
  41573. CylinderGeometry.prototype._regenerateVertexData = function () {
  41574. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  41575. };
  41576. CylinderGeometry.prototype.copy = function (id) {
  41577. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  41578. };
  41579. CylinderGeometry.prototype.serialize = function () {
  41580. var serializationObject = _super.prototype.serialize.call(this);
  41581. serializationObject.height = this.height;
  41582. serializationObject.diameterTop = this.diameterTop;
  41583. serializationObject.diameterBottom = this.diameterBottom;
  41584. serializationObject.tessellation = this.tessellation;
  41585. return serializationObject;
  41586. };
  41587. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  41588. if (scene.getGeometryByID(parsedCylinder.id)) {
  41589. return null; // null since geometry could be something else than a cylinder...
  41590. }
  41591. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  41592. if (BABYLON.Tags) {
  41593. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  41594. }
  41595. scene.pushGeometry(cylinder, true);
  41596. return cylinder;
  41597. };
  41598. return CylinderGeometry;
  41599. }(_PrimitiveGeometry));
  41600. BABYLON.CylinderGeometry = CylinderGeometry;
  41601. /**
  41602. * Creates a new torus geometry
  41603. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  41604. */
  41605. var TorusGeometry = /** @class */ (function (_super) {
  41606. __extends(TorusGeometry, _super);
  41607. /**
  41608. * Creates a new torus geometry
  41609. * @param id defines the unique ID of the geometry
  41610. * @param scene defines the hosting scene
  41611. * @param diameter defines the diameter of the torus
  41612. * @param thickness defines the thickness of the torus (ie. internal diameter)
  41613. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  41614. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41615. * @param mesh defines the hosting mesh (can be null)
  41616. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41617. */
  41618. function TorusGeometry(id, scene,
  41619. /**
  41620. * Defines the diameter of the torus
  41621. */
  41622. diameter,
  41623. /**
  41624. * Defines the thickness of the torus (ie. internal diameter)
  41625. */
  41626. thickness,
  41627. /**
  41628. * Defines the tesselation factor to apply to the torus
  41629. */
  41630. tessellation, canBeRegenerated, mesh,
  41631. /**
  41632. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41633. */
  41634. side) {
  41635. if (mesh === void 0) { mesh = null; }
  41636. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41637. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41638. _this.diameter = diameter;
  41639. _this.thickness = thickness;
  41640. _this.tessellation = tessellation;
  41641. _this.side = side;
  41642. return _this;
  41643. }
  41644. /** @hidden */
  41645. TorusGeometry.prototype._regenerateVertexData = function () {
  41646. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  41647. };
  41648. TorusGeometry.prototype.copy = function (id) {
  41649. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  41650. };
  41651. TorusGeometry.prototype.serialize = function () {
  41652. var serializationObject = _super.prototype.serialize.call(this);
  41653. serializationObject.diameter = this.diameter;
  41654. serializationObject.thickness = this.thickness;
  41655. serializationObject.tessellation = this.tessellation;
  41656. return serializationObject;
  41657. };
  41658. TorusGeometry.Parse = function (parsedTorus, scene) {
  41659. if (scene.getGeometryByID(parsedTorus.id)) {
  41660. return null; // null since geometry could be something else than a torus...
  41661. }
  41662. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  41663. if (BABYLON.Tags) {
  41664. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  41665. }
  41666. scene.pushGeometry(torus, true);
  41667. return torus;
  41668. };
  41669. return TorusGeometry;
  41670. }(_PrimitiveGeometry));
  41671. BABYLON.TorusGeometry = TorusGeometry;
  41672. /**
  41673. * Creates a new ground geometry
  41674. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  41675. */
  41676. var GroundGeometry = /** @class */ (function (_super) {
  41677. __extends(GroundGeometry, _super);
  41678. /**
  41679. * Creates a new ground geometry
  41680. * @param id defines the unique ID of the geometry
  41681. * @param scene defines the hosting scene
  41682. * @param width defines the width of the ground
  41683. * @param height defines the height of the ground
  41684. * @param subdivisions defines the subdivisions to apply to the ground
  41685. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41686. * @param mesh defines the hosting mesh (can be null)
  41687. */
  41688. function GroundGeometry(id, scene,
  41689. /**
  41690. * Defines the width of the ground
  41691. */
  41692. width,
  41693. /**
  41694. * Defines the height of the ground
  41695. */
  41696. height,
  41697. /**
  41698. * Defines the subdivisions to apply to the ground
  41699. */
  41700. subdivisions, canBeRegenerated, mesh) {
  41701. if (mesh === void 0) { mesh = null; }
  41702. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41703. _this.width = width;
  41704. _this.height = height;
  41705. _this.subdivisions = subdivisions;
  41706. return _this;
  41707. }
  41708. /** @hidden */
  41709. GroundGeometry.prototype._regenerateVertexData = function () {
  41710. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  41711. };
  41712. GroundGeometry.prototype.copy = function (id) {
  41713. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  41714. };
  41715. GroundGeometry.prototype.serialize = function () {
  41716. var serializationObject = _super.prototype.serialize.call(this);
  41717. serializationObject.width = this.width;
  41718. serializationObject.height = this.height;
  41719. serializationObject.subdivisions = this.subdivisions;
  41720. return serializationObject;
  41721. };
  41722. GroundGeometry.Parse = function (parsedGround, scene) {
  41723. if (scene.getGeometryByID(parsedGround.id)) {
  41724. return null; // null since geometry could be something else than a ground...
  41725. }
  41726. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  41727. if (BABYLON.Tags) {
  41728. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  41729. }
  41730. scene.pushGeometry(ground, true);
  41731. return ground;
  41732. };
  41733. return GroundGeometry;
  41734. }(_PrimitiveGeometry));
  41735. BABYLON.GroundGeometry = GroundGeometry;
  41736. /**
  41737. * Creates a tiled ground geometry
  41738. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  41739. */
  41740. var TiledGroundGeometry = /** @class */ (function (_super) {
  41741. __extends(TiledGroundGeometry, _super);
  41742. /**
  41743. * Creates a tiled ground geometry
  41744. * @param id defines the unique ID of the geometry
  41745. * @param scene defines the hosting scene
  41746. * @param xmin defines the minimum value on X axis
  41747. * @param zmin defines the minimum value on Z axis
  41748. * @param xmax defines the maximum value on X axis
  41749. * @param zmax defines the maximum value on Z axis
  41750. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  41751. * @param precision defines the precision to use when computing the tiles
  41752. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41753. * @param mesh defines the hosting mesh (can be null)
  41754. */
  41755. function TiledGroundGeometry(id, scene,
  41756. /**
  41757. * Defines the minimum value on X axis
  41758. */
  41759. xmin,
  41760. /**
  41761. * Defines the minimum value on Z axis
  41762. */
  41763. zmin,
  41764. /**
  41765. * Defines the maximum value on X axis
  41766. */
  41767. xmax,
  41768. /**
  41769. * Defines the maximum value on Z axis
  41770. */
  41771. zmax,
  41772. /**
  41773. * Defines the subdivisions to apply to the ground
  41774. */
  41775. subdivisions,
  41776. /**
  41777. * Defines the precision to use when computing the tiles
  41778. */
  41779. precision, canBeRegenerated, mesh) {
  41780. if (mesh === void 0) { mesh = null; }
  41781. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41782. _this.xmin = xmin;
  41783. _this.zmin = zmin;
  41784. _this.xmax = xmax;
  41785. _this.zmax = zmax;
  41786. _this.subdivisions = subdivisions;
  41787. _this.precision = precision;
  41788. return _this;
  41789. }
  41790. /** @hidden */
  41791. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  41792. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  41793. };
  41794. TiledGroundGeometry.prototype.copy = function (id) {
  41795. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  41796. };
  41797. return TiledGroundGeometry;
  41798. }(_PrimitiveGeometry));
  41799. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  41800. /**
  41801. * Creates a plane geometry
  41802. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  41803. */
  41804. var PlaneGeometry = /** @class */ (function (_super) {
  41805. __extends(PlaneGeometry, _super);
  41806. /**
  41807. * Creates a plane geometry
  41808. * @param id defines the unique ID of the geometry
  41809. * @param scene defines the hosting scene
  41810. * @param size defines the size of the plane (width === height)
  41811. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41812. * @param mesh defines the hosting mesh (can be null)
  41813. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41814. */
  41815. function PlaneGeometry(id, scene,
  41816. /**
  41817. * Defines the size of the plane (width === height)
  41818. */
  41819. size, canBeRegenerated, mesh,
  41820. /**
  41821. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41822. */
  41823. side) {
  41824. if (mesh === void 0) { mesh = null; }
  41825. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41826. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41827. _this.size = size;
  41828. _this.side = side;
  41829. return _this;
  41830. }
  41831. /** @hidden */
  41832. PlaneGeometry.prototype._regenerateVertexData = function () {
  41833. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  41834. };
  41835. PlaneGeometry.prototype.copy = function (id) {
  41836. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  41837. };
  41838. PlaneGeometry.prototype.serialize = function () {
  41839. var serializationObject = _super.prototype.serialize.call(this);
  41840. serializationObject.size = this.size;
  41841. return serializationObject;
  41842. };
  41843. PlaneGeometry.Parse = function (parsedPlane, scene) {
  41844. if (scene.getGeometryByID(parsedPlane.id)) {
  41845. return null; // null since geometry could be something else than a ground...
  41846. }
  41847. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  41848. if (BABYLON.Tags) {
  41849. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  41850. }
  41851. scene.pushGeometry(plane, true);
  41852. return plane;
  41853. };
  41854. return PlaneGeometry;
  41855. }(_PrimitiveGeometry));
  41856. BABYLON.PlaneGeometry = PlaneGeometry;
  41857. /**
  41858. * Creates a torus knot geometry
  41859. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  41860. */
  41861. var TorusKnotGeometry = /** @class */ (function (_super) {
  41862. __extends(TorusKnotGeometry, _super);
  41863. /**
  41864. * Creates a torus knot geometry
  41865. * @param id defines the unique ID of the geometry
  41866. * @param scene defines the hosting scene
  41867. * @param radius defines the radius of the torus knot
  41868. * @param tube defines the thickness of the torus knot tube
  41869. * @param radialSegments defines the number of radial segments
  41870. * @param tubularSegments defines the number of tubular segments
  41871. * @param p defines the first number of windings
  41872. * @param q defines the second number of windings
  41873. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41874. * @param mesh defines the hosting mesh (can be null)
  41875. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41876. */
  41877. function TorusKnotGeometry(id, scene,
  41878. /**
  41879. * Defines the radius of the torus knot
  41880. */
  41881. radius,
  41882. /**
  41883. * Defines the thickness of the torus knot tube
  41884. */
  41885. tube,
  41886. /**
  41887. * Defines the number of radial segments
  41888. */
  41889. radialSegments,
  41890. /**
  41891. * Defines the number of tubular segments
  41892. */
  41893. tubularSegments,
  41894. /**
  41895. * Defines the first number of windings
  41896. */
  41897. p,
  41898. /**
  41899. * Defines the second number of windings
  41900. */
  41901. q, canBeRegenerated, mesh,
  41902. /**
  41903. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41904. */
  41905. side) {
  41906. if (mesh === void 0) { mesh = null; }
  41907. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41908. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41909. _this.radius = radius;
  41910. _this.tube = tube;
  41911. _this.radialSegments = radialSegments;
  41912. _this.tubularSegments = tubularSegments;
  41913. _this.p = p;
  41914. _this.q = q;
  41915. _this.side = side;
  41916. return _this;
  41917. }
  41918. /** @hidden */
  41919. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  41920. 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 });
  41921. };
  41922. TorusKnotGeometry.prototype.copy = function (id) {
  41923. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  41924. };
  41925. TorusKnotGeometry.prototype.serialize = function () {
  41926. var serializationObject = _super.prototype.serialize.call(this);
  41927. serializationObject.radius = this.radius;
  41928. serializationObject.tube = this.tube;
  41929. serializationObject.radialSegments = this.radialSegments;
  41930. serializationObject.tubularSegments = this.tubularSegments;
  41931. serializationObject.p = this.p;
  41932. serializationObject.q = this.q;
  41933. return serializationObject;
  41934. };
  41935. ;
  41936. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  41937. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  41938. return null; // null since geometry could be something else than a ground...
  41939. }
  41940. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  41941. if (BABYLON.Tags) {
  41942. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  41943. }
  41944. scene.pushGeometry(torusKnot, true);
  41945. return torusKnot;
  41946. };
  41947. return TorusKnotGeometry;
  41948. }(_PrimitiveGeometry));
  41949. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  41950. //}
  41951. })(BABYLON || (BABYLON = {}));
  41952. //# sourceMappingURL=babylon.geometry.js.map
  41953. var BABYLON;
  41954. (function (BABYLON) {
  41955. /**
  41956. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  41957. */
  41958. var PerformanceMonitor = /** @class */ (function () {
  41959. /**
  41960. * constructor
  41961. * @param frameSampleSize The number of samples required to saturate the sliding window
  41962. */
  41963. function PerformanceMonitor(frameSampleSize) {
  41964. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  41965. this._enabled = true;
  41966. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  41967. }
  41968. /**
  41969. * Samples current frame
  41970. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  41971. */
  41972. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  41973. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  41974. if (!this._enabled)
  41975. return;
  41976. if (this._lastFrameTimeMs != null) {
  41977. var dt = timeMs - this._lastFrameTimeMs;
  41978. this._rollingFrameTime.add(dt);
  41979. }
  41980. this._lastFrameTimeMs = timeMs;
  41981. };
  41982. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  41983. /**
  41984. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  41985. */
  41986. get: function () {
  41987. return this._rollingFrameTime.average;
  41988. },
  41989. enumerable: true,
  41990. configurable: true
  41991. });
  41992. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  41993. /**
  41994. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  41995. */
  41996. get: function () {
  41997. return this._rollingFrameTime.variance;
  41998. },
  41999. enumerable: true,
  42000. configurable: true
  42001. });
  42002. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  42003. /**
  42004. * Returns the frame time of the most recent frame
  42005. */
  42006. get: function () {
  42007. return this._rollingFrameTime.history(0);
  42008. },
  42009. enumerable: true,
  42010. configurable: true
  42011. });
  42012. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  42013. /**
  42014. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  42015. */
  42016. get: function () {
  42017. return 1000.0 / this._rollingFrameTime.average;
  42018. },
  42019. enumerable: true,
  42020. configurable: true
  42021. });
  42022. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  42023. /**
  42024. * Returns the average framerate in frames per second using the most recent frame time
  42025. */
  42026. get: function () {
  42027. var history = this._rollingFrameTime.history(0);
  42028. if (history === 0) {
  42029. return 0;
  42030. }
  42031. return 1000.0 / history;
  42032. },
  42033. enumerable: true,
  42034. configurable: true
  42035. });
  42036. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  42037. /**
  42038. * Returns true if enough samples have been taken to completely fill the sliding window
  42039. */
  42040. get: function () {
  42041. return this._rollingFrameTime.isSaturated();
  42042. },
  42043. enumerable: true,
  42044. configurable: true
  42045. });
  42046. /**
  42047. * Enables contributions to the sliding window sample set
  42048. */
  42049. PerformanceMonitor.prototype.enable = function () {
  42050. this._enabled = true;
  42051. };
  42052. /**
  42053. * Disables contributions to the sliding window sample set
  42054. * Samples will not be interpolated over the disabled period
  42055. */
  42056. PerformanceMonitor.prototype.disable = function () {
  42057. this._enabled = false;
  42058. //clear last sample to avoid interpolating over the disabled period when next enabled
  42059. this._lastFrameTimeMs = null;
  42060. };
  42061. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  42062. /**
  42063. * Returns true if sampling is enabled
  42064. */
  42065. get: function () {
  42066. return this._enabled;
  42067. },
  42068. enumerable: true,
  42069. configurable: true
  42070. });
  42071. /**
  42072. * Resets performance monitor
  42073. */
  42074. PerformanceMonitor.prototype.reset = function () {
  42075. //clear last sample to avoid interpolating over the disabled period when next enabled
  42076. this._lastFrameTimeMs = null;
  42077. //wipe record
  42078. this._rollingFrameTime.reset();
  42079. };
  42080. return PerformanceMonitor;
  42081. }());
  42082. BABYLON.PerformanceMonitor = PerformanceMonitor;
  42083. /**
  42084. * RollingAverage
  42085. *
  42086. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  42087. */
  42088. var RollingAverage = /** @class */ (function () {
  42089. /**
  42090. * constructor
  42091. * @param length The number of samples required to saturate the sliding window
  42092. */
  42093. function RollingAverage(length) {
  42094. this._samples = new Array(length);
  42095. this.reset();
  42096. }
  42097. /**
  42098. * Adds a sample to the sample set
  42099. * @param v The sample value
  42100. */
  42101. RollingAverage.prototype.add = function (v) {
  42102. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  42103. var delta;
  42104. //we need to check if we've already wrapped round
  42105. if (this.isSaturated()) {
  42106. //remove bottom of stack from mean
  42107. var bottomValue = this._samples[this._pos];
  42108. delta = bottomValue - this.average;
  42109. this.average -= delta / (this._sampleCount - 1);
  42110. this._m2 -= delta * (bottomValue - this.average);
  42111. }
  42112. else {
  42113. this._sampleCount++;
  42114. }
  42115. //add new value to mean
  42116. delta = v - this.average;
  42117. this.average += delta / (this._sampleCount);
  42118. this._m2 += delta * (v - this.average);
  42119. //set the new variance
  42120. this.variance = this._m2 / (this._sampleCount - 1);
  42121. this._samples[this._pos] = v;
  42122. this._pos++;
  42123. this._pos %= this._samples.length; //positive wrap around
  42124. };
  42125. /**
  42126. * Returns previously added values or null if outside of history or outside the sliding window domain
  42127. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  42128. * @return Value previously recorded with add() or null if outside of range
  42129. */
  42130. RollingAverage.prototype.history = function (i) {
  42131. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  42132. return 0;
  42133. }
  42134. var i0 = this._wrapPosition(this._pos - 1.0);
  42135. return this._samples[this._wrapPosition(i0 - i)];
  42136. };
  42137. /**
  42138. * Returns true if enough samples have been taken to completely fill the sliding window
  42139. * @return true if sample-set saturated
  42140. */
  42141. RollingAverage.prototype.isSaturated = function () {
  42142. return this._sampleCount >= this._samples.length;
  42143. };
  42144. /**
  42145. * Resets the rolling average (equivalent to 0 samples taken so far)
  42146. */
  42147. RollingAverage.prototype.reset = function () {
  42148. this.average = 0;
  42149. this.variance = 0;
  42150. this._sampleCount = 0;
  42151. this._pos = 0;
  42152. this._m2 = 0;
  42153. };
  42154. /**
  42155. * Wraps a value around the sample range boundaries
  42156. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  42157. * @return Wrapped position in sample range
  42158. */
  42159. RollingAverage.prototype._wrapPosition = function (i) {
  42160. var max = this._samples.length;
  42161. return ((i % max) + max) % max;
  42162. };
  42163. return RollingAverage;
  42164. }());
  42165. BABYLON.RollingAverage = RollingAverage;
  42166. })(BABYLON || (BABYLON = {}));
  42167. //# sourceMappingURL=babylon.performanceMonitor.js.map
  42168. var BABYLON;
  42169. (function (BABYLON) {
  42170. /**
  42171. * "Static Class" containing the most commonly used helper while dealing with material for
  42172. * rendering purpose.
  42173. *
  42174. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  42175. *
  42176. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  42177. */
  42178. var MaterialHelper = /** @class */ (function () {
  42179. function MaterialHelper() {
  42180. }
  42181. /**
  42182. * Bind the current view position to an effect.
  42183. * @param effect The effect to be bound
  42184. * @param scene The scene the eyes position is used from
  42185. */
  42186. MaterialHelper.BindEyePosition = function (effect, scene) {
  42187. if (scene._forcedViewPosition) {
  42188. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  42189. return;
  42190. }
  42191. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  42192. };
  42193. /**
  42194. * Helps preparing the defines values about the UVs in used in the effect.
  42195. * UVs are shared as much as we can accross channels in the shaders.
  42196. * @param texture The texture we are preparing the UVs for
  42197. * @param defines The defines to update
  42198. * @param key The channel key "diffuse", "specular"... used in the shader
  42199. */
  42200. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  42201. defines._needUVs = true;
  42202. defines[key] = true;
  42203. if (texture.getTextureMatrix().isIdentity(true)) {
  42204. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  42205. if (texture.coordinatesIndex === 0) {
  42206. defines["MAINUV1"] = true;
  42207. }
  42208. else {
  42209. defines["MAINUV2"] = true;
  42210. }
  42211. }
  42212. else {
  42213. defines[key + "DIRECTUV"] = 0;
  42214. }
  42215. };
  42216. /**
  42217. * Binds a texture matrix value to its corrsponding uniform
  42218. * @param texture The texture to bind the matrix for
  42219. * @param uniformBuffer The uniform buffer receivin the data
  42220. * @param key The channel key "diffuse", "specular"... used in the shader
  42221. */
  42222. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  42223. var matrix = texture.getTextureMatrix();
  42224. if (!matrix.isIdentity(true)) {
  42225. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  42226. }
  42227. };
  42228. /**
  42229. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  42230. * @param mesh defines the current mesh
  42231. * @param scene defines the current scene
  42232. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  42233. * @param pointsCloud defines if point cloud rendering has to be turned on
  42234. * @param fogEnabled defines if fog has to be turned on
  42235. * @param alphaTest defines if alpha testing has to be turned on
  42236. * @param defines defines the current list of defines
  42237. */
  42238. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  42239. if (defines._areMiscDirty) {
  42240. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  42241. defines["POINTSIZE"] = pointsCloud;
  42242. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  42243. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  42244. defines["ALPHATEST"] = alphaTest;
  42245. }
  42246. };
  42247. /**
  42248. * Helper used to prepare the list of defines associated with frame values for shader compilation
  42249. * @param scene defines the current scene
  42250. * @param engine defines the current engine
  42251. * @param defines specifies the list of active defines
  42252. * @param useInstances defines if instances have to be turned on
  42253. * @param useClipPlane defines if clip plane have to be turned on
  42254. */
  42255. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  42256. if (useClipPlane === void 0) { useClipPlane = null; }
  42257. var changed = false;
  42258. var useClipPlane1 = false;
  42259. var useClipPlane2 = false;
  42260. var useClipPlane3 = false;
  42261. var useClipPlane4 = false;
  42262. useClipPlane1 = useClipPlane == null ? (scene.clipPlane !== undefined && scene.clipPlane !== null) : useClipPlane;
  42263. useClipPlane2 = useClipPlane == null ? (scene.clipPlane2 !== undefined && scene.clipPlane2 !== null) : useClipPlane;
  42264. useClipPlane3 = useClipPlane == null ? (scene.clipPlane3 !== undefined && scene.clipPlane3 !== null) : useClipPlane;
  42265. useClipPlane4 = useClipPlane == null ? (scene.clipPlane4 !== undefined && scene.clipPlane4 !== null) : useClipPlane;
  42266. if (defines["CLIPPLANE"] !== useClipPlane1) {
  42267. defines["CLIPPLANE"] = useClipPlane1;
  42268. changed = true;
  42269. }
  42270. if (defines["CLIPPLANE2"] !== useClipPlane2) {
  42271. defines["CLIPPLANE2"] = useClipPlane2;
  42272. changed = true;
  42273. }
  42274. if (defines["CLIPPLANE3"] !== useClipPlane3) {
  42275. defines["CLIPPLANE3"] = useClipPlane3;
  42276. changed = true;
  42277. }
  42278. if (defines["CLIPPLANE4"] !== useClipPlane4) {
  42279. defines["CLIPPLANE4"] = useClipPlane4;
  42280. changed = true;
  42281. }
  42282. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  42283. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  42284. changed = true;
  42285. }
  42286. if (defines["INSTANCES"] !== useInstances) {
  42287. defines["INSTANCES"] = useInstances;
  42288. changed = true;
  42289. }
  42290. if (changed) {
  42291. defines.markAsUnprocessed();
  42292. }
  42293. };
  42294. /**
  42295. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  42296. * @param mesh The mesh containing the geometry data we will draw
  42297. * @param defines The defines to update
  42298. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  42299. * @param useBones Precise whether bones should be used or not (override mesh info)
  42300. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  42301. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  42302. * @returns false if defines are considered not dirty and have not been checked
  42303. */
  42304. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  42305. if (useMorphTargets === void 0) { useMorphTargets = false; }
  42306. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  42307. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  42308. return false;
  42309. }
  42310. defines._normals = defines._needNormals;
  42311. defines._uvs = defines._needUVs;
  42312. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  42313. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  42314. defines["TANGENT"] = true;
  42315. }
  42316. if (defines._needUVs) {
  42317. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  42318. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  42319. }
  42320. else {
  42321. defines["UV1"] = false;
  42322. defines["UV2"] = false;
  42323. }
  42324. if (useVertexColor) {
  42325. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  42326. defines["VERTEXCOLOR"] = hasVertexColors;
  42327. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  42328. }
  42329. if (useBones) {
  42330. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42331. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  42332. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  42333. }
  42334. else {
  42335. defines["NUM_BONE_INFLUENCERS"] = 0;
  42336. defines["BonesPerMesh"] = 0;
  42337. }
  42338. }
  42339. if (useMorphTargets) {
  42340. var manager = mesh.morphTargetManager;
  42341. if (manager) {
  42342. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  42343. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  42344. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  42345. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  42346. }
  42347. else {
  42348. defines["MORPHTARGETS_TANGENT"] = false;
  42349. defines["MORPHTARGETS_NORMAL"] = false;
  42350. defines["MORPHTARGETS"] = false;
  42351. defines["NUM_MORPH_INFLUENCERS"] = 0;
  42352. }
  42353. }
  42354. return true;
  42355. };
  42356. /**
  42357. * Prepares the defines related to the light information passed in parameter
  42358. * @param scene The scene we are intending to draw
  42359. * @param mesh The mesh the effect is compiling for
  42360. * @param defines The defines to update
  42361. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  42362. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  42363. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  42364. * @returns true if normals will be required for the rest of the effect
  42365. */
  42366. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  42367. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42368. if (disableLighting === void 0) { disableLighting = false; }
  42369. if (!defines._areLightsDirty) {
  42370. return defines._needNormals;
  42371. }
  42372. var lightIndex = 0;
  42373. var needNormals = false;
  42374. var needRebuild = false;
  42375. var lightmapMode = false;
  42376. var shadowEnabled = false;
  42377. var specularEnabled = false;
  42378. if (scene.lightsEnabled && !disableLighting) {
  42379. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  42380. var light = _a[_i];
  42381. needNormals = true;
  42382. if (defines["LIGHT" + lightIndex] === undefined) {
  42383. needRebuild = true;
  42384. }
  42385. defines["LIGHT" + lightIndex] = true;
  42386. defines["SPOTLIGHT" + lightIndex] = false;
  42387. defines["HEMILIGHT" + lightIndex] = false;
  42388. defines["POINTLIGHT" + lightIndex] = false;
  42389. defines["DIRLIGHT" + lightIndex] = false;
  42390. light.prepareLightSpecificDefines(defines, lightIndex);
  42391. // FallOff.
  42392. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = false;
  42393. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = false;
  42394. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = false;
  42395. switch (light.falloffType) {
  42396. case BABYLON.Light.FALLOFF_GLTF:
  42397. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = true;
  42398. break;
  42399. case BABYLON.Light.FALLOFF_PHYSICAL:
  42400. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = true;
  42401. break;
  42402. case BABYLON.Light.FALLOFF_STANDARD:
  42403. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = true;
  42404. break;
  42405. }
  42406. // Specular
  42407. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  42408. specularEnabled = true;
  42409. }
  42410. // Shadows
  42411. defines["SHADOW" + lightIndex] = false;
  42412. defines["SHADOWPCF" + lightIndex] = false;
  42413. defines["SHADOWPCSS" + lightIndex] = false;
  42414. defines["SHADOWPOISSON" + lightIndex] = false;
  42415. defines["SHADOWESM" + lightIndex] = false;
  42416. defines["SHADOWCUBE" + lightIndex] = false;
  42417. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  42418. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  42419. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  42420. var shadowGenerator = light.getShadowGenerator();
  42421. if (shadowGenerator) {
  42422. var shadowMap = shadowGenerator.getShadowMap();
  42423. if (shadowMap) {
  42424. if (shadowMap.renderList && shadowMap.renderList.length > 0) {
  42425. shadowEnabled = true;
  42426. shadowGenerator.prepareDefines(defines, lightIndex);
  42427. }
  42428. }
  42429. }
  42430. }
  42431. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  42432. lightmapMode = true;
  42433. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  42434. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  42435. }
  42436. else {
  42437. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  42438. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  42439. }
  42440. lightIndex++;
  42441. if (lightIndex === maxSimultaneousLights)
  42442. break;
  42443. }
  42444. }
  42445. defines["SPECULARTERM"] = specularEnabled;
  42446. defines["SHADOWS"] = shadowEnabled;
  42447. // Resetting all other lights if any
  42448. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  42449. if (defines["LIGHT" + index] !== undefined) {
  42450. defines["LIGHT" + index] = false;
  42451. defines["HEMILIGHT" + lightIndex] = false;
  42452. defines["POINTLIGHT" + lightIndex] = false;
  42453. defines["DIRLIGHT" + lightIndex] = false;
  42454. defines["SPOTLIGHT" + lightIndex] = false;
  42455. defines["SHADOW" + lightIndex] = false;
  42456. }
  42457. }
  42458. var caps = scene.getEngine().getCaps();
  42459. if (defines["SHADOWFLOAT"] === undefined) {
  42460. needRebuild = true;
  42461. }
  42462. defines["SHADOWFLOAT"] = shadowEnabled &&
  42463. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  42464. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  42465. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  42466. if (needRebuild) {
  42467. defines.rebuild();
  42468. }
  42469. return needNormals;
  42470. };
  42471. /**
  42472. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  42473. * that won t be acctive due to defines being turned off.
  42474. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  42475. * @param samplersList The samplers list
  42476. * @param defines The defines helping in the list generation
  42477. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  42478. */
  42479. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  42480. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42481. var uniformsList;
  42482. var uniformBuffersList = null;
  42483. if (uniformsListOrOptions.uniformsNames) {
  42484. var options = uniformsListOrOptions;
  42485. uniformsList = options.uniformsNames;
  42486. uniformBuffersList = options.uniformBuffersNames;
  42487. samplersList = options.samplers;
  42488. defines = options.defines;
  42489. maxSimultaneousLights = options.maxSimultaneousLights;
  42490. }
  42491. else {
  42492. uniformsList = uniformsListOrOptions;
  42493. if (!samplersList) {
  42494. samplersList = [];
  42495. }
  42496. }
  42497. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42498. if (!defines["LIGHT" + lightIndex]) {
  42499. break;
  42500. }
  42501. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightFalloff" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  42502. if (uniformBuffersList) {
  42503. uniformBuffersList.push("Light" + lightIndex);
  42504. }
  42505. samplersList.push("shadowSampler" + lightIndex);
  42506. samplersList.push("depthSampler" + lightIndex);
  42507. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  42508. samplersList.push("projectionLightSampler" + lightIndex);
  42509. uniformsList.push("textureProjectionMatrix" + lightIndex);
  42510. }
  42511. }
  42512. if (defines["NUM_MORPH_INFLUENCERS"]) {
  42513. uniformsList.push("morphTargetInfluences");
  42514. }
  42515. };
  42516. /**
  42517. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  42518. * @param defines The defines to update while falling back
  42519. * @param fallbacks The authorized effect fallbacks
  42520. * @param maxSimultaneousLights The maximum number of lights allowed
  42521. * @param rank the current rank of the Effect
  42522. * @returns The newly affected rank
  42523. */
  42524. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  42525. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42526. if (rank === void 0) { rank = 0; }
  42527. var lightFallbackRank = 0;
  42528. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42529. if (!defines["LIGHT" + lightIndex]) {
  42530. break;
  42531. }
  42532. if (lightIndex > 0) {
  42533. lightFallbackRank = rank + lightIndex;
  42534. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  42535. }
  42536. if (!defines["SHADOWS"]) {
  42537. if (defines["SHADOW" + lightIndex]) {
  42538. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  42539. }
  42540. if (defines["SHADOWPCF" + lightIndex]) {
  42541. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  42542. }
  42543. if (defines["SHADOWPCSS" + lightIndex]) {
  42544. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  42545. }
  42546. if (defines["SHADOWPOISSON" + lightIndex]) {
  42547. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  42548. }
  42549. if (defines["SHADOWESM" + lightIndex]) {
  42550. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  42551. }
  42552. }
  42553. }
  42554. return lightFallbackRank++;
  42555. };
  42556. /**
  42557. * Prepares the list of attributes required for morph targets according to the effect defines.
  42558. * @param attribs The current list of supported attribs
  42559. * @param mesh The mesh to prepare the morph targets attributes for
  42560. * @param defines The current Defines of the effect
  42561. */
  42562. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  42563. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  42564. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  42565. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  42566. var manager = mesh.morphTargetManager;
  42567. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  42568. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  42569. for (var index = 0; index < influencers; index++) {
  42570. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  42571. if (normal) {
  42572. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  42573. }
  42574. if (tangent) {
  42575. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  42576. }
  42577. if (attribs.length > maxAttributesCount) {
  42578. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  42579. }
  42580. }
  42581. }
  42582. };
  42583. /**
  42584. * Prepares the list of attributes required for bones according to the effect defines.
  42585. * @param attribs The current list of supported attribs
  42586. * @param mesh The mesh to prepare the bones attributes for
  42587. * @param defines The current Defines of the effect
  42588. * @param fallbacks The current efffect fallback strategy
  42589. */
  42590. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  42591. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  42592. fallbacks.addCPUSkinningFallback(0, mesh);
  42593. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  42594. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  42595. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  42596. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  42597. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  42598. }
  42599. }
  42600. };
  42601. /**
  42602. * Prepares the list of attributes required for instances according to the effect defines.
  42603. * @param attribs The current list of supported attribs
  42604. * @param defines The current Defines of the effect
  42605. */
  42606. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  42607. if (defines["INSTANCES"]) {
  42608. attribs.push("world0");
  42609. attribs.push("world1");
  42610. attribs.push("world2");
  42611. attribs.push("world3");
  42612. }
  42613. };
  42614. /**
  42615. * Binds the light shadow information to the effect for the given mesh.
  42616. * @param light The light containing the generator
  42617. * @param scene The scene the lights belongs to
  42618. * @param mesh The mesh we are binding the information to render
  42619. * @param lightIndex The light index in the effect used to render the mesh
  42620. * @param effect The effect we are binding the data to
  42621. */
  42622. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  42623. if (light.shadowEnabled && mesh.receiveShadows) {
  42624. var shadowGenerator = light.getShadowGenerator();
  42625. if (shadowGenerator) {
  42626. shadowGenerator.bindShadowLight(lightIndex, effect);
  42627. }
  42628. }
  42629. };
  42630. /**
  42631. * Binds the light information to the effect.
  42632. * @param light The light containing the generator
  42633. * @param effect The effect we are binding the data to
  42634. * @param lightIndex The light index in the effect used to render
  42635. */
  42636. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  42637. light.transferToEffect(effect, lightIndex + "");
  42638. };
  42639. /**
  42640. * Binds the lights information from the scene to the effect for the given mesh.
  42641. * @param scene The scene the lights belongs to
  42642. * @param mesh The mesh we are binding the information to render
  42643. * @param effect The effect we are binding the data to
  42644. * @param defines The generated defines for the effect
  42645. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  42646. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  42647. */
  42648. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  42649. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42650. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  42651. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  42652. for (var i = 0; i < len; i++) {
  42653. var light = mesh._lightSources[i];
  42654. var iAsString = i.toString();
  42655. var scaledIntensity = light.getScaledIntensity();
  42656. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  42657. MaterialHelper.BindLightProperties(light, effect, i);
  42658. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  42659. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  42660. if (defines["SPECULARTERM"]) {
  42661. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  42662. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  42663. }
  42664. // Shadows
  42665. if (scene.shadowsEnabled) {
  42666. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  42667. }
  42668. light._uniformBuffer.update();
  42669. }
  42670. };
  42671. /**
  42672. * Binds the fog information from the scene to the effect for the given mesh.
  42673. * @param scene The scene the lights belongs to
  42674. * @param mesh The mesh we are binding the information to render
  42675. * @param effect The effect we are binding the data to
  42676. * @param linearSpace Defines if the fog effect is applied in linear space
  42677. */
  42678. MaterialHelper.BindFogParameters = function (scene, mesh, effect, linearSpace) {
  42679. if (linearSpace === void 0) { linearSpace = false; }
  42680. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  42681. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  42682. // Convert fog color to linear space if used in a linear space computed shader.
  42683. if (linearSpace) {
  42684. scene.fogColor.toLinearSpaceToRef(this._tempFogColor);
  42685. effect.setColor3("vFogColor", this._tempFogColor);
  42686. }
  42687. else {
  42688. effect.setColor3("vFogColor", scene.fogColor);
  42689. }
  42690. }
  42691. };
  42692. /**
  42693. * Binds the bones information from the mesh to the effect.
  42694. * @param mesh The mesh we are binding the information to render
  42695. * @param effect The effect we are binding the data to
  42696. */
  42697. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  42698. if (!effect || !mesh) {
  42699. return;
  42700. }
  42701. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  42702. mesh.computeBonesUsingShaders = false;
  42703. }
  42704. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42705. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  42706. if (matrices) {
  42707. effect.setMatrices("mBones", matrices);
  42708. }
  42709. }
  42710. };
  42711. /**
  42712. * Binds the morph targets information from the mesh to the effect.
  42713. * @param abstractMesh The mesh we are binding the information to render
  42714. * @param effect The effect we are binding the data to
  42715. */
  42716. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  42717. var manager = abstractMesh.morphTargetManager;
  42718. if (!abstractMesh || !manager) {
  42719. return;
  42720. }
  42721. effect.setFloatArray("morphTargetInfluences", manager.influences);
  42722. };
  42723. /**
  42724. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  42725. * @param defines The generated defines used in the effect
  42726. * @param effect The effect we are binding the data to
  42727. * @param scene The scene we are willing to render with logarithmic scale for
  42728. */
  42729. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  42730. if (defines["LOGARITHMICDEPTH"]) {
  42731. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  42732. }
  42733. };
  42734. /**
  42735. * Binds the clip plane information from the scene to the effect.
  42736. * @param scene The scene the clip plane information are extracted from
  42737. * @param effect The effect we are binding the data to
  42738. */
  42739. MaterialHelper.BindClipPlane = function (effect, scene) {
  42740. if (scene.clipPlane) {
  42741. var clipPlane = scene.clipPlane;
  42742. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  42743. }
  42744. if (scene.clipPlane2) {
  42745. var clipPlane = scene.clipPlane2;
  42746. effect.setFloat4("vClipPlane2", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  42747. }
  42748. if (scene.clipPlane3) {
  42749. var clipPlane = scene.clipPlane3;
  42750. effect.setFloat4("vClipPlane3", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  42751. }
  42752. if (scene.clipPlane4) {
  42753. var clipPlane = scene.clipPlane4;
  42754. effect.setFloat4("vClipPlane4", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  42755. }
  42756. };
  42757. MaterialHelper._tempFogColor = BABYLON.Color3.Black();
  42758. return MaterialHelper;
  42759. }());
  42760. BABYLON.MaterialHelper = MaterialHelper;
  42761. })(BABYLON || (BABYLON = {}));
  42762. //# sourceMappingURL=babylon.materialHelper.js.map
  42763. var BABYLON;
  42764. (function (BABYLON) {
  42765. /**
  42766. * Base class of materials working in push mode in babylon JS
  42767. * @hidden
  42768. */
  42769. var PushMaterial = /** @class */ (function (_super) {
  42770. __extends(PushMaterial, _super);
  42771. function PushMaterial(name, scene) {
  42772. var _this = _super.call(this, name, scene) || this;
  42773. _this._normalMatrix = new BABYLON.Matrix();
  42774. _this.storeEffectOnSubMeshes = true;
  42775. return _this;
  42776. }
  42777. PushMaterial.prototype.getEffect = function () {
  42778. return this._activeEffect;
  42779. };
  42780. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  42781. if (!mesh) {
  42782. return false;
  42783. }
  42784. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  42785. return true;
  42786. }
  42787. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  42788. };
  42789. /**
  42790. * Binds the given world matrix to the active effect
  42791. *
  42792. * @param world the matrix to bind
  42793. */
  42794. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  42795. this._activeEffect.setMatrix("world", world);
  42796. };
  42797. /**
  42798. * Binds the given normal matrix to the active effect
  42799. *
  42800. * @param normalMatrix the matrix to bind
  42801. */
  42802. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  42803. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  42804. };
  42805. PushMaterial.prototype.bind = function (world, mesh) {
  42806. if (!mesh) {
  42807. return;
  42808. }
  42809. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  42810. };
  42811. PushMaterial.prototype._afterBind = function (mesh, effect) {
  42812. if (effect === void 0) { effect = null; }
  42813. _super.prototype._afterBind.call(this, mesh);
  42814. this.getScene()._cachedEffect = effect;
  42815. };
  42816. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  42817. if (visibility === void 0) { visibility = 1; }
  42818. return scene.isCachedMaterialInvalid(this, effect, visibility);
  42819. };
  42820. return PushMaterial;
  42821. }(BABYLON.Material));
  42822. BABYLON.PushMaterial = PushMaterial;
  42823. })(BABYLON || (BABYLON = {}));
  42824. //# sourceMappingURL=babylon.pushMaterial.js.map
  42825. var BABYLON;
  42826. (function (BABYLON) {
  42827. /** @hidden */
  42828. var StandardMaterialDefines = /** @class */ (function (_super) {
  42829. __extends(StandardMaterialDefines, _super);
  42830. function StandardMaterialDefines() {
  42831. var _this = _super.call(this) || this;
  42832. _this.MAINUV1 = false;
  42833. _this.MAINUV2 = false;
  42834. _this.DIFFUSE = false;
  42835. _this.DIFFUSEDIRECTUV = 0;
  42836. _this.AMBIENT = false;
  42837. _this.AMBIENTDIRECTUV = 0;
  42838. _this.OPACITY = false;
  42839. _this.OPACITYDIRECTUV = 0;
  42840. _this.OPACITYRGB = false;
  42841. _this.REFLECTION = false;
  42842. _this.EMISSIVE = false;
  42843. _this.EMISSIVEDIRECTUV = 0;
  42844. _this.SPECULAR = false;
  42845. _this.SPECULARDIRECTUV = 0;
  42846. _this.BUMP = false;
  42847. _this.BUMPDIRECTUV = 0;
  42848. _this.PARALLAX = false;
  42849. _this.PARALLAXOCCLUSION = false;
  42850. _this.SPECULAROVERALPHA = false;
  42851. _this.CLIPPLANE = false;
  42852. _this.CLIPPLANE2 = false;
  42853. _this.CLIPPLANE3 = false;
  42854. _this.CLIPPLANE4 = false;
  42855. _this.ALPHATEST = false;
  42856. _this.DEPTHPREPASS = false;
  42857. _this.ALPHAFROMDIFFUSE = false;
  42858. _this.POINTSIZE = false;
  42859. _this.FOG = false;
  42860. _this.SPECULARTERM = false;
  42861. _this.DIFFUSEFRESNEL = false;
  42862. _this.OPACITYFRESNEL = false;
  42863. _this.REFLECTIONFRESNEL = false;
  42864. _this.REFRACTIONFRESNEL = false;
  42865. _this.EMISSIVEFRESNEL = false;
  42866. _this.FRESNEL = false;
  42867. _this.NORMAL = false;
  42868. _this.UV1 = false;
  42869. _this.UV2 = false;
  42870. _this.VERTEXCOLOR = false;
  42871. _this.VERTEXALPHA = false;
  42872. _this.NUM_BONE_INFLUENCERS = 0;
  42873. _this.BonesPerMesh = 0;
  42874. _this.INSTANCES = false;
  42875. _this.GLOSSINESS = false;
  42876. _this.ROUGHNESS = false;
  42877. _this.EMISSIVEASILLUMINATION = false;
  42878. _this.LINKEMISSIVEWITHDIFFUSE = false;
  42879. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  42880. _this.LIGHTMAP = false;
  42881. _this.LIGHTMAPDIRECTUV = 0;
  42882. _this.OBJECTSPACE_NORMALMAP = false;
  42883. _this.USELIGHTMAPASSHADOWMAP = false;
  42884. _this.REFLECTIONMAP_3D = false;
  42885. _this.REFLECTIONMAP_SPHERICAL = false;
  42886. _this.REFLECTIONMAP_PLANAR = false;
  42887. _this.REFLECTIONMAP_CUBIC = false;
  42888. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  42889. _this.REFLECTIONMAP_PROJECTION = false;
  42890. _this.REFLECTIONMAP_SKYBOX = false;
  42891. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  42892. _this.REFLECTIONMAP_EXPLICIT = false;
  42893. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  42894. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  42895. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  42896. _this.INVERTCUBICMAP = false;
  42897. _this.LOGARITHMICDEPTH = false;
  42898. _this.REFRACTION = false;
  42899. _this.REFRACTIONMAP_3D = false;
  42900. _this.REFLECTIONOVERALPHA = false;
  42901. _this.TWOSIDEDLIGHTING = false;
  42902. _this.SHADOWFLOAT = false;
  42903. _this.MORPHTARGETS = false;
  42904. _this.MORPHTARGETS_NORMAL = false;
  42905. _this.MORPHTARGETS_TANGENT = false;
  42906. _this.NUM_MORPH_INFLUENCERS = 0;
  42907. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  42908. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  42909. _this.IMAGEPROCESSING = false;
  42910. _this.VIGNETTE = false;
  42911. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  42912. _this.VIGNETTEBLENDMODEOPAQUE = false;
  42913. _this.TONEMAPPING = false;
  42914. _this.TONEMAPPING_ACES = false;
  42915. _this.CONTRAST = false;
  42916. _this.COLORCURVES = false;
  42917. _this.COLORGRADING = false;
  42918. _this.COLORGRADING3D = false;
  42919. _this.SAMPLER3DGREENDEPTH = false;
  42920. _this.SAMPLER3DBGRMAP = false;
  42921. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  42922. /**
  42923. * If the reflection texture on this material is in linear color space
  42924. * @hidden
  42925. */
  42926. _this.IS_REFLECTION_LINEAR = false;
  42927. /**
  42928. * If the refraction texture on this material is in linear color space
  42929. * @hidden
  42930. */
  42931. _this.IS_REFRACTION_LINEAR = false;
  42932. _this.EXPOSURE = false;
  42933. _this.rebuild();
  42934. return _this;
  42935. }
  42936. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  42937. var modes = [
  42938. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  42939. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  42940. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  42941. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  42942. ];
  42943. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  42944. var mode = modes_1[_i];
  42945. this[mode] = (mode === modeToEnable);
  42946. }
  42947. };
  42948. return StandardMaterialDefines;
  42949. }(BABYLON.MaterialDefines));
  42950. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  42951. /**
  42952. * This is the default material used in Babylon. It is the best trade off between quality
  42953. * and performances.
  42954. * @see http://doc.babylonjs.com/babylon101/materials
  42955. */
  42956. var StandardMaterial = /** @class */ (function (_super) {
  42957. __extends(StandardMaterial, _super);
  42958. /**
  42959. * Instantiates a new standard material.
  42960. * This is the default material used in Babylon. It is the best trade off between quality
  42961. * and performances.
  42962. * @see http://doc.babylonjs.com/babylon101/materials
  42963. * @param name Define the name of the material in the scene
  42964. * @param scene Define the scene the material belong to
  42965. */
  42966. function StandardMaterial(name, scene) {
  42967. var _this = _super.call(this, name, scene) || this;
  42968. /**
  42969. * The color of the material lit by the environmental background lighting.
  42970. * @see http://doc.babylonjs.com/babylon101/materials#ambient-color-example
  42971. */
  42972. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  42973. /**
  42974. * The basic color of the material as viewed under a light.
  42975. */
  42976. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  42977. /**
  42978. * Define how the color and intensity of the highlight given by the light in the material.
  42979. */
  42980. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  42981. /**
  42982. * Define the color of the material as if self lit.
  42983. * This will be mixed in the final result even in the absence of light.
  42984. */
  42985. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42986. /**
  42987. * Defines how sharp are the highlights in the material.
  42988. * The bigger the value the sharper giving a more glossy feeling to the result.
  42989. * Reversely, the smaller the value the blurrier giving a more rough feeling to the result.
  42990. */
  42991. _this.specularPower = 64;
  42992. _this._useAlphaFromDiffuseTexture = false;
  42993. _this._useEmissiveAsIllumination = false;
  42994. _this._linkEmissiveWithDiffuse = false;
  42995. _this._useSpecularOverAlpha = false;
  42996. _this._useReflectionOverAlpha = false;
  42997. _this._disableLighting = false;
  42998. _this._useObjectSpaceNormalMap = false;
  42999. _this._useParallax = false;
  43000. _this._useParallaxOcclusion = false;
  43001. /**
  43002. * Apply a scaling factor that determine which "depth" the height map should reprensent. A value between 0.05 and 0.1 is reasonnable in Parallax, you can reach 0.2 using Parallax Occlusion.
  43003. */
  43004. _this.parallaxScaleBias = 0.05;
  43005. _this._roughness = 0;
  43006. /**
  43007. * In case of refraction, define the value of the indice of refraction.
  43008. * @see http://doc.babylonjs.com/how_to/reflect#how-to-obtain-reflections-and-refractions
  43009. */
  43010. _this.indexOfRefraction = 0.98;
  43011. /**
  43012. * Invert the refraction texture alongside the y axis.
  43013. * It can be usefull with procedural textures or probe for instance.
  43014. * @see http://doc.babylonjs.com/how_to/reflect#how-to-obtain-reflections-and-refractions
  43015. */
  43016. _this.invertRefractionY = true;
  43017. /**
  43018. * Defines the alpha limits in alpha test mode.
  43019. */
  43020. _this.alphaCutOff = 0.4;
  43021. _this._useLightmapAsShadowmap = false;
  43022. _this._useReflectionFresnelFromSpecular = false;
  43023. _this._useGlossinessFromSpecularMapAlpha = false;
  43024. _this._maxSimultaneousLights = 4;
  43025. _this._invertNormalMapX = false;
  43026. _this._invertNormalMapY = false;
  43027. _this._twoSidedLighting = false;
  43028. _this._renderTargets = new BABYLON.SmartArray(16);
  43029. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  43030. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43031. // Setup the default processing configuration to the scene.
  43032. _this._attachImageProcessingConfiguration(null);
  43033. _this.getRenderTargetTextures = function () {
  43034. _this._renderTargets.reset();
  43035. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43036. _this._renderTargets.push(_this._reflectionTexture);
  43037. }
  43038. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43039. _this._renderTargets.push(_this._refractionTexture);
  43040. }
  43041. return _this._renderTargets;
  43042. };
  43043. return _this;
  43044. }
  43045. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  43046. /**
  43047. * Gets the image processing configuration used either in this material.
  43048. */
  43049. get: function () {
  43050. return this._imageProcessingConfiguration;
  43051. },
  43052. /**
  43053. * Sets the Default image processing configuration used either in the this material.
  43054. *
  43055. * If sets to null, the scene one is in use.
  43056. */
  43057. set: function (value) {
  43058. this._attachImageProcessingConfiguration(value);
  43059. // Ensure the effect will be rebuilt.
  43060. this._markAllSubMeshesAsTexturesDirty();
  43061. },
  43062. enumerable: true,
  43063. configurable: true
  43064. });
  43065. /**
  43066. * Attaches a new image processing configuration to the Standard Material.
  43067. * @param configuration
  43068. */
  43069. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43070. var _this = this;
  43071. if (configuration === this._imageProcessingConfiguration) {
  43072. return;
  43073. }
  43074. // Detaches observer.
  43075. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43076. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43077. }
  43078. // Pick the scene configuration if needed.
  43079. if (!configuration) {
  43080. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43081. }
  43082. else {
  43083. this._imageProcessingConfiguration = configuration;
  43084. }
  43085. // Attaches observer.
  43086. if (this._imageProcessingConfiguration) {
  43087. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43088. _this._markAllSubMeshesAsImageProcessingDirty();
  43089. });
  43090. }
  43091. };
  43092. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  43093. /**
  43094. * Gets wether the color curves effect is enabled.
  43095. */
  43096. get: function () {
  43097. return this.imageProcessingConfiguration.colorCurvesEnabled;
  43098. },
  43099. /**
  43100. * Sets wether the color curves effect is enabled.
  43101. */
  43102. set: function (value) {
  43103. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  43104. },
  43105. enumerable: true,
  43106. configurable: true
  43107. });
  43108. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  43109. /**
  43110. * Gets wether the color grading effect is enabled.
  43111. */
  43112. get: function () {
  43113. return this.imageProcessingConfiguration.colorGradingEnabled;
  43114. },
  43115. /**
  43116. * Gets wether the color grading effect is enabled.
  43117. */
  43118. set: function (value) {
  43119. this.imageProcessingConfiguration.colorGradingEnabled = value;
  43120. },
  43121. enumerable: true,
  43122. configurable: true
  43123. });
  43124. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  43125. /**
  43126. * Gets wether tonemapping is enabled or not.
  43127. */
  43128. get: function () {
  43129. return this._imageProcessingConfiguration.toneMappingEnabled;
  43130. },
  43131. /**
  43132. * Sets wether tonemapping is enabled or not
  43133. */
  43134. set: function (value) {
  43135. this._imageProcessingConfiguration.toneMappingEnabled = value;
  43136. },
  43137. enumerable: true,
  43138. configurable: true
  43139. });
  43140. ;
  43141. ;
  43142. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  43143. /**
  43144. * The camera exposure used on this material.
  43145. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  43146. * This corresponds to a photographic exposure.
  43147. */
  43148. get: function () {
  43149. return this._imageProcessingConfiguration.exposure;
  43150. },
  43151. /**
  43152. * The camera exposure used on this material.
  43153. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  43154. * This corresponds to a photographic exposure.
  43155. */
  43156. set: function (value) {
  43157. this._imageProcessingConfiguration.exposure = value;
  43158. },
  43159. enumerable: true,
  43160. configurable: true
  43161. });
  43162. ;
  43163. ;
  43164. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  43165. /**
  43166. * Gets The camera contrast used on this material.
  43167. */
  43168. get: function () {
  43169. return this._imageProcessingConfiguration.contrast;
  43170. },
  43171. /**
  43172. * Sets The camera contrast used on this material.
  43173. */
  43174. set: function (value) {
  43175. this._imageProcessingConfiguration.contrast = value;
  43176. },
  43177. enumerable: true,
  43178. configurable: true
  43179. });
  43180. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  43181. /**
  43182. * Gets the Color Grading 2D Lookup Texture.
  43183. */
  43184. get: function () {
  43185. return this._imageProcessingConfiguration.colorGradingTexture;
  43186. },
  43187. /**
  43188. * Sets the Color Grading 2D Lookup Texture.
  43189. */
  43190. set: function (value) {
  43191. this._imageProcessingConfiguration.colorGradingTexture = value;
  43192. },
  43193. enumerable: true,
  43194. configurable: true
  43195. });
  43196. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  43197. /**
  43198. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  43199. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  43200. * 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;
  43201. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  43202. */
  43203. get: function () {
  43204. return this._imageProcessingConfiguration.colorCurves;
  43205. },
  43206. /**
  43207. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  43208. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  43209. * 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;
  43210. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  43211. */
  43212. set: function (value) {
  43213. this._imageProcessingConfiguration.colorCurves = value;
  43214. },
  43215. enumerable: true,
  43216. configurable: true
  43217. });
  43218. Object.defineProperty(StandardMaterial.prototype, "hasRenderTargetTextures", {
  43219. /**
  43220. * Gets a boolean indicating that current material needs to register RTT
  43221. */
  43222. get: function () {
  43223. if (StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  43224. return true;
  43225. }
  43226. if (StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
  43227. return true;
  43228. }
  43229. return false;
  43230. },
  43231. enumerable: true,
  43232. configurable: true
  43233. });
  43234. /**
  43235. * Gets the current class name of the material e.g. "StandardMaterial"
  43236. * Mainly use in serialization.
  43237. * @returns the class name
  43238. */
  43239. StandardMaterial.prototype.getClassName = function () {
  43240. return "StandardMaterial";
  43241. };
  43242. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  43243. /**
  43244. * In case the depth buffer does not allow enough depth precision for your scene (might be the case in large scenes)
  43245. * You can try switching to logarithmic depth.
  43246. * @see http://doc.babylonjs.com/how_to/using_logarithmic_depth_buffer
  43247. */
  43248. get: function () {
  43249. return this._useLogarithmicDepth;
  43250. },
  43251. set: function (value) {
  43252. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43253. this._markAllSubMeshesAsMiscDirty();
  43254. },
  43255. enumerable: true,
  43256. configurable: true
  43257. });
  43258. /**
  43259. * Specifies if the material will require alpha blending
  43260. * @returns a boolean specifying if alpha blending is needed
  43261. */
  43262. StandardMaterial.prototype.needAlphaBlending = function () {
  43263. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  43264. };
  43265. /**
  43266. * Specifies if this material should be rendered in alpha test mode
  43267. * @returns a boolean specifying if an alpha test is needed.
  43268. */
  43269. StandardMaterial.prototype.needAlphaTesting = function () {
  43270. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  43271. };
  43272. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  43273. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  43274. };
  43275. /**
  43276. * Get the texture used for alpha test purpose.
  43277. * @returns the diffuse texture in case of the standard material.
  43278. */
  43279. StandardMaterial.prototype.getAlphaTestTexture = function () {
  43280. return this._diffuseTexture;
  43281. };
  43282. /**
  43283. * Get if the submesh is ready to be used and all its information available.
  43284. * Child classes can use it to update shaders
  43285. * @param mesh defines the mesh to check
  43286. * @param subMesh defines which submesh to check
  43287. * @param useInstances specifies that instances should be used
  43288. * @returns a boolean indicating that the submesh is ready or not
  43289. */
  43290. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43291. if (useInstances === void 0) { useInstances = false; }
  43292. if (subMesh.effect && this.isFrozen) {
  43293. if (this._wasPreviouslyReady) {
  43294. return true;
  43295. }
  43296. }
  43297. if (!subMesh._materialDefines) {
  43298. subMesh._materialDefines = new StandardMaterialDefines();
  43299. }
  43300. var scene = this.getScene();
  43301. var defines = subMesh._materialDefines;
  43302. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43303. if (defines._renderId === scene.getRenderId()) {
  43304. return true;
  43305. }
  43306. }
  43307. var engine = scene.getEngine();
  43308. // Lights
  43309. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  43310. // Textures
  43311. if (defines._areTexturesDirty) {
  43312. defines._needUVs = false;
  43313. defines.MAINUV1 = false;
  43314. defines.MAINUV2 = false;
  43315. if (scene.texturesEnabled) {
  43316. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43317. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  43318. return false;
  43319. }
  43320. else {
  43321. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  43322. }
  43323. }
  43324. else {
  43325. defines.DIFFUSE = false;
  43326. }
  43327. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43328. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43329. return false;
  43330. }
  43331. else {
  43332. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  43333. }
  43334. }
  43335. else {
  43336. defines.AMBIENT = false;
  43337. }
  43338. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43339. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43340. return false;
  43341. }
  43342. else {
  43343. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  43344. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  43345. }
  43346. }
  43347. else {
  43348. defines.OPACITY = false;
  43349. }
  43350. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43351. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  43352. return false;
  43353. }
  43354. else {
  43355. defines._needNormals = true;
  43356. defines.REFLECTION = true;
  43357. defines.ROUGHNESS = (this._roughness > 0);
  43358. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  43359. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  43360. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  43361. switch (this._reflectionTexture.coordinatesMode) {
  43362. case BABYLON.Texture.EXPLICIT_MODE:
  43363. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  43364. break;
  43365. case BABYLON.Texture.PLANAR_MODE:
  43366. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  43367. break;
  43368. case BABYLON.Texture.PROJECTION_MODE:
  43369. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  43370. break;
  43371. case BABYLON.Texture.SKYBOX_MODE:
  43372. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  43373. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !this._reflectionTexture.getReflectionTextureMatrix().isIdentity();
  43374. break;
  43375. case BABYLON.Texture.SPHERICAL_MODE:
  43376. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  43377. break;
  43378. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  43379. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  43380. break;
  43381. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  43382. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  43383. break;
  43384. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  43385. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  43386. break;
  43387. case BABYLON.Texture.CUBIC_MODE:
  43388. case BABYLON.Texture.INVCUBIC_MODE:
  43389. default:
  43390. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  43391. break;
  43392. }
  43393. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  43394. }
  43395. }
  43396. else {
  43397. defines.REFLECTION = false;
  43398. }
  43399. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43400. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43401. return false;
  43402. }
  43403. else {
  43404. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  43405. }
  43406. }
  43407. else {
  43408. defines.EMISSIVE = false;
  43409. }
  43410. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43411. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43412. return false;
  43413. }
  43414. else {
  43415. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  43416. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  43417. }
  43418. }
  43419. else {
  43420. defines.LIGHTMAP = false;
  43421. }
  43422. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43423. if (!this._specularTexture.isReadyOrNotBlocking()) {
  43424. return false;
  43425. }
  43426. else {
  43427. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  43428. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  43429. }
  43430. }
  43431. else {
  43432. defines.SPECULAR = false;
  43433. }
  43434. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  43435. // Bump texure can not be not blocking.
  43436. if (!this._bumpTexture.isReady()) {
  43437. return false;
  43438. }
  43439. else {
  43440. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  43441. defines.PARALLAX = this._useParallax;
  43442. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  43443. }
  43444. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  43445. }
  43446. else {
  43447. defines.BUMP = false;
  43448. }
  43449. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43450. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  43451. return false;
  43452. }
  43453. else {
  43454. defines._needUVs = true;
  43455. defines.REFRACTION = true;
  43456. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  43457. }
  43458. }
  43459. else {
  43460. defines.REFRACTION = false;
  43461. }
  43462. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  43463. }
  43464. else {
  43465. defines.DIFFUSE = false;
  43466. defines.AMBIENT = false;
  43467. defines.OPACITY = false;
  43468. defines.REFLECTION = false;
  43469. defines.EMISSIVE = false;
  43470. defines.LIGHTMAP = false;
  43471. defines.BUMP = false;
  43472. defines.REFRACTION = false;
  43473. }
  43474. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  43475. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  43476. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  43477. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  43478. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  43479. }
  43480. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  43481. if (!this._imageProcessingConfiguration.isReady()) {
  43482. return false;
  43483. }
  43484. this._imageProcessingConfiguration.prepareDefines(defines);
  43485. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  43486. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  43487. }
  43488. if (defines._areFresnelDirty) {
  43489. if (StandardMaterial.FresnelEnabled) {
  43490. // Fresnel
  43491. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  43492. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  43493. this._reflectionFresnelParameters) {
  43494. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  43495. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  43496. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  43497. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  43498. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  43499. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  43500. defines._needNormals = true;
  43501. defines.FRESNEL = true;
  43502. }
  43503. }
  43504. else {
  43505. defines.FRESNEL = false;
  43506. }
  43507. }
  43508. // Misc.
  43509. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  43510. // Attribs
  43511. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  43512. // Values that need to be evaluated on every frame
  43513. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  43514. // Get correct effect
  43515. if (defines.isDirty) {
  43516. defines.markAsProcessed();
  43517. scene.resetCachedMaterial();
  43518. // Fallbacks
  43519. var fallbacks = new BABYLON.EffectFallbacks();
  43520. if (defines.REFLECTION) {
  43521. fallbacks.addFallback(0, "REFLECTION");
  43522. }
  43523. if (defines.SPECULAR) {
  43524. fallbacks.addFallback(0, "SPECULAR");
  43525. }
  43526. if (defines.BUMP) {
  43527. fallbacks.addFallback(0, "BUMP");
  43528. }
  43529. if (defines.PARALLAX) {
  43530. fallbacks.addFallback(1, "PARALLAX");
  43531. }
  43532. if (defines.PARALLAXOCCLUSION) {
  43533. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  43534. }
  43535. if (defines.SPECULAROVERALPHA) {
  43536. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  43537. }
  43538. if (defines.FOG) {
  43539. fallbacks.addFallback(1, "FOG");
  43540. }
  43541. if (defines.POINTSIZE) {
  43542. fallbacks.addFallback(0, "POINTSIZE");
  43543. }
  43544. if (defines.LOGARITHMICDEPTH) {
  43545. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  43546. }
  43547. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  43548. if (defines.SPECULARTERM) {
  43549. fallbacks.addFallback(0, "SPECULARTERM");
  43550. }
  43551. if (defines.DIFFUSEFRESNEL) {
  43552. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  43553. }
  43554. if (defines.OPACITYFRESNEL) {
  43555. fallbacks.addFallback(2, "OPACITYFRESNEL");
  43556. }
  43557. if (defines.REFLECTIONFRESNEL) {
  43558. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  43559. }
  43560. if (defines.EMISSIVEFRESNEL) {
  43561. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  43562. }
  43563. if (defines.FRESNEL) {
  43564. fallbacks.addFallback(4, "FRESNEL");
  43565. }
  43566. //Attributes
  43567. var attribs = [BABYLON.VertexBuffer.PositionKind];
  43568. if (defines.NORMAL) {
  43569. attribs.push(BABYLON.VertexBuffer.NormalKind);
  43570. }
  43571. if (defines.UV1) {
  43572. attribs.push(BABYLON.VertexBuffer.UVKind);
  43573. }
  43574. if (defines.UV2) {
  43575. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43576. }
  43577. if (defines.VERTEXCOLOR) {
  43578. attribs.push(BABYLON.VertexBuffer.ColorKind);
  43579. }
  43580. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  43581. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  43582. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  43583. var shaderName = "default";
  43584. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  43585. "vFogInfos", "vFogColor", "pointSize",
  43586. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  43587. "mBones",
  43588. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  43589. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  43590. "vReflectionPosition", "vReflectionSize",
  43591. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  43592. ];
  43593. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  43594. var uniformBuffers = ["Material", "Scene"];
  43595. if (BABYLON.ImageProcessingConfiguration) {
  43596. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  43597. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  43598. }
  43599. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  43600. uniformsNames: uniforms,
  43601. uniformBuffersNames: uniformBuffers,
  43602. samplers: samplers,
  43603. defines: defines,
  43604. maxSimultaneousLights: this._maxSimultaneousLights
  43605. });
  43606. if (this.customShaderNameResolve) {
  43607. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  43608. }
  43609. var join = defines.toString();
  43610. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  43611. attributes: attribs,
  43612. uniformsNames: uniforms,
  43613. uniformBuffersNames: uniformBuffers,
  43614. samplers: samplers,
  43615. defines: join,
  43616. fallbacks: fallbacks,
  43617. onCompiled: this.onCompiled,
  43618. onError: this.onError,
  43619. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  43620. }, engine), defines);
  43621. this.buildUniformLayout();
  43622. }
  43623. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43624. return false;
  43625. }
  43626. defines._renderId = scene.getRenderId();
  43627. this._wasPreviouslyReady = true;
  43628. return true;
  43629. };
  43630. /**
  43631. * Builds the material UBO layouts.
  43632. * Used internally during the effect preparation.
  43633. */
  43634. StandardMaterial.prototype.buildUniformLayout = function () {
  43635. // Order is important !
  43636. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  43637. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  43638. this._uniformBuffer.addUniform("opacityParts", 4);
  43639. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  43640. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  43641. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  43642. this._uniformBuffer.addUniform("refractionRightColor", 4);
  43643. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  43644. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  43645. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  43646. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  43647. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  43648. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  43649. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  43650. this._uniformBuffer.addUniform("vReflectionSize", 3);
  43651. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  43652. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  43653. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  43654. this._uniformBuffer.addUniform("vBumpInfos", 3);
  43655. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  43656. this._uniformBuffer.addUniform("ambientMatrix", 16);
  43657. this._uniformBuffer.addUniform("opacityMatrix", 16);
  43658. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  43659. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  43660. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  43661. this._uniformBuffer.addUniform("specularMatrix", 16);
  43662. this._uniformBuffer.addUniform("bumpMatrix", 16);
  43663. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  43664. this._uniformBuffer.addUniform("refractionMatrix", 16);
  43665. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  43666. this._uniformBuffer.addUniform("vSpecularColor", 4);
  43667. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  43668. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  43669. this._uniformBuffer.addUniform("pointSize", 1);
  43670. this._uniformBuffer.create();
  43671. };
  43672. /**
  43673. * Unbinds the material from the mesh
  43674. */
  43675. StandardMaterial.prototype.unbind = function () {
  43676. if (this._activeEffect) {
  43677. var needFlag = false;
  43678. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  43679. this._activeEffect.setTexture("reflection2DSampler", null);
  43680. needFlag = true;
  43681. }
  43682. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  43683. this._activeEffect.setTexture("refraction2DSampler", null);
  43684. needFlag = true;
  43685. }
  43686. if (needFlag) {
  43687. this._markAllSubMeshesAsTexturesDirty();
  43688. }
  43689. }
  43690. _super.prototype.unbind.call(this);
  43691. };
  43692. /**
  43693. * Binds the submesh to this material by preparing the effect and shader to draw
  43694. * @param world defines the world transformation matrix
  43695. * @param mesh defines the mesh containing the submesh
  43696. * @param subMesh defines the submesh to bind the material to
  43697. */
  43698. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  43699. var scene = this.getScene();
  43700. var defines = subMesh._materialDefines;
  43701. if (!defines) {
  43702. return;
  43703. }
  43704. var effect = subMesh.effect;
  43705. if (!effect) {
  43706. return;
  43707. }
  43708. this._activeEffect = effect;
  43709. // Matrices
  43710. this.bindOnlyWorldMatrix(world);
  43711. // Normal Matrix
  43712. if (defines.OBJECTSPACE_NORMALMAP) {
  43713. world.toNormalMatrix(this._normalMatrix);
  43714. this.bindOnlyNormalMatrix(this._normalMatrix);
  43715. }
  43716. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  43717. // Bones
  43718. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  43719. if (mustRebind) {
  43720. this._uniformBuffer.bindToEffect(effect, "Material");
  43721. this.bindViewProjection(effect);
  43722. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  43723. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  43724. // Fresnel
  43725. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  43726. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  43727. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  43728. }
  43729. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  43730. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  43731. }
  43732. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  43733. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  43734. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  43735. }
  43736. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  43737. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  43738. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  43739. }
  43740. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  43741. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  43742. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  43743. }
  43744. }
  43745. // Textures
  43746. if (scene.texturesEnabled) {
  43747. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43748. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  43749. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  43750. if (this._diffuseTexture.hasAlpha) {
  43751. effect.setFloat("alphaCutOff", this.alphaCutOff);
  43752. }
  43753. }
  43754. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43755. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  43756. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  43757. }
  43758. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43759. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  43760. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  43761. }
  43762. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43763. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  43764. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  43765. if (this._reflectionTexture.boundingBoxSize) {
  43766. var cubeTexture = this._reflectionTexture;
  43767. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  43768. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  43769. }
  43770. }
  43771. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43772. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  43773. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  43774. }
  43775. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43776. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  43777. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  43778. }
  43779. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43780. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  43781. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  43782. }
  43783. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43784. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  43785. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  43786. if (scene._mirroredCameraPosition) {
  43787. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  43788. }
  43789. else {
  43790. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  43791. }
  43792. }
  43793. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43794. var depth = 1.0;
  43795. if (!this._refractionTexture.isCube) {
  43796. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  43797. if (this._refractionTexture.depth) {
  43798. depth = this._refractionTexture.depth;
  43799. }
  43800. }
  43801. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  43802. }
  43803. }
  43804. // Point size
  43805. if (this.pointsCloud) {
  43806. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  43807. }
  43808. if (defines.SPECULARTERM) {
  43809. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  43810. }
  43811. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  43812. // Diffuse
  43813. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  43814. }
  43815. // Textures
  43816. if (scene.texturesEnabled) {
  43817. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43818. effect.setTexture("diffuseSampler", this._diffuseTexture);
  43819. }
  43820. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43821. effect.setTexture("ambientSampler", this._ambientTexture);
  43822. }
  43823. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43824. effect.setTexture("opacitySampler", this._opacityTexture);
  43825. }
  43826. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43827. if (this._reflectionTexture.isCube) {
  43828. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  43829. }
  43830. else {
  43831. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  43832. }
  43833. }
  43834. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43835. effect.setTexture("emissiveSampler", this._emissiveTexture);
  43836. }
  43837. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43838. effect.setTexture("lightmapSampler", this._lightmapTexture);
  43839. }
  43840. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43841. effect.setTexture("specularSampler", this._specularTexture);
  43842. }
  43843. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43844. effect.setTexture("bumpSampler", this._bumpTexture);
  43845. }
  43846. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43847. var depth = 1.0;
  43848. if (this._refractionTexture.isCube) {
  43849. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  43850. }
  43851. else {
  43852. effect.setTexture("refraction2DSampler", this._refractionTexture);
  43853. }
  43854. }
  43855. }
  43856. // Clip plane
  43857. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  43858. // Colors
  43859. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  43860. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  43861. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  43862. }
  43863. if (mustRebind || !this.isFrozen) {
  43864. // Lights
  43865. if (scene.lightsEnabled && !this._disableLighting) {
  43866. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  43867. }
  43868. // View
  43869. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  43870. this.bindView(effect);
  43871. }
  43872. // Fog
  43873. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  43874. // Morph targets
  43875. if (defines.NUM_MORPH_INFLUENCERS) {
  43876. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  43877. }
  43878. // Log. depth
  43879. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  43880. // image processing
  43881. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  43882. this._imageProcessingConfiguration.bind(this._activeEffect);
  43883. }
  43884. }
  43885. this._uniformBuffer.update();
  43886. this._afterBind(mesh, this._activeEffect);
  43887. };
  43888. /**
  43889. * Get the list of animatables in the material.
  43890. * @returns the list of animatables object used in the material
  43891. */
  43892. StandardMaterial.prototype.getAnimatables = function () {
  43893. var results = [];
  43894. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  43895. results.push(this._diffuseTexture);
  43896. }
  43897. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  43898. results.push(this._ambientTexture);
  43899. }
  43900. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  43901. results.push(this._opacityTexture);
  43902. }
  43903. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  43904. results.push(this._reflectionTexture);
  43905. }
  43906. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  43907. results.push(this._emissiveTexture);
  43908. }
  43909. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  43910. results.push(this._specularTexture);
  43911. }
  43912. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  43913. results.push(this._bumpTexture);
  43914. }
  43915. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  43916. results.push(this._lightmapTexture);
  43917. }
  43918. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  43919. results.push(this._refractionTexture);
  43920. }
  43921. return results;
  43922. };
  43923. /**
  43924. * Gets the active textures from the material
  43925. * @returns an array of textures
  43926. */
  43927. StandardMaterial.prototype.getActiveTextures = function () {
  43928. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43929. if (this._diffuseTexture) {
  43930. activeTextures.push(this._diffuseTexture);
  43931. }
  43932. if (this._ambientTexture) {
  43933. activeTextures.push(this._ambientTexture);
  43934. }
  43935. if (this._opacityTexture) {
  43936. activeTextures.push(this._opacityTexture);
  43937. }
  43938. if (this._reflectionTexture) {
  43939. activeTextures.push(this._reflectionTexture);
  43940. }
  43941. if (this._emissiveTexture) {
  43942. activeTextures.push(this._emissiveTexture);
  43943. }
  43944. if (this._specularTexture) {
  43945. activeTextures.push(this._specularTexture);
  43946. }
  43947. if (this._bumpTexture) {
  43948. activeTextures.push(this._bumpTexture);
  43949. }
  43950. if (this._lightmapTexture) {
  43951. activeTextures.push(this._lightmapTexture);
  43952. }
  43953. if (this._refractionTexture) {
  43954. activeTextures.push(this._refractionTexture);
  43955. }
  43956. return activeTextures;
  43957. };
  43958. /**
  43959. * Specifies if the material uses a texture
  43960. * @param texture defines the texture to check against the material
  43961. * @returns a boolean specifying if the material uses the texture
  43962. */
  43963. StandardMaterial.prototype.hasTexture = function (texture) {
  43964. if (_super.prototype.hasTexture.call(this, texture)) {
  43965. return true;
  43966. }
  43967. if (this._diffuseTexture === texture) {
  43968. return true;
  43969. }
  43970. if (this._ambientTexture === texture) {
  43971. return true;
  43972. }
  43973. if (this._opacityTexture === texture) {
  43974. return true;
  43975. }
  43976. if (this._reflectionTexture === texture) {
  43977. return true;
  43978. }
  43979. if (this._emissiveTexture === texture) {
  43980. return true;
  43981. }
  43982. if (this._specularTexture === texture) {
  43983. return true;
  43984. }
  43985. if (this._bumpTexture === texture) {
  43986. return true;
  43987. }
  43988. if (this._lightmapTexture === texture) {
  43989. return true;
  43990. }
  43991. if (this._refractionTexture === texture) {
  43992. return true;
  43993. }
  43994. return false;
  43995. };
  43996. /**
  43997. * Disposes the material
  43998. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  43999. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  44000. */
  44001. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44002. if (forceDisposeTextures) {
  44003. if (this._diffuseTexture) {
  44004. this._diffuseTexture.dispose();
  44005. }
  44006. if (this._ambientTexture) {
  44007. this._ambientTexture.dispose();
  44008. }
  44009. if (this._opacityTexture) {
  44010. this._opacityTexture.dispose();
  44011. }
  44012. if (this._reflectionTexture) {
  44013. this._reflectionTexture.dispose();
  44014. }
  44015. if (this._emissiveTexture) {
  44016. this._emissiveTexture.dispose();
  44017. }
  44018. if (this._specularTexture) {
  44019. this._specularTexture.dispose();
  44020. }
  44021. if (this._bumpTexture) {
  44022. this._bumpTexture.dispose();
  44023. }
  44024. if (this._lightmapTexture) {
  44025. this._lightmapTexture.dispose();
  44026. }
  44027. if (this._refractionTexture) {
  44028. this._refractionTexture.dispose();
  44029. }
  44030. }
  44031. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44032. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44033. }
  44034. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44035. };
  44036. /**
  44037. * Makes a duplicate of the material, and gives it a new name
  44038. * @param name defines the new name for the duplicated material
  44039. * @returns the cloned material
  44040. */
  44041. StandardMaterial.prototype.clone = function (name) {
  44042. var _this = this;
  44043. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  44044. result.name = name;
  44045. result.id = name;
  44046. return result;
  44047. };
  44048. /**
  44049. * Serializes this material in a JSON representation
  44050. * @returns the serialized material object
  44051. */
  44052. StandardMaterial.prototype.serialize = function () {
  44053. return BABYLON.SerializationHelper.Serialize(this);
  44054. };
  44055. /**
  44056. * Creates a standard material from parsed material data
  44057. * @param source defines the JSON represnetation of the material
  44058. * @param scene defines the hosting scene
  44059. * @param rootUrl defines the root URL to use to load textures and relative dependencies
  44060. * @returns a new material
  44061. */
  44062. StandardMaterial.Parse = function (source, scene, rootUrl) {
  44063. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  44064. };
  44065. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  44066. /**
  44067. * Are diffuse textures enabled in the application.
  44068. */
  44069. get: function () {
  44070. return StandardMaterial._DiffuseTextureEnabled;
  44071. },
  44072. set: function (value) {
  44073. if (StandardMaterial._DiffuseTextureEnabled === value) {
  44074. return;
  44075. }
  44076. StandardMaterial._DiffuseTextureEnabled = value;
  44077. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44078. },
  44079. enumerable: true,
  44080. configurable: true
  44081. });
  44082. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  44083. /**
  44084. * Are ambient textures enabled in the application.
  44085. */
  44086. get: function () {
  44087. return StandardMaterial._AmbientTextureEnabled;
  44088. },
  44089. set: function (value) {
  44090. if (StandardMaterial._AmbientTextureEnabled === value) {
  44091. return;
  44092. }
  44093. StandardMaterial._AmbientTextureEnabled = value;
  44094. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44095. },
  44096. enumerable: true,
  44097. configurable: true
  44098. });
  44099. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  44100. /**
  44101. * Are opacity textures enabled in the application.
  44102. */
  44103. get: function () {
  44104. return StandardMaterial._OpacityTextureEnabled;
  44105. },
  44106. set: function (value) {
  44107. if (StandardMaterial._OpacityTextureEnabled === value) {
  44108. return;
  44109. }
  44110. StandardMaterial._OpacityTextureEnabled = value;
  44111. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44112. },
  44113. enumerable: true,
  44114. configurable: true
  44115. });
  44116. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  44117. /**
  44118. * Are reflection textures enabled in the application.
  44119. */
  44120. get: function () {
  44121. return StandardMaterial._ReflectionTextureEnabled;
  44122. },
  44123. set: function (value) {
  44124. if (StandardMaterial._ReflectionTextureEnabled === value) {
  44125. return;
  44126. }
  44127. StandardMaterial._ReflectionTextureEnabled = value;
  44128. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44129. },
  44130. enumerable: true,
  44131. configurable: true
  44132. });
  44133. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  44134. /**
  44135. * Are emissive textures enabled in the application.
  44136. */
  44137. get: function () {
  44138. return StandardMaterial._EmissiveTextureEnabled;
  44139. },
  44140. set: function (value) {
  44141. if (StandardMaterial._EmissiveTextureEnabled === value) {
  44142. return;
  44143. }
  44144. StandardMaterial._EmissiveTextureEnabled = value;
  44145. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44146. },
  44147. enumerable: true,
  44148. configurable: true
  44149. });
  44150. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  44151. /**
  44152. * Are specular textures enabled in the application.
  44153. */
  44154. get: function () {
  44155. return StandardMaterial._SpecularTextureEnabled;
  44156. },
  44157. set: function (value) {
  44158. if (StandardMaterial._SpecularTextureEnabled === value) {
  44159. return;
  44160. }
  44161. StandardMaterial._SpecularTextureEnabled = value;
  44162. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44163. },
  44164. enumerable: true,
  44165. configurable: true
  44166. });
  44167. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  44168. /**
  44169. * Are bump textures enabled in the application.
  44170. */
  44171. get: function () {
  44172. return StandardMaterial._BumpTextureEnabled;
  44173. },
  44174. set: function (value) {
  44175. if (StandardMaterial._BumpTextureEnabled === value) {
  44176. return;
  44177. }
  44178. StandardMaterial._BumpTextureEnabled = value;
  44179. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44180. },
  44181. enumerable: true,
  44182. configurable: true
  44183. });
  44184. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  44185. /**
  44186. * Are lightmap textures enabled in the application.
  44187. */
  44188. get: function () {
  44189. return StandardMaterial._LightmapTextureEnabled;
  44190. },
  44191. set: function (value) {
  44192. if (StandardMaterial._LightmapTextureEnabled === value) {
  44193. return;
  44194. }
  44195. StandardMaterial._LightmapTextureEnabled = value;
  44196. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44197. },
  44198. enumerable: true,
  44199. configurable: true
  44200. });
  44201. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  44202. /**
  44203. * Are refraction textures enabled in the application.
  44204. */
  44205. get: function () {
  44206. return StandardMaterial._RefractionTextureEnabled;
  44207. },
  44208. set: function (value) {
  44209. if (StandardMaterial._RefractionTextureEnabled === value) {
  44210. return;
  44211. }
  44212. StandardMaterial._RefractionTextureEnabled = value;
  44213. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44214. },
  44215. enumerable: true,
  44216. configurable: true
  44217. });
  44218. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  44219. /**
  44220. * Are color grading textures enabled in the application.
  44221. */
  44222. get: function () {
  44223. return StandardMaterial._ColorGradingTextureEnabled;
  44224. },
  44225. set: function (value) {
  44226. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  44227. return;
  44228. }
  44229. StandardMaterial._ColorGradingTextureEnabled = value;
  44230. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44231. },
  44232. enumerable: true,
  44233. configurable: true
  44234. });
  44235. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  44236. /**
  44237. * Are fresnels enabled in the application.
  44238. */
  44239. get: function () {
  44240. return StandardMaterial._FresnelEnabled;
  44241. },
  44242. set: function (value) {
  44243. if (StandardMaterial._FresnelEnabled === value) {
  44244. return;
  44245. }
  44246. StandardMaterial._FresnelEnabled = value;
  44247. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  44248. },
  44249. enumerable: true,
  44250. configurable: true
  44251. });
  44252. // Flags used to enable or disable a type of texture for all Standard Materials
  44253. StandardMaterial._DiffuseTextureEnabled = true;
  44254. StandardMaterial._AmbientTextureEnabled = true;
  44255. StandardMaterial._OpacityTextureEnabled = true;
  44256. StandardMaterial._ReflectionTextureEnabled = true;
  44257. StandardMaterial._EmissiveTextureEnabled = true;
  44258. StandardMaterial._SpecularTextureEnabled = true;
  44259. StandardMaterial._BumpTextureEnabled = true;
  44260. StandardMaterial._LightmapTextureEnabled = true;
  44261. StandardMaterial._RefractionTextureEnabled = true;
  44262. StandardMaterial._ColorGradingTextureEnabled = true;
  44263. StandardMaterial._FresnelEnabled = true;
  44264. __decorate([
  44265. BABYLON.serializeAsTexture("diffuseTexture")
  44266. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  44267. __decorate([
  44268. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  44269. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  44270. __decorate([
  44271. BABYLON.serializeAsTexture("ambientTexture")
  44272. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  44273. __decorate([
  44274. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44275. ], StandardMaterial.prototype, "ambientTexture", void 0);
  44276. __decorate([
  44277. BABYLON.serializeAsTexture("opacityTexture")
  44278. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  44279. __decorate([
  44280. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  44281. ], StandardMaterial.prototype, "opacityTexture", void 0);
  44282. __decorate([
  44283. BABYLON.serializeAsTexture("reflectionTexture")
  44284. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  44285. __decorate([
  44286. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44287. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  44288. __decorate([
  44289. BABYLON.serializeAsTexture("emissiveTexture")
  44290. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  44291. __decorate([
  44292. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44293. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  44294. __decorate([
  44295. BABYLON.serializeAsTexture("specularTexture")
  44296. ], StandardMaterial.prototype, "_specularTexture", void 0);
  44297. __decorate([
  44298. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44299. ], StandardMaterial.prototype, "specularTexture", void 0);
  44300. __decorate([
  44301. BABYLON.serializeAsTexture("bumpTexture")
  44302. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  44303. __decorate([
  44304. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44305. ], StandardMaterial.prototype, "bumpTexture", void 0);
  44306. __decorate([
  44307. BABYLON.serializeAsTexture("lightmapTexture")
  44308. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  44309. __decorate([
  44310. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44311. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  44312. __decorate([
  44313. BABYLON.serializeAsTexture("refractionTexture")
  44314. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  44315. __decorate([
  44316. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44317. ], StandardMaterial.prototype, "refractionTexture", void 0);
  44318. __decorate([
  44319. BABYLON.serializeAsColor3("ambient")
  44320. ], StandardMaterial.prototype, "ambientColor", void 0);
  44321. __decorate([
  44322. BABYLON.serializeAsColor3("diffuse")
  44323. ], StandardMaterial.prototype, "diffuseColor", void 0);
  44324. __decorate([
  44325. BABYLON.serializeAsColor3("specular")
  44326. ], StandardMaterial.prototype, "specularColor", void 0);
  44327. __decorate([
  44328. BABYLON.serializeAsColor3("emissive")
  44329. ], StandardMaterial.prototype, "emissiveColor", void 0);
  44330. __decorate([
  44331. BABYLON.serialize()
  44332. ], StandardMaterial.prototype, "specularPower", void 0);
  44333. __decorate([
  44334. BABYLON.serialize("useAlphaFromDiffuseTexture")
  44335. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  44336. __decorate([
  44337. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44338. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  44339. __decorate([
  44340. BABYLON.serialize("useEmissiveAsIllumination")
  44341. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  44342. __decorate([
  44343. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44344. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  44345. __decorate([
  44346. BABYLON.serialize("linkEmissiveWithDiffuse")
  44347. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  44348. __decorate([
  44349. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44350. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  44351. __decorate([
  44352. BABYLON.serialize("useSpecularOverAlpha")
  44353. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  44354. __decorate([
  44355. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44356. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  44357. __decorate([
  44358. BABYLON.serialize("useReflectionOverAlpha")
  44359. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  44360. __decorate([
  44361. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44362. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  44363. __decorate([
  44364. BABYLON.serialize("disableLighting")
  44365. ], StandardMaterial.prototype, "_disableLighting", void 0);
  44366. __decorate([
  44367. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44368. ], StandardMaterial.prototype, "disableLighting", void 0);
  44369. __decorate([
  44370. BABYLON.serialize("useObjectSpaceNormalMap")
  44371. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  44372. __decorate([
  44373. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44374. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  44375. __decorate([
  44376. BABYLON.serialize("useParallax")
  44377. ], StandardMaterial.prototype, "_useParallax", void 0);
  44378. __decorate([
  44379. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44380. ], StandardMaterial.prototype, "useParallax", void 0);
  44381. __decorate([
  44382. BABYLON.serialize("useParallaxOcclusion")
  44383. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  44384. __decorate([
  44385. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44386. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  44387. __decorate([
  44388. BABYLON.serialize()
  44389. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  44390. __decorate([
  44391. BABYLON.serialize("roughness")
  44392. ], StandardMaterial.prototype, "_roughness", void 0);
  44393. __decorate([
  44394. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44395. ], StandardMaterial.prototype, "roughness", void 0);
  44396. __decorate([
  44397. BABYLON.serialize()
  44398. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  44399. __decorate([
  44400. BABYLON.serialize()
  44401. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  44402. __decorate([
  44403. BABYLON.serialize()
  44404. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  44405. __decorate([
  44406. BABYLON.serialize("useLightmapAsShadowmap")
  44407. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  44408. __decorate([
  44409. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44410. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44411. __decorate([
  44412. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  44413. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  44414. __decorate([
  44415. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44416. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  44417. __decorate([
  44418. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  44419. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  44420. __decorate([
  44421. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  44422. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  44423. __decorate([
  44424. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  44425. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  44426. __decorate([
  44427. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44428. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  44429. __decorate([
  44430. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  44431. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  44432. __decorate([
  44433. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44434. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  44435. __decorate([
  44436. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  44437. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  44438. __decorate([
  44439. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44440. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  44441. __decorate([
  44442. BABYLON.serialize("useReflectionFresnelFromSpecular")
  44443. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  44444. __decorate([
  44445. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44446. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  44447. __decorate([
  44448. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  44449. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  44450. __decorate([
  44451. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44452. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  44453. __decorate([
  44454. BABYLON.serialize("maxSimultaneousLights")
  44455. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  44456. __decorate([
  44457. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44458. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  44459. __decorate([
  44460. BABYLON.serialize("invertNormalMapX")
  44461. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  44462. __decorate([
  44463. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44464. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  44465. __decorate([
  44466. BABYLON.serialize("invertNormalMapY")
  44467. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  44468. __decorate([
  44469. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44470. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  44471. __decorate([
  44472. BABYLON.serialize("twoSidedLighting")
  44473. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  44474. __decorate([
  44475. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44476. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  44477. __decorate([
  44478. BABYLON.serialize()
  44479. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  44480. return StandardMaterial;
  44481. }(BABYLON.PushMaterial));
  44482. BABYLON.StandardMaterial = StandardMaterial;
  44483. })(BABYLON || (BABYLON = {}));
  44484. //# sourceMappingURL=babylon.standardMaterial.js.map
  44485. var BABYLON;
  44486. (function (BABYLON) {
  44487. /**
  44488. * Class representing spherical polynomial coefficients to the 3rd degree
  44489. */
  44490. var SphericalPolynomial = /** @class */ (function () {
  44491. function SphericalPolynomial() {
  44492. /**
  44493. * The x coefficients of the spherical polynomial
  44494. */
  44495. this.x = BABYLON.Vector3.Zero();
  44496. /**
  44497. * The y coefficients of the spherical polynomial
  44498. */
  44499. this.y = BABYLON.Vector3.Zero();
  44500. /**
  44501. * The z coefficients of the spherical polynomial
  44502. */
  44503. this.z = BABYLON.Vector3.Zero();
  44504. /**
  44505. * The xx coefficients of the spherical polynomial
  44506. */
  44507. this.xx = BABYLON.Vector3.Zero();
  44508. /**
  44509. * The yy coefficients of the spherical polynomial
  44510. */
  44511. this.yy = BABYLON.Vector3.Zero();
  44512. /**
  44513. * The zz coefficients of the spherical polynomial
  44514. */
  44515. this.zz = BABYLON.Vector3.Zero();
  44516. /**
  44517. * The xy coefficients of the spherical polynomial
  44518. */
  44519. this.xy = BABYLON.Vector3.Zero();
  44520. /**
  44521. * The yz coefficients of the spherical polynomial
  44522. */
  44523. this.yz = BABYLON.Vector3.Zero();
  44524. /**
  44525. * The zx coefficients of the spherical polynomial
  44526. */
  44527. this.zx = BABYLON.Vector3.Zero();
  44528. }
  44529. /**
  44530. * Adds an ambient color to the spherical polynomial
  44531. * @param color the color to add
  44532. */
  44533. SphericalPolynomial.prototype.addAmbient = function (color) {
  44534. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  44535. this.xx = this.xx.add(colorVector);
  44536. this.yy = this.yy.add(colorVector);
  44537. this.zz = this.zz.add(colorVector);
  44538. };
  44539. /**
  44540. * Scales the spherical polynomial by the given amount
  44541. * @param scale the amount to scale
  44542. */
  44543. SphericalPolynomial.prototype.scale = function (scale) {
  44544. this.x = this.x.scale(scale);
  44545. this.y = this.y.scale(scale);
  44546. this.z = this.z.scale(scale);
  44547. this.xx = this.xx.scale(scale);
  44548. this.yy = this.yy.scale(scale);
  44549. this.zz = this.zz.scale(scale);
  44550. this.yz = this.yz.scale(scale);
  44551. this.zx = this.zx.scale(scale);
  44552. this.xy = this.xy.scale(scale);
  44553. };
  44554. /**
  44555. * Gets the spherical polynomial from harmonics
  44556. * @param harmonics the spherical harmonics
  44557. * @returns the spherical polynomial
  44558. */
  44559. SphericalPolynomial.FromHarmonics = function (harmonics) {
  44560. var result = new SphericalPolynomial();
  44561. result.x = harmonics.l11.scale(1.02333);
  44562. result.y = harmonics.l1_1.scale(1.02333);
  44563. result.z = harmonics.l10.scale(1.02333);
  44564. result.xx = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).add(harmonics.lL22.scale(0.429043));
  44565. result.yy = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).subtract(harmonics.lL22.scale(0.429043));
  44566. result.zz = harmonics.l00.scale(0.886277).add(harmonics.l20.scale(0.495417));
  44567. result.yz = harmonics.l2_1.scale(0.858086);
  44568. result.zx = harmonics.l21.scale(0.858086);
  44569. result.xy = harmonics.l2_2.scale(0.858086);
  44570. result.scale(1.0 / Math.PI);
  44571. return result;
  44572. };
  44573. /**
  44574. * Constructs a spherical polynomial from an array.
  44575. * @param data defines the 9x3 coefficients (x, y, z, xx, yy, zz, yz, zx, xy)
  44576. * @returns the spherical polynomial
  44577. */
  44578. SphericalPolynomial.FromArray = function (data) {
  44579. var sp = new SphericalPolynomial();
  44580. BABYLON.Vector3.FromArrayToRef(data[0], 0, sp.x);
  44581. BABYLON.Vector3.FromArrayToRef(data[1], 0, sp.y);
  44582. BABYLON.Vector3.FromArrayToRef(data[2], 0, sp.z);
  44583. BABYLON.Vector3.FromArrayToRef(data[3], 0, sp.xx);
  44584. BABYLON.Vector3.FromArrayToRef(data[4], 0, sp.yy);
  44585. BABYLON.Vector3.FromArrayToRef(data[5], 0, sp.zz);
  44586. BABYLON.Vector3.FromArrayToRef(data[6], 0, sp.yz);
  44587. BABYLON.Vector3.FromArrayToRef(data[7], 0, sp.zx);
  44588. BABYLON.Vector3.FromArrayToRef(data[8], 0, sp.xy);
  44589. return sp;
  44590. };
  44591. return SphericalPolynomial;
  44592. }());
  44593. BABYLON.SphericalPolynomial = SphericalPolynomial;
  44594. /**
  44595. * Class representing spherical harmonics coefficients to the 3rd degree
  44596. */
  44597. var SphericalHarmonics = /** @class */ (function () {
  44598. function SphericalHarmonics() {
  44599. /**
  44600. * The l0,0 coefficients of the spherical harmonics
  44601. */
  44602. this.l00 = BABYLON.Vector3.Zero();
  44603. /**
  44604. * The l1,-1 coefficients of the spherical harmonics
  44605. */
  44606. this.l1_1 = BABYLON.Vector3.Zero();
  44607. /**
  44608. * The l1,0 coefficients of the spherical harmonics
  44609. */
  44610. this.l10 = BABYLON.Vector3.Zero();
  44611. /**
  44612. * The l1,1 coefficients of the spherical harmonics
  44613. */
  44614. this.l11 = BABYLON.Vector3.Zero();
  44615. /**
  44616. * The l2,-2 coefficients of the spherical harmonics
  44617. */
  44618. this.l2_2 = BABYLON.Vector3.Zero();
  44619. /**
  44620. * The l2,-1 coefficients of the spherical harmonics
  44621. */
  44622. this.l2_1 = BABYLON.Vector3.Zero();
  44623. /**
  44624. * The l2,0 coefficients of the spherical harmonics
  44625. */
  44626. this.l20 = BABYLON.Vector3.Zero();
  44627. /**
  44628. * The l2,1 coefficients of the spherical harmonics
  44629. */
  44630. this.l21 = BABYLON.Vector3.Zero();
  44631. /**
  44632. * The l2,2 coefficients of the spherical harmonics
  44633. */
  44634. this.lL22 = BABYLON.Vector3.Zero();
  44635. }
  44636. /**
  44637. * Adds a light to the spherical harmonics
  44638. * @param direction the direction of the light
  44639. * @param color the color of the light
  44640. * @param deltaSolidAngle the delta solid angle of the light
  44641. */
  44642. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  44643. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  44644. var c = colorVector.scale(deltaSolidAngle);
  44645. this.l00 = this.l00.add(c.scale(0.282095));
  44646. this.l1_1 = this.l1_1.add(c.scale(0.488603 * direction.y));
  44647. this.l10 = this.l10.add(c.scale(0.488603 * direction.z));
  44648. this.l11 = this.l11.add(c.scale(0.488603 * direction.x));
  44649. this.l2_2 = this.l2_2.add(c.scale(1.092548 * direction.x * direction.y));
  44650. this.l2_1 = this.l2_1.add(c.scale(1.092548 * direction.y * direction.z));
  44651. this.l21 = this.l21.add(c.scale(1.092548 * direction.x * direction.z));
  44652. this.l20 = this.l20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  44653. this.lL22 = this.lL22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  44654. };
  44655. /**
  44656. * Scales the spherical harmonics by the given amount
  44657. * @param scale the amount to scale
  44658. */
  44659. SphericalHarmonics.prototype.scale = function (scale) {
  44660. this.l00 = this.l00.scale(scale);
  44661. this.l1_1 = this.l1_1.scale(scale);
  44662. this.l10 = this.l10.scale(scale);
  44663. this.l11 = this.l11.scale(scale);
  44664. this.l2_2 = this.l2_2.scale(scale);
  44665. this.l2_1 = this.l2_1.scale(scale);
  44666. this.l20 = this.l20.scale(scale);
  44667. this.l21 = this.l21.scale(scale);
  44668. this.lL22 = this.lL22.scale(scale);
  44669. };
  44670. /**
  44671. * Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  44672. *
  44673. * ```
  44674. * E_lm = A_l * L_lm
  44675. * ```
  44676. *
  44677. * In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  44678. * This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  44679. * the scaling factors are given in equation 9.
  44680. */
  44681. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  44682. // Constant (Band 0)
  44683. this.l00 = this.l00.scale(3.141593);
  44684. // Linear (Band 1)
  44685. this.l1_1 = this.l1_1.scale(2.094395);
  44686. this.l10 = this.l10.scale(2.094395);
  44687. this.l11 = this.l11.scale(2.094395);
  44688. // Quadratic (Band 2)
  44689. this.l2_2 = this.l2_2.scale(0.785398);
  44690. this.l2_1 = this.l2_1.scale(0.785398);
  44691. this.l20 = this.l20.scale(0.785398);
  44692. this.l21 = this.l21.scale(0.785398);
  44693. this.lL22 = this.lL22.scale(0.785398);
  44694. };
  44695. /**
  44696. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  44697. *
  44698. * ```
  44699. * L = (1/pi) * E * rho
  44700. * ```
  44701. *
  44702. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  44703. */
  44704. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  44705. this.scale(1.0 / Math.PI);
  44706. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  44707. // (The pixel shader must apply albedo after texture fetches, etc).
  44708. };
  44709. /**
  44710. * Gets the spherical harmonics from polynomial
  44711. * @param polynomial the spherical polynomial
  44712. * @returns the spherical harmonics
  44713. */
  44714. SphericalHarmonics.FromPolynomial = function (polynomial) {
  44715. var result = new SphericalHarmonics();
  44716. result.l00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  44717. result.l1_1 = polynomial.y.scale(0.977204);
  44718. result.l10 = polynomial.z.scale(0.977204);
  44719. result.l11 = polynomial.x.scale(0.977204);
  44720. result.l2_2 = polynomial.xy.scale(1.16538);
  44721. result.l2_1 = polynomial.yz.scale(1.16538);
  44722. result.l20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  44723. result.l21 = polynomial.zx.scale(1.16538);
  44724. result.lL22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  44725. result.scale(Math.PI);
  44726. return result;
  44727. };
  44728. /**
  44729. * Constructs a spherical harmonics from an array.
  44730. * @param data defines the 9x3 coefficients (l00, l1-1, l10, l11, l2-2, l2-1, l20, l21, l22)
  44731. * @returns the spherical harmonics
  44732. */
  44733. SphericalHarmonics.FromArray = function (data) {
  44734. var sh = new SphericalHarmonics();
  44735. BABYLON.Vector3.FromArrayToRef(data[0], 0, sh.l00);
  44736. BABYLON.Vector3.FromArrayToRef(data[1], 0, sh.l1_1);
  44737. BABYLON.Vector3.FromArrayToRef(data[2], 0, sh.l10);
  44738. BABYLON.Vector3.FromArrayToRef(data[3], 0, sh.l11);
  44739. BABYLON.Vector3.FromArrayToRef(data[4], 0, sh.l2_2);
  44740. BABYLON.Vector3.FromArrayToRef(data[5], 0, sh.l2_1);
  44741. BABYLON.Vector3.FromArrayToRef(data[6], 0, sh.l20);
  44742. BABYLON.Vector3.FromArrayToRef(data[7], 0, sh.l21);
  44743. BABYLON.Vector3.FromArrayToRef(data[8], 0, sh.lL22);
  44744. return sh;
  44745. };
  44746. return SphericalHarmonics;
  44747. }());
  44748. BABYLON.SphericalHarmonics = SphericalHarmonics;
  44749. })(BABYLON || (BABYLON = {}));
  44750. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  44751. var BABYLON;
  44752. (function (BABYLON) {
  44753. var FileFaceOrientation = /** @class */ (function () {
  44754. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  44755. this.name = name;
  44756. this.worldAxisForNormal = worldAxisForNormal;
  44757. this.worldAxisForFileX = worldAxisForFileX;
  44758. this.worldAxisForFileY = worldAxisForFileY;
  44759. }
  44760. return FileFaceOrientation;
  44761. }());
  44762. ;
  44763. /**
  44764. * Helper class dealing with the extraction of spherical polynomial dataArray
  44765. * from a cube map.
  44766. */
  44767. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  44768. function CubeMapToSphericalPolynomialTools() {
  44769. }
  44770. /**
  44771. * Converts a texture to the according Spherical Polynomial data.
  44772. * This extracts the first 3 orders only as they are the only one used in the lighting.
  44773. *
  44774. * @param texture The texture to extract the information from.
  44775. * @return The Spherical Polynomial data.
  44776. */
  44777. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  44778. if (!texture.isCube) {
  44779. // Only supports cube Textures currently.
  44780. return null;
  44781. }
  44782. var size = texture.getSize().width;
  44783. var right = texture.readPixels(0);
  44784. var left = texture.readPixels(1);
  44785. var up;
  44786. var down;
  44787. if (texture.isRenderTarget) {
  44788. up = texture.readPixels(3);
  44789. down = texture.readPixels(2);
  44790. }
  44791. else {
  44792. up = texture.readPixels(2);
  44793. down = texture.readPixels(3);
  44794. }
  44795. var front = texture.readPixels(4);
  44796. var back = texture.readPixels(5);
  44797. var gammaSpace = texture.gammaSpace;
  44798. // Always read as RGBA.
  44799. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  44800. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  44801. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  44802. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  44803. }
  44804. var cubeInfo = {
  44805. size: size,
  44806. right: right,
  44807. left: left,
  44808. up: up,
  44809. down: down,
  44810. front: front,
  44811. back: back,
  44812. format: format,
  44813. type: type,
  44814. gammaSpace: gammaSpace,
  44815. };
  44816. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  44817. };
  44818. /**
  44819. * Converts a cubemap to the according Spherical Polynomial data.
  44820. * This extracts the first 3 orders only as they are the only one used in the lighting.
  44821. *
  44822. * @param cubeInfo The Cube map to extract the information from.
  44823. * @return The Spherical Polynomial data.
  44824. */
  44825. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  44826. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  44827. var totalSolidAngle = 0.0;
  44828. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  44829. var du = 2.0 / cubeInfo.size;
  44830. var dv = du;
  44831. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  44832. var minUV = du * 0.5 - 1.0;
  44833. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  44834. var fileFace = this.FileFaces[faceIndex];
  44835. var dataArray = cubeInfo[fileFace.name];
  44836. var v = minUV;
  44837. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  44838. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  44839. // Because SP is still linear, so summation is fine in that basis.
  44840. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  44841. for (var y = 0; y < cubeInfo.size; y++) {
  44842. var u = minUV;
  44843. for (var x = 0; x < cubeInfo.size; x++) {
  44844. // World direction (not normalised)
  44845. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  44846. worldDirection.normalize();
  44847. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  44848. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  44849. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  44850. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  44851. // Handle Integer types.
  44852. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  44853. r /= 255;
  44854. g /= 255;
  44855. b /= 255;
  44856. }
  44857. // Handle Gamma space textures.
  44858. if (cubeInfo.gammaSpace) {
  44859. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  44860. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  44861. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  44862. }
  44863. var color = new BABYLON.Color3(r, g, b);
  44864. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  44865. totalSolidAngle += deltaSolidAngle;
  44866. u += du;
  44867. }
  44868. v += dv;
  44869. }
  44870. }
  44871. // Solid angle for entire sphere is 4*pi
  44872. var sphereSolidAngle = 4.0 * Math.PI;
  44873. // Adjust the solid angle to allow for how many faces we processed.
  44874. var facesProcessed = 6.0;
  44875. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  44876. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  44877. // This is needed because the numerical integration over the cube uses a
  44878. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  44879. // and also to compensate for accumulative error due to float precision in the summation.
  44880. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  44881. sphericalHarmonics.scale(correctionFactor);
  44882. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  44883. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  44884. return BABYLON.SphericalPolynomial.FromHarmonics(sphericalHarmonics);
  44885. };
  44886. CubeMapToSphericalPolynomialTools.FileFaces = [
  44887. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  44888. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  44889. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  44890. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  44891. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  44892. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  44893. ];
  44894. return CubeMapToSphericalPolynomialTools;
  44895. }());
  44896. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  44897. })(BABYLON || (BABYLON = {}));
  44898. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  44899. var BABYLON;
  44900. (function (BABYLON) {
  44901. /**
  44902. * Manages the defines for the PBR Material.
  44903. * @hiddenChildren
  44904. */
  44905. var PBRMaterialDefines = /** @class */ (function (_super) {
  44906. __extends(PBRMaterialDefines, _super);
  44907. /**
  44908. * Initializes the PBR Material defines.
  44909. */
  44910. function PBRMaterialDefines() {
  44911. var _this = _super.call(this) || this;
  44912. _this.PBR = true;
  44913. _this.MAINUV1 = false;
  44914. _this.MAINUV2 = false;
  44915. _this.UV1 = false;
  44916. _this.UV2 = false;
  44917. _this.ALBEDO = false;
  44918. _this.ALBEDODIRECTUV = 0;
  44919. _this.VERTEXCOLOR = false;
  44920. _this.AMBIENT = false;
  44921. _this.AMBIENTDIRECTUV = 0;
  44922. _this.AMBIENTINGRAYSCALE = false;
  44923. _this.OPACITY = false;
  44924. _this.VERTEXALPHA = false;
  44925. _this.OPACITYDIRECTUV = 0;
  44926. _this.OPACITYRGB = false;
  44927. _this.ALPHATEST = false;
  44928. _this.DEPTHPREPASS = false;
  44929. _this.ALPHABLEND = false;
  44930. _this.ALPHAFROMALBEDO = false;
  44931. _this.ALPHATESTVALUE = "0.5";
  44932. _this.SPECULAROVERALPHA = false;
  44933. _this.RADIANCEOVERALPHA = false;
  44934. _this.ALPHAFRESNEL = false;
  44935. _this.LINEARALPHAFRESNEL = false;
  44936. _this.PREMULTIPLYALPHA = false;
  44937. _this.EMISSIVE = false;
  44938. _this.EMISSIVEDIRECTUV = 0;
  44939. _this.REFLECTIVITY = false;
  44940. _this.REFLECTIVITYDIRECTUV = 0;
  44941. _this.SPECULARTERM = false;
  44942. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  44943. _this.MICROSURFACEAUTOMATIC = false;
  44944. _this.LODBASEDMICROSFURACE = false;
  44945. _this.MICROSURFACEMAP = false;
  44946. _this.MICROSURFACEMAPDIRECTUV = 0;
  44947. _this.METALLICWORKFLOW = false;
  44948. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  44949. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  44950. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  44951. _this.AOSTOREINMETALMAPRED = false;
  44952. _this.ENVIRONMENTBRDF = false;
  44953. _this.NORMAL = false;
  44954. _this.TANGENT = false;
  44955. _this.BUMP = false;
  44956. _this.BUMPDIRECTUV = 0;
  44957. _this.OBJECTSPACE_NORMALMAP = false;
  44958. _this.PARALLAX = false;
  44959. _this.PARALLAXOCCLUSION = false;
  44960. _this.NORMALXYSCALE = true;
  44961. _this.LIGHTMAP = false;
  44962. _this.LIGHTMAPDIRECTUV = 0;
  44963. _this.USELIGHTMAPASSHADOWMAP = false;
  44964. _this.GAMMALIGHTMAP = false;
  44965. _this.REFLECTION = false;
  44966. _this.REFLECTIONMAP_3D = false;
  44967. _this.REFLECTIONMAP_SPHERICAL = false;
  44968. _this.REFLECTIONMAP_PLANAR = false;
  44969. _this.REFLECTIONMAP_CUBIC = false;
  44970. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44971. _this.REFLECTIONMAP_PROJECTION = false;
  44972. _this.REFLECTIONMAP_SKYBOX = false;
  44973. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  44974. _this.REFLECTIONMAP_EXPLICIT = false;
  44975. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44976. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44977. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44978. _this.INVERTCUBICMAP = false;
  44979. _this.USESPHERICALFROMREFLECTIONMAP = false;
  44980. _this.USESPHERICALINVERTEX = false;
  44981. _this.REFLECTIONMAP_OPPOSITEZ = false;
  44982. _this.LODINREFLECTIONALPHA = false;
  44983. _this.GAMMAREFLECTION = false;
  44984. _this.RGBDREFLECTION = false;
  44985. _this.RADIANCEOCCLUSION = false;
  44986. _this.HORIZONOCCLUSION = false;
  44987. _this.REFRACTION = false;
  44988. _this.REFRACTIONMAP_3D = false;
  44989. _this.REFRACTIONMAP_OPPOSITEZ = false;
  44990. _this.LODINREFRACTIONALPHA = false;
  44991. _this.GAMMAREFRACTION = false;
  44992. _this.RGBDREFRACTION = false;
  44993. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  44994. _this.INSTANCES = false;
  44995. _this.NUM_BONE_INFLUENCERS = 0;
  44996. _this.BonesPerMesh = 0;
  44997. _this.NONUNIFORMSCALING = false;
  44998. _this.MORPHTARGETS = false;
  44999. _this.MORPHTARGETS_NORMAL = false;
  45000. _this.MORPHTARGETS_TANGENT = false;
  45001. _this.NUM_MORPH_INFLUENCERS = 0;
  45002. _this.IMAGEPROCESSING = false;
  45003. _this.VIGNETTE = false;
  45004. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  45005. _this.VIGNETTEBLENDMODEOPAQUE = false;
  45006. _this.TONEMAPPING = false;
  45007. _this.TONEMAPPING_ACES = false;
  45008. _this.CONTRAST = false;
  45009. _this.COLORCURVES = false;
  45010. _this.COLORGRADING = false;
  45011. _this.COLORGRADING3D = false;
  45012. _this.SAMPLER3DGREENDEPTH = false;
  45013. _this.SAMPLER3DBGRMAP = false;
  45014. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  45015. _this.EXPOSURE = false;
  45016. _this.USEPHYSICALLIGHTFALLOFF = false;
  45017. _this.USEGLTFLIGHTFALLOFF = false;
  45018. _this.TWOSIDEDLIGHTING = false;
  45019. _this.SHADOWFLOAT = false;
  45020. _this.CLIPPLANE = false;
  45021. _this.CLIPPLANE2 = false;
  45022. _this.CLIPPLANE3 = false;
  45023. _this.CLIPPLANE4 = false;
  45024. _this.POINTSIZE = false;
  45025. _this.FOG = false;
  45026. _this.LOGARITHMICDEPTH = false;
  45027. _this.FORCENORMALFORWARD = false;
  45028. _this.SPECULARAA = false;
  45029. _this.UNLIT = false;
  45030. _this.rebuild();
  45031. return _this;
  45032. }
  45033. /**
  45034. * Resets the PBR Material defines.
  45035. */
  45036. PBRMaterialDefines.prototype.reset = function () {
  45037. _super.prototype.reset.call(this);
  45038. this.ALPHATESTVALUE = "0.5";
  45039. this.PBR = true;
  45040. };
  45041. return PBRMaterialDefines;
  45042. }(BABYLON.MaterialDefines));
  45043. /**
  45044. * The Physically based material base class of BJS.
  45045. *
  45046. * This offers the main features of a standard PBR material.
  45047. * For more information, please refer to the documentation :
  45048. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  45049. */
  45050. var PBRBaseMaterial = /** @class */ (function (_super) {
  45051. __extends(PBRBaseMaterial, _super);
  45052. /**
  45053. * Instantiates a new PBRMaterial instance.
  45054. *
  45055. * @param name The material name
  45056. * @param scene The scene the material will be use in.
  45057. */
  45058. function PBRBaseMaterial(name, scene) {
  45059. var _this = _super.call(this, name, scene) || this;
  45060. /**
  45061. * Intensity of the direct lights e.g. the four lights available in your scene.
  45062. * This impacts both the direct diffuse and specular highlights.
  45063. */
  45064. _this._directIntensity = 1.0;
  45065. /**
  45066. * Intensity of the emissive part of the material.
  45067. * This helps controlling the emissive effect without modifying the emissive color.
  45068. */
  45069. _this._emissiveIntensity = 1.0;
  45070. /**
  45071. * Intensity of the environment e.g. how much the environment will light the object
  45072. * either through harmonics for rough material or through the refelction for shiny ones.
  45073. */
  45074. _this._environmentIntensity = 1.0;
  45075. /**
  45076. * This is a special control allowing the reduction of the specular highlights coming from the
  45077. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  45078. */
  45079. _this._specularIntensity = 1.0;
  45080. /**
  45081. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  45082. */
  45083. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  45084. /**
  45085. * Debug Control allowing disabling the bump map on this material.
  45086. */
  45087. _this._disableBumpMap = false;
  45088. /**
  45089. * AKA Occlusion Texture Intensity in other nomenclature.
  45090. */
  45091. _this._ambientTextureStrength = 1.0;
  45092. /**
  45093. * Defines how much the AO map is occluding the analytical lights (point spot...).
  45094. * 1 means it completely occludes it
  45095. * 0 mean it has no impact
  45096. */
  45097. _this._ambientTextureImpactOnAnalyticalLights = BABYLON.PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  45098. /**
  45099. * The color of a material in ambient lighting.
  45100. */
  45101. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  45102. /**
  45103. * AKA Diffuse Color in other nomenclature.
  45104. */
  45105. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  45106. /**
  45107. * AKA Specular Color in other nomenclature.
  45108. */
  45109. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  45110. /**
  45111. * The color applied when light is reflected from a material.
  45112. */
  45113. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  45114. /**
  45115. * The color applied when light is emitted from a material.
  45116. */
  45117. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  45118. /**
  45119. * AKA Glossiness in other nomenclature.
  45120. */
  45121. _this._microSurface = 0.9;
  45122. /**
  45123. * source material index of refraction (IOR)' / 'destination material IOR.
  45124. */
  45125. _this._indexOfRefraction = 0.66;
  45126. /**
  45127. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  45128. */
  45129. _this._invertRefractionY = false;
  45130. /**
  45131. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  45132. * Materials half opaque for instance using refraction could benefit from this control.
  45133. */
  45134. _this._linkRefractionWithTransparency = false;
  45135. /**
  45136. * Specifies that the material will use the light map as a show map.
  45137. */
  45138. _this._useLightmapAsShadowmap = false;
  45139. /**
  45140. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  45141. * makes the reflect vector face the model (under horizon).
  45142. */
  45143. _this._useHorizonOcclusion = true;
  45144. /**
  45145. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  45146. * too much the area relying on ambient texture to define their ambient occlusion.
  45147. */
  45148. _this._useRadianceOcclusion = true;
  45149. /**
  45150. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  45151. */
  45152. _this._useAlphaFromAlbedoTexture = false;
  45153. /**
  45154. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  45155. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  45156. */
  45157. _this._useSpecularOverAlpha = true;
  45158. /**
  45159. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  45160. */
  45161. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  45162. /**
  45163. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  45164. */
  45165. _this._useRoughnessFromMetallicTextureAlpha = true;
  45166. /**
  45167. * Specifies if the metallic texture contains the roughness information in its green channel.
  45168. */
  45169. _this._useRoughnessFromMetallicTextureGreen = false;
  45170. /**
  45171. * Specifies if the metallic texture contains the metallness information in its blue channel.
  45172. */
  45173. _this._useMetallnessFromMetallicTextureBlue = false;
  45174. /**
  45175. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  45176. */
  45177. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  45178. /**
  45179. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  45180. */
  45181. _this._useAmbientInGrayScale = false;
  45182. /**
  45183. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  45184. * The material will try to infer what glossiness each pixel should be.
  45185. */
  45186. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  45187. /**
  45188. * Defines the falloff type used in this material.
  45189. * It by default is Physical.
  45190. */
  45191. _this._lightFalloff = PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  45192. /**
  45193. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  45194. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  45195. */
  45196. _this._useRadianceOverAlpha = true;
  45197. /**
  45198. * Allows using an object space normal map (instead of tangent space).
  45199. */
  45200. _this._useObjectSpaceNormalMap = false;
  45201. /**
  45202. * Allows using the bump map in parallax mode.
  45203. */
  45204. _this._useParallax = false;
  45205. /**
  45206. * Allows using the bump map in parallax occlusion mode.
  45207. */
  45208. _this._useParallaxOcclusion = false;
  45209. /**
  45210. * Controls the scale bias of the parallax mode.
  45211. */
  45212. _this._parallaxScaleBias = 0.05;
  45213. /**
  45214. * If sets to true, disables all the lights affecting the material.
  45215. */
  45216. _this._disableLighting = false;
  45217. /**
  45218. * Number of Simultaneous lights allowed on the material.
  45219. */
  45220. _this._maxSimultaneousLights = 4;
  45221. /**
  45222. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  45223. */
  45224. _this._invertNormalMapX = false;
  45225. /**
  45226. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  45227. */
  45228. _this._invertNormalMapY = false;
  45229. /**
  45230. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45231. */
  45232. _this._twoSidedLighting = false;
  45233. /**
  45234. * Defines the alpha limits in alpha test mode.
  45235. */
  45236. _this._alphaCutOff = 0.4;
  45237. /**
  45238. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  45239. */
  45240. _this._forceAlphaTest = false;
  45241. /**
  45242. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45243. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  45244. */
  45245. _this._useAlphaFresnel = false;
  45246. /**
  45247. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45248. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  45249. */
  45250. _this._useLinearAlphaFresnel = false;
  45251. /**
  45252. * The transparency mode of the material.
  45253. */
  45254. _this._transparencyMode = null;
  45255. /**
  45256. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  45257. * from cos thetav and roughness:
  45258. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  45259. */
  45260. _this._environmentBRDFTexture = null;
  45261. /**
  45262. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  45263. */
  45264. _this._forceIrradianceInFragment = false;
  45265. /**
  45266. * Force normal to face away from face.
  45267. */
  45268. _this._forceNormalForward = false;
  45269. /**
  45270. * Enables specular anti aliasing in the PBR shader.
  45271. * It will both interacts on the Geometry for analytical and IBL lighting.
  45272. * It also prefilter the roughness map based on the bump values.
  45273. */
  45274. _this._enableSpecularAntiAliasing = false;
  45275. /**
  45276. * Stores the available render targets.
  45277. */
  45278. _this._renderTargets = new BABYLON.SmartArray(16);
  45279. /**
  45280. * Sets the global ambient color for the material used in lighting calculations.
  45281. */
  45282. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  45283. /**
  45284. * If set to true, no lighting calculations will be applied.
  45285. */
  45286. _this._unlit = false;
  45287. // Setup the default processing configuration to the scene.
  45288. _this._attachImageProcessingConfiguration(null);
  45289. _this.getRenderTargetTextures = function () {
  45290. _this._renderTargets.reset();
  45291. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  45292. _this._renderTargets.push(_this._reflectionTexture);
  45293. }
  45294. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  45295. _this._renderTargets.push(_this._refractionTexture);
  45296. }
  45297. return _this._renderTargets;
  45298. };
  45299. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  45300. return _this;
  45301. }
  45302. /**
  45303. * Attaches a new image processing configuration to the PBR Material.
  45304. * @param configuration
  45305. */
  45306. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  45307. var _this = this;
  45308. if (configuration === this._imageProcessingConfiguration) {
  45309. return;
  45310. }
  45311. // Detaches observer.
  45312. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  45313. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  45314. }
  45315. // Pick the scene configuration if needed.
  45316. if (!configuration) {
  45317. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  45318. }
  45319. else {
  45320. this._imageProcessingConfiguration = configuration;
  45321. }
  45322. // Attaches observer.
  45323. if (this._imageProcessingConfiguration) {
  45324. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  45325. _this._markAllSubMeshesAsImageProcessingDirty();
  45326. });
  45327. }
  45328. };
  45329. Object.defineProperty(PBRBaseMaterial.prototype, "hasRenderTargetTextures", {
  45330. /**
  45331. * Gets a boolean indicating that current material needs to register RTT
  45332. */
  45333. get: function () {
  45334. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  45335. return true;
  45336. }
  45337. if (BABYLON.StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
  45338. return true;
  45339. }
  45340. return false;
  45341. },
  45342. enumerable: true,
  45343. configurable: true
  45344. });
  45345. /**
  45346. * Gets the name of the material class.
  45347. */
  45348. PBRBaseMaterial.prototype.getClassName = function () {
  45349. return "PBRBaseMaterial";
  45350. };
  45351. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  45352. /**
  45353. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  45354. */
  45355. get: function () {
  45356. return this._useLogarithmicDepth;
  45357. },
  45358. /**
  45359. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  45360. */
  45361. set: function (value) {
  45362. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  45363. },
  45364. enumerable: true,
  45365. configurable: true
  45366. });
  45367. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  45368. /**
  45369. * Gets the current transparency mode.
  45370. */
  45371. get: function () {
  45372. return this._transparencyMode;
  45373. },
  45374. /**
  45375. * Sets the transparency mode of the material.
  45376. *
  45377. * | Value | Type | Description |
  45378. * | ----- | ----------------------------------- | ----------- |
  45379. * | 0 | OPAQUE | |
  45380. * | 1 | ALPHATEST | |
  45381. * | 2 | ALPHABLEND | |
  45382. * | 3 | ALPHATESTANDBLEND | |
  45383. *
  45384. */
  45385. set: function (value) {
  45386. if (this._transparencyMode === value) {
  45387. return;
  45388. }
  45389. this._transparencyMode = value;
  45390. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  45391. this._markAllSubMeshesAsTexturesAndMiscDirty();
  45392. },
  45393. enumerable: true,
  45394. configurable: true
  45395. });
  45396. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  45397. /**
  45398. * Returns true if alpha blending should be disabled.
  45399. */
  45400. get: function () {
  45401. return (this._linkRefractionWithTransparency ||
  45402. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  45403. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  45404. },
  45405. enumerable: true,
  45406. configurable: true
  45407. });
  45408. /**
  45409. * Specifies whether or not this material should be rendered in alpha blend mode.
  45410. */
  45411. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  45412. if (this._disableAlphaBlending) {
  45413. return false;
  45414. }
  45415. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  45416. };
  45417. /**
  45418. * Specifies if the mesh will require alpha blending.
  45419. * @param mesh - BJS mesh.
  45420. */
  45421. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  45422. if (this._disableAlphaBlending) {
  45423. return false;
  45424. }
  45425. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  45426. };
  45427. /**
  45428. * Specifies whether or not this material should be rendered in alpha test mode.
  45429. */
  45430. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  45431. if (this._forceAlphaTest) {
  45432. return true;
  45433. }
  45434. if (this._linkRefractionWithTransparency) {
  45435. return false;
  45436. }
  45437. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  45438. };
  45439. /**
  45440. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  45441. */
  45442. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  45443. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  45444. };
  45445. /**
  45446. * Gets the texture used for the alpha test.
  45447. */
  45448. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  45449. return this._albedoTexture;
  45450. };
  45451. /**
  45452. * Specifies that the submesh is ready to be used.
  45453. * @param mesh - BJS mesh.
  45454. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  45455. * @param useInstances - Specifies that instances should be used.
  45456. * @returns - boolean indicating that the submesh is ready or not.
  45457. */
  45458. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  45459. if (subMesh.effect && this.isFrozen) {
  45460. if (this._wasPreviouslyReady) {
  45461. return true;
  45462. }
  45463. }
  45464. if (!subMesh._materialDefines) {
  45465. subMesh._materialDefines = new PBRMaterialDefines();
  45466. }
  45467. var defines = subMesh._materialDefines;
  45468. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  45469. if (defines._renderId === this.getScene().getRenderId()) {
  45470. return true;
  45471. }
  45472. }
  45473. var scene = this.getScene();
  45474. var engine = scene.getEngine();
  45475. if (defines._areTexturesDirty) {
  45476. if (scene.texturesEnabled) {
  45477. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45478. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  45479. return false;
  45480. }
  45481. }
  45482. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45483. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  45484. return false;
  45485. }
  45486. }
  45487. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45488. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  45489. return false;
  45490. }
  45491. }
  45492. var reflectionTexture = this._getReflectionTexture();
  45493. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45494. if (!reflectionTexture.isReadyOrNotBlocking()) {
  45495. return false;
  45496. }
  45497. }
  45498. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45499. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  45500. return false;
  45501. }
  45502. }
  45503. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45504. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  45505. return false;
  45506. }
  45507. }
  45508. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45509. if (this._metallicTexture) {
  45510. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  45511. return false;
  45512. }
  45513. }
  45514. else if (this._reflectivityTexture) {
  45515. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  45516. return false;
  45517. }
  45518. }
  45519. if (this._microSurfaceTexture) {
  45520. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  45521. return false;
  45522. }
  45523. }
  45524. }
  45525. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45526. // Bump texture cannot be not blocking.
  45527. if (!this._bumpTexture.isReady()) {
  45528. return false;
  45529. }
  45530. }
  45531. var refractionTexture = this._getRefractionTexture();
  45532. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45533. if (!refractionTexture.isReadyOrNotBlocking()) {
  45534. return false;
  45535. }
  45536. }
  45537. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45538. // This is blocking.
  45539. if (!this._environmentBRDFTexture.isReady()) {
  45540. return false;
  45541. }
  45542. }
  45543. }
  45544. }
  45545. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  45546. if (!this._imageProcessingConfiguration.isReady()) {
  45547. return false;
  45548. }
  45549. }
  45550. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  45551. mesh.createNormals(true);
  45552. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  45553. }
  45554. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  45555. if (effect) {
  45556. scene.resetCachedMaterial();
  45557. subMesh.setEffect(effect, defines);
  45558. this.buildUniformLayout();
  45559. }
  45560. if (!subMesh.effect || !subMesh.effect.isReady()) {
  45561. return false;
  45562. }
  45563. defines._renderId = scene.getRenderId();
  45564. this._wasPreviouslyReady = true;
  45565. return true;
  45566. };
  45567. /**
  45568. * Specifies if the material uses metallic roughness workflow.
  45569. * @returns boolean specifiying if the material uses metallic roughness workflow.
  45570. */
  45571. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  45572. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  45573. return true;
  45574. }
  45575. return false;
  45576. };
  45577. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  45578. if (onCompiled === void 0) { onCompiled = null; }
  45579. if (onError === void 0) { onError = null; }
  45580. if (useInstances === void 0) { useInstances = null; }
  45581. if (useClipPlane === void 0) { useClipPlane = null; }
  45582. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  45583. if (!defines.isDirty) {
  45584. return null;
  45585. }
  45586. defines.markAsProcessed();
  45587. var scene = this.getScene();
  45588. var engine = scene.getEngine();
  45589. // Fallbacks
  45590. var fallbacks = new BABYLON.EffectFallbacks();
  45591. var fallbackRank = 0;
  45592. if (defines.USESPHERICALINVERTEX) {
  45593. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  45594. }
  45595. if (defines.FOG) {
  45596. fallbacks.addFallback(fallbackRank, "FOG");
  45597. }
  45598. if (defines.SPECULARAA) {
  45599. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  45600. }
  45601. if (defines.POINTSIZE) {
  45602. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  45603. }
  45604. if (defines.LOGARITHMICDEPTH) {
  45605. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  45606. }
  45607. if (defines.PARALLAX) {
  45608. fallbacks.addFallback(fallbackRank, "PARALLAX");
  45609. }
  45610. if (defines.PARALLAXOCCLUSION) {
  45611. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  45612. }
  45613. if (defines.ENVIRONMENTBRDF) {
  45614. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  45615. }
  45616. if (defines.TANGENT) {
  45617. fallbacks.addFallback(fallbackRank++, "TANGENT");
  45618. }
  45619. if (defines.BUMP) {
  45620. fallbacks.addFallback(fallbackRank++, "BUMP");
  45621. }
  45622. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  45623. if (defines.SPECULARTERM) {
  45624. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  45625. }
  45626. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  45627. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  45628. }
  45629. if (defines.LIGHTMAP) {
  45630. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  45631. }
  45632. if (defines.NORMAL) {
  45633. fallbacks.addFallback(fallbackRank++, "NORMAL");
  45634. }
  45635. if (defines.AMBIENT) {
  45636. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  45637. }
  45638. if (defines.EMISSIVE) {
  45639. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  45640. }
  45641. if (defines.VERTEXCOLOR) {
  45642. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  45643. }
  45644. if (defines.NUM_BONE_INFLUENCERS > 0) {
  45645. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  45646. }
  45647. if (defines.MORPHTARGETS) {
  45648. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  45649. }
  45650. //Attributes
  45651. var attribs = [BABYLON.VertexBuffer.PositionKind];
  45652. if (defines.NORMAL) {
  45653. attribs.push(BABYLON.VertexBuffer.NormalKind);
  45654. }
  45655. if (defines.TANGENT) {
  45656. attribs.push(BABYLON.VertexBuffer.TangentKind);
  45657. }
  45658. if (defines.UV1) {
  45659. attribs.push(BABYLON.VertexBuffer.UVKind);
  45660. }
  45661. if (defines.UV2) {
  45662. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  45663. }
  45664. if (defines.VERTEXCOLOR) {
  45665. attribs.push(BABYLON.VertexBuffer.ColorKind);
  45666. }
  45667. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  45668. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  45669. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  45670. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  45671. "vFogInfos", "vFogColor", "pointSize",
  45672. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  45673. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  45674. "mBones",
  45675. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  45676. "vLightingIntensity",
  45677. "logarithmicDepthConstant",
  45678. "vSphericalX", "vSphericalY", "vSphericalZ",
  45679. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  45680. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  45681. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  45682. "vTangentSpaceParams"
  45683. ];
  45684. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  45685. "bumpSampler", "lightmapSampler", "opacitySampler",
  45686. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  45687. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  45688. "microSurfaceSampler", "environmentBrdfSampler"];
  45689. var uniformBuffers = ["Material", "Scene"];
  45690. if (BABYLON.ImageProcessingConfiguration) {
  45691. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  45692. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  45693. }
  45694. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  45695. uniformsNames: uniforms,
  45696. uniformBuffersNames: uniformBuffers,
  45697. samplers: samplers,
  45698. defines: defines,
  45699. maxSimultaneousLights: this._maxSimultaneousLights
  45700. });
  45701. var join = defines.toString();
  45702. return engine.createEffect("pbr", {
  45703. attributes: attribs,
  45704. uniformsNames: uniforms,
  45705. uniformBuffersNames: uniformBuffers,
  45706. samplers: samplers,
  45707. defines: join,
  45708. fallbacks: fallbacks,
  45709. onCompiled: onCompiled,
  45710. onError: onError,
  45711. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  45712. }, engine);
  45713. };
  45714. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  45715. if (useInstances === void 0) { useInstances = null; }
  45716. if (useClipPlane === void 0) { useClipPlane = null; }
  45717. var scene = this.getScene();
  45718. var engine = scene.getEngine();
  45719. // Lights
  45720. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  45721. defines._needNormals = true;
  45722. // Textures
  45723. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  45724. if (defines._areTexturesDirty) {
  45725. defines._needUVs = false;
  45726. if (scene.texturesEnabled) {
  45727. if (scene.getEngine().getCaps().textureLOD) {
  45728. defines.LODBASEDMICROSFURACE = true;
  45729. }
  45730. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45731. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  45732. }
  45733. else {
  45734. defines.ALBEDO = false;
  45735. }
  45736. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45737. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  45738. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  45739. }
  45740. else {
  45741. defines.AMBIENT = false;
  45742. }
  45743. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45744. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  45745. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  45746. }
  45747. else {
  45748. defines.OPACITY = false;
  45749. }
  45750. var reflectionTexture = this._getReflectionTexture();
  45751. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45752. defines.REFLECTION = true;
  45753. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  45754. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  45755. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  45756. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  45757. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  45758. defines.INVERTCUBICMAP = true;
  45759. }
  45760. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  45761. switch (reflectionTexture.coordinatesMode) {
  45762. case BABYLON.Texture.EXPLICIT_MODE:
  45763. defines.REFLECTIONMAP_EXPLICIT = true;
  45764. break;
  45765. case BABYLON.Texture.PLANAR_MODE:
  45766. defines.REFLECTIONMAP_PLANAR = true;
  45767. break;
  45768. case BABYLON.Texture.PROJECTION_MODE:
  45769. defines.REFLECTIONMAP_PROJECTION = true;
  45770. break;
  45771. case BABYLON.Texture.SKYBOX_MODE:
  45772. defines.REFLECTIONMAP_SKYBOX = true;
  45773. break;
  45774. case BABYLON.Texture.SPHERICAL_MODE:
  45775. defines.REFLECTIONMAP_SPHERICAL = true;
  45776. break;
  45777. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  45778. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  45779. break;
  45780. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  45781. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  45782. break;
  45783. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  45784. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  45785. break;
  45786. case BABYLON.Texture.CUBIC_MODE:
  45787. case BABYLON.Texture.INVCUBIC_MODE:
  45788. default:
  45789. defines.REFLECTIONMAP_CUBIC = true;
  45790. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  45791. break;
  45792. }
  45793. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  45794. if (reflectionTexture.sphericalPolynomial) {
  45795. defines.USESPHERICALFROMREFLECTIONMAP = true;
  45796. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  45797. defines.USESPHERICALINVERTEX = false;
  45798. }
  45799. else {
  45800. defines.USESPHERICALINVERTEX = true;
  45801. }
  45802. }
  45803. }
  45804. else {
  45805. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  45806. }
  45807. }
  45808. else {
  45809. defines.REFLECTION = false;
  45810. defines.REFLECTIONMAP_3D = false;
  45811. defines.REFLECTIONMAP_SPHERICAL = false;
  45812. defines.REFLECTIONMAP_PLANAR = false;
  45813. defines.REFLECTIONMAP_CUBIC = false;
  45814. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  45815. defines.REFLECTIONMAP_PROJECTION = false;
  45816. defines.REFLECTIONMAP_SKYBOX = false;
  45817. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  45818. defines.REFLECTIONMAP_EXPLICIT = false;
  45819. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  45820. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  45821. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  45822. defines.INVERTCUBICMAP = false;
  45823. defines.USESPHERICALFROMREFLECTIONMAP = false;
  45824. defines.USESPHERICALINVERTEX = false;
  45825. defines.REFLECTIONMAP_OPPOSITEZ = false;
  45826. defines.LODINREFLECTIONALPHA = false;
  45827. defines.GAMMAREFLECTION = false;
  45828. defines.RGBDREFLECTION = false;
  45829. }
  45830. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45831. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  45832. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  45833. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  45834. }
  45835. else {
  45836. defines.LIGHTMAP = false;
  45837. }
  45838. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45839. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  45840. }
  45841. else {
  45842. defines.EMISSIVE = false;
  45843. }
  45844. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45845. if (this._metallicTexture) {
  45846. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  45847. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  45848. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  45849. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  45850. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  45851. }
  45852. else if (this._reflectivityTexture) {
  45853. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  45854. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  45855. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  45856. }
  45857. else {
  45858. defines.REFLECTIVITY = false;
  45859. }
  45860. if (this._microSurfaceTexture) {
  45861. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  45862. }
  45863. else {
  45864. defines.MICROSURFACEMAP = false;
  45865. }
  45866. }
  45867. else {
  45868. defines.REFLECTIVITY = false;
  45869. defines.MICROSURFACEMAP = false;
  45870. }
  45871. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45872. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  45873. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45874. defines.PARALLAX = true;
  45875. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  45876. }
  45877. else {
  45878. defines.PARALLAX = false;
  45879. }
  45880. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  45881. }
  45882. else {
  45883. defines.BUMP = false;
  45884. }
  45885. var refractionTexture = this._getRefractionTexture();
  45886. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45887. defines.REFRACTION = true;
  45888. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  45889. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  45890. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  45891. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  45892. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  45893. if (this._linkRefractionWithTransparency) {
  45894. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  45895. }
  45896. }
  45897. else {
  45898. defines.REFRACTION = false;
  45899. }
  45900. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45901. defines.ENVIRONMENTBRDF = true;
  45902. }
  45903. else {
  45904. defines.ENVIRONMENTBRDF = false;
  45905. }
  45906. if (this._shouldUseAlphaFromAlbedoTexture()) {
  45907. defines.ALPHAFROMALBEDO = true;
  45908. }
  45909. else {
  45910. defines.ALPHAFROMALBEDO = false;
  45911. }
  45912. }
  45913. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  45914. if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_STANDARD) {
  45915. defines.USEPHYSICALLIGHTFALLOFF = false;
  45916. defines.USEGLTFLIGHTFALLOFF = false;
  45917. }
  45918. else if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_GLTF) {
  45919. defines.USEPHYSICALLIGHTFALLOFF = false;
  45920. defines.USEGLTFLIGHTFALLOFF = true;
  45921. }
  45922. else {
  45923. defines.USEPHYSICALLIGHTFALLOFF = true;
  45924. defines.USEGLTFLIGHTFALLOFF = false;
  45925. }
  45926. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  45927. if (!this.backFaceCulling && this._twoSidedLighting) {
  45928. defines.TWOSIDEDLIGHTING = true;
  45929. }
  45930. else {
  45931. defines.TWOSIDEDLIGHTING = false;
  45932. }
  45933. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  45934. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  45935. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  45936. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  45937. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  45938. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  45939. }
  45940. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  45941. this._imageProcessingConfiguration.prepareDefines(defines);
  45942. }
  45943. defines.FORCENORMALFORWARD = this._forceNormalForward;
  45944. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  45945. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  45946. // Misc.
  45947. if (defines._areMiscDirty) {
  45948. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  45949. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  45950. }
  45951. // Values that need to be evaluated on every frame
  45952. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  45953. // Attribs
  45954. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  45955. };
  45956. /**
  45957. * Force shader compilation
  45958. */
  45959. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  45960. var _this = this;
  45961. var localOptions = __assign({ clipPlane: false }, options);
  45962. var defines = new PBRMaterialDefines();
  45963. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  45964. if (effect.isReady()) {
  45965. if (onCompiled) {
  45966. onCompiled(this);
  45967. }
  45968. }
  45969. else {
  45970. effect.onCompileObservable.add(function () {
  45971. if (onCompiled) {
  45972. onCompiled(_this);
  45973. }
  45974. });
  45975. }
  45976. };
  45977. /**
  45978. * Initializes the uniform buffer layout for the shader.
  45979. */
  45980. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  45981. // Order is important !
  45982. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  45983. this._uniformBuffer.addUniform("vAmbientInfos", 4);
  45984. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  45985. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  45986. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  45987. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  45988. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  45989. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  45990. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  45991. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  45992. this._uniformBuffer.addUniform("vReflectionSize", 3);
  45993. this._uniformBuffer.addUniform("vBumpInfos", 3);
  45994. this._uniformBuffer.addUniform("albedoMatrix", 16);
  45995. this._uniformBuffer.addUniform("ambientMatrix", 16);
  45996. this._uniformBuffer.addUniform("opacityMatrix", 16);
  45997. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  45998. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  45999. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  46000. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  46001. this._uniformBuffer.addUniform("bumpMatrix", 16);
  46002. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  46003. this._uniformBuffer.addUniform("refractionMatrix", 16);
  46004. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  46005. this._uniformBuffer.addUniform("vReflectionColor", 3);
  46006. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  46007. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  46008. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  46009. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  46010. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  46011. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  46012. this._uniformBuffer.addUniform("pointSize", 1);
  46013. this._uniformBuffer.create();
  46014. };
  46015. /**
  46016. * Unbinds the textures.
  46017. */
  46018. PBRBaseMaterial.prototype.unbind = function () {
  46019. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  46020. this._uniformBuffer.setTexture("reflectionSampler", null);
  46021. }
  46022. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  46023. this._uniformBuffer.setTexture("refractionSampler", null);
  46024. }
  46025. _super.prototype.unbind.call(this);
  46026. };
  46027. /**
  46028. * Binds the submesh data.
  46029. * @param world - The world matrix.
  46030. * @param mesh - The BJS mesh.
  46031. * @param subMesh - A submesh of the BJS mesh.
  46032. */
  46033. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  46034. var scene = this.getScene();
  46035. var defines = subMesh._materialDefines;
  46036. if (!defines) {
  46037. return;
  46038. }
  46039. var effect = subMesh.effect;
  46040. if (!effect) {
  46041. return;
  46042. }
  46043. this._activeEffect = effect;
  46044. // Matrices
  46045. this.bindOnlyWorldMatrix(world);
  46046. // Normal Matrix
  46047. if (defines.OBJECTSPACE_NORMALMAP) {
  46048. world.toNormalMatrix(this._normalMatrix);
  46049. this.bindOnlyNormalMatrix(this._normalMatrix);
  46050. }
  46051. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  46052. // Bones
  46053. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  46054. var reflectionTexture = null;
  46055. if (mustRebind) {
  46056. this._uniformBuffer.bindToEffect(effect, "Material");
  46057. this.bindViewProjection(effect);
  46058. reflectionTexture = this._getReflectionTexture();
  46059. var refractionTexture = this._getRefractionTexture();
  46060. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  46061. // Texture uniforms
  46062. if (scene.texturesEnabled) {
  46063. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  46064. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  46065. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  46066. }
  46067. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  46068. this._uniformBuffer.updateFloat4("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength, this._ambientTextureImpactOnAnalyticalLights);
  46069. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  46070. }
  46071. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  46072. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  46073. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  46074. }
  46075. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  46076. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  46077. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  46078. if (reflectionTexture.boundingBoxSize) {
  46079. var cubeTexture = reflectionTexture;
  46080. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  46081. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  46082. }
  46083. var polynomials = reflectionTexture.sphericalPolynomial;
  46084. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  46085. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  46086. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  46087. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  46088. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  46089. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  46090. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  46091. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  46092. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  46093. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  46094. }
  46095. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  46096. }
  46097. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  46098. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  46099. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  46100. }
  46101. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  46102. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  46103. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  46104. }
  46105. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  46106. if (this._metallicTexture) {
  46107. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  46108. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  46109. }
  46110. else if (this._reflectivityTexture) {
  46111. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  46112. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  46113. }
  46114. if (this._microSurfaceTexture) {
  46115. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  46116. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  46117. }
  46118. }
  46119. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  46120. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  46121. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  46122. if (scene._mirroredCameraPosition) {
  46123. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  46124. }
  46125. else {
  46126. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  46127. }
  46128. }
  46129. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  46130. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  46131. var depth = 1.0;
  46132. if (!refractionTexture.isCube) {
  46133. if (refractionTexture.depth) {
  46134. depth = refractionTexture.depth;
  46135. }
  46136. }
  46137. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  46138. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  46139. }
  46140. }
  46141. // Point size
  46142. if (this.pointsCloud) {
  46143. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  46144. }
  46145. // Colors
  46146. if (defines.METALLICWORKFLOW) {
  46147. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  46148. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  46149. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  46150. }
  46151. else {
  46152. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  46153. }
  46154. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  46155. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  46156. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  46157. // Misc
  46158. this._lightingInfos.x = this._directIntensity;
  46159. this._lightingInfos.y = this._emissiveIntensity;
  46160. this._lightingInfos.z = this._environmentIntensity;
  46161. this._lightingInfos.w = this._specularIntensity;
  46162. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  46163. }
  46164. // Textures
  46165. if (scene.texturesEnabled) {
  46166. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  46167. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  46168. }
  46169. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  46170. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  46171. }
  46172. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  46173. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  46174. }
  46175. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  46176. if (defines.LODBASEDMICROSFURACE) {
  46177. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  46178. }
  46179. else {
  46180. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  46181. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  46182. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  46183. }
  46184. }
  46185. if (defines.ENVIRONMENTBRDF) {
  46186. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  46187. }
  46188. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  46189. if (defines.LODBASEDMICROSFURACE) {
  46190. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  46191. }
  46192. else {
  46193. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  46194. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  46195. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  46196. }
  46197. }
  46198. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  46199. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  46200. }
  46201. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  46202. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  46203. }
  46204. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  46205. if (this._metallicTexture) {
  46206. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  46207. }
  46208. else if (this._reflectivityTexture) {
  46209. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  46210. }
  46211. if (this._microSurfaceTexture) {
  46212. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  46213. }
  46214. }
  46215. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  46216. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  46217. }
  46218. }
  46219. // Clip plane
  46220. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  46221. // Colors
  46222. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  46223. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  46224. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  46225. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  46226. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  46227. }
  46228. if (mustRebind || !this.isFrozen) {
  46229. // Lights
  46230. if (scene.lightsEnabled && !this._disableLighting) {
  46231. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._lightFalloff !== PBRBaseMaterial.LIGHTFALLOFF_STANDARD);
  46232. }
  46233. // View
  46234. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  46235. this.bindView(effect);
  46236. }
  46237. // Fog
  46238. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect, true);
  46239. // Morph targets
  46240. if (defines.NUM_MORPH_INFLUENCERS) {
  46241. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  46242. }
  46243. // image processing
  46244. this._imageProcessingConfiguration.bind(this._activeEffect);
  46245. // Log. depth
  46246. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  46247. }
  46248. this._uniformBuffer.update();
  46249. this._afterBind(mesh, this._activeEffect);
  46250. };
  46251. /**
  46252. * Returns the animatable textures.
  46253. * @returns - Array of animatable textures.
  46254. */
  46255. PBRBaseMaterial.prototype.getAnimatables = function () {
  46256. var results = [];
  46257. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  46258. results.push(this._albedoTexture);
  46259. }
  46260. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  46261. results.push(this._ambientTexture);
  46262. }
  46263. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  46264. results.push(this._opacityTexture);
  46265. }
  46266. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  46267. results.push(this._reflectionTexture);
  46268. }
  46269. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  46270. results.push(this._emissiveTexture);
  46271. }
  46272. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  46273. results.push(this._metallicTexture);
  46274. }
  46275. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  46276. results.push(this._reflectivityTexture);
  46277. }
  46278. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  46279. results.push(this._bumpTexture);
  46280. }
  46281. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  46282. results.push(this._lightmapTexture);
  46283. }
  46284. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  46285. results.push(this._refractionTexture);
  46286. }
  46287. return results;
  46288. };
  46289. /**
  46290. * Returns the texture used for reflections.
  46291. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  46292. */
  46293. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  46294. if (this._reflectionTexture) {
  46295. return this._reflectionTexture;
  46296. }
  46297. return this.getScene().environmentTexture;
  46298. };
  46299. /**
  46300. * Returns the texture used for refraction or null if none is used.
  46301. * @returns - Refection texture if present. If no refraction texture and refraction
  46302. * is linked with transparency, returns environment texture. Otherwise, returns null.
  46303. */
  46304. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  46305. if (this._refractionTexture) {
  46306. return this._refractionTexture;
  46307. }
  46308. if (this._linkRefractionWithTransparency) {
  46309. return this.getScene().environmentTexture;
  46310. }
  46311. return null;
  46312. };
  46313. /**
  46314. * Disposes the resources of the material.
  46315. * @param forceDisposeEffect - Forces the disposal of effects.
  46316. * @param forceDisposeTextures - Forces the disposal of all textures.
  46317. */
  46318. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  46319. if (forceDisposeTextures) {
  46320. if (this._albedoTexture) {
  46321. this._albedoTexture.dispose();
  46322. }
  46323. if (this._ambientTexture) {
  46324. this._ambientTexture.dispose();
  46325. }
  46326. if (this._opacityTexture) {
  46327. this._opacityTexture.dispose();
  46328. }
  46329. if (this._reflectionTexture) {
  46330. this._reflectionTexture.dispose();
  46331. }
  46332. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  46333. this._environmentBRDFTexture.dispose();
  46334. }
  46335. if (this._emissiveTexture) {
  46336. this._emissiveTexture.dispose();
  46337. }
  46338. if (this._metallicTexture) {
  46339. this._metallicTexture.dispose();
  46340. }
  46341. if (this._reflectivityTexture) {
  46342. this._reflectivityTexture.dispose();
  46343. }
  46344. if (this._bumpTexture) {
  46345. this._bumpTexture.dispose();
  46346. }
  46347. if (this._lightmapTexture) {
  46348. this._lightmapTexture.dispose();
  46349. }
  46350. if (this._refractionTexture) {
  46351. this._refractionTexture.dispose();
  46352. }
  46353. }
  46354. this._renderTargets.dispose();
  46355. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  46356. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  46357. }
  46358. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  46359. };
  46360. /**
  46361. * PBRMaterialLightFalloff Physical: light is falling off following the inverse squared distance law.
  46362. */
  46363. PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL = 0;
  46364. /**
  46365. * PBRMaterialLightFalloff gltf: light is falling off as described in the gltf moving to PBR document
  46366. * to enhance interoperability with other engines.
  46367. */
  46368. PBRBaseMaterial.LIGHTFALLOFF_GLTF = 1;
  46369. /**
  46370. * PBRMaterialLightFalloff Standard: light is falling off like in the standard material
  46371. * to enhance interoperability with other materials.
  46372. */
  46373. PBRBaseMaterial.LIGHTFALLOFF_STANDARD = 2;
  46374. /**
  46375. * Stores the reflectivity values based on metallic roughness workflow.
  46376. */
  46377. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  46378. __decorate([
  46379. BABYLON.serializeAsImageProcessingConfiguration()
  46380. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  46381. __decorate([
  46382. BABYLON.serialize()
  46383. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  46384. __decorate([
  46385. BABYLON.serialize()
  46386. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  46387. return PBRBaseMaterial;
  46388. }(BABYLON.PushMaterial));
  46389. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  46390. })(BABYLON || (BABYLON = {}));
  46391. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  46392. var BABYLON;
  46393. (function (BABYLON) {
  46394. /**
  46395. * The Physically based simple base material of BJS.
  46396. *
  46397. * This enables better naming and convention enforcements on top of the pbrMaterial.
  46398. * It is used as the base class for both the specGloss and metalRough conventions.
  46399. */
  46400. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  46401. __extends(PBRBaseSimpleMaterial, _super);
  46402. /**
  46403. * Instantiates a new PBRMaterial instance.
  46404. *
  46405. * @param name The material name
  46406. * @param scene The scene the material will be use in.
  46407. */
  46408. function PBRBaseSimpleMaterial(name, scene) {
  46409. var _this = _super.call(this, name, scene) || this;
  46410. /**
  46411. * Number of Simultaneous lights allowed on the material.
  46412. */
  46413. _this.maxSimultaneousLights = 4;
  46414. /**
  46415. * If sets to true, disables all the lights affecting the material.
  46416. */
  46417. _this.disableLighting = false;
  46418. /**
  46419. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  46420. */
  46421. _this.invertNormalMapX = false;
  46422. /**
  46423. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  46424. */
  46425. _this.invertNormalMapY = false;
  46426. /**
  46427. * Emissivie color used to self-illuminate the model.
  46428. */
  46429. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  46430. /**
  46431. * Occlusion Channel Strenght.
  46432. */
  46433. _this.occlusionStrength = 1.0;
  46434. /**
  46435. * If true, the light map contains occlusion information instead of lighting info.
  46436. */
  46437. _this.useLightmapAsShadowmap = false;
  46438. _this._useAlphaFromAlbedoTexture = true;
  46439. _this._useAmbientInGrayScale = true;
  46440. return _this;
  46441. }
  46442. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  46443. /**
  46444. * Gets the current double sided mode.
  46445. */
  46446. get: function () {
  46447. return this._twoSidedLighting;
  46448. },
  46449. /**
  46450. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  46451. */
  46452. set: function (value) {
  46453. if (this._twoSidedLighting === value) {
  46454. return;
  46455. }
  46456. this._twoSidedLighting = value;
  46457. this.backFaceCulling = !value;
  46458. this._markAllSubMeshesAsTexturesDirty();
  46459. },
  46460. enumerable: true,
  46461. configurable: true
  46462. });
  46463. /**
  46464. * Return the active textures of the material.
  46465. */
  46466. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  46467. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46468. if (this.environmentTexture) {
  46469. activeTextures.push(this.environmentTexture);
  46470. }
  46471. if (this.normalTexture) {
  46472. activeTextures.push(this.normalTexture);
  46473. }
  46474. if (this.emissiveTexture) {
  46475. activeTextures.push(this.emissiveTexture);
  46476. }
  46477. if (this.occlusionTexture) {
  46478. activeTextures.push(this.occlusionTexture);
  46479. }
  46480. if (this.lightmapTexture) {
  46481. activeTextures.push(this.lightmapTexture);
  46482. }
  46483. return activeTextures;
  46484. };
  46485. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  46486. if (_super.prototype.hasTexture.call(this, texture)) {
  46487. return true;
  46488. }
  46489. if (this.lightmapTexture === texture) {
  46490. return true;
  46491. }
  46492. return false;
  46493. };
  46494. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  46495. return "PBRBaseSimpleMaterial";
  46496. };
  46497. __decorate([
  46498. BABYLON.serialize(),
  46499. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46500. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  46501. __decorate([
  46502. BABYLON.serialize(),
  46503. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46504. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  46505. __decorate([
  46506. BABYLON.serializeAsTexture(),
  46507. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  46508. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  46509. __decorate([
  46510. BABYLON.serialize(),
  46511. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46512. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  46513. __decorate([
  46514. BABYLON.serialize(),
  46515. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46516. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  46517. __decorate([
  46518. BABYLON.serializeAsTexture(),
  46519. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  46520. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  46521. __decorate([
  46522. BABYLON.serializeAsColor3("emissive"),
  46523. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46524. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  46525. __decorate([
  46526. BABYLON.serializeAsTexture(),
  46527. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46528. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  46529. __decorate([
  46530. BABYLON.serialize(),
  46531. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  46532. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  46533. __decorate([
  46534. BABYLON.serializeAsTexture(),
  46535. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  46536. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  46537. __decorate([
  46538. BABYLON.serialize(),
  46539. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  46540. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  46541. __decorate([
  46542. BABYLON.serialize()
  46543. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  46544. __decorate([
  46545. BABYLON.serializeAsTexture(),
  46546. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  46547. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  46548. __decorate([
  46549. BABYLON.serialize(),
  46550. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46551. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  46552. return PBRBaseSimpleMaterial;
  46553. }(BABYLON.PBRBaseMaterial));
  46554. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  46555. })(BABYLON || (BABYLON = {}));
  46556. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  46557. var BABYLON;
  46558. (function (BABYLON) {
  46559. /**
  46560. * The Physically based material of BJS.
  46561. *
  46562. * This offers the main features of a standard PBR material.
  46563. * For more information, please refer to the documentation :
  46564. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  46565. */
  46566. var PBRMaterial = /** @class */ (function (_super) {
  46567. __extends(PBRMaterial, _super);
  46568. /**
  46569. * Instantiates a new PBRMaterial instance.
  46570. *
  46571. * @param name The material name
  46572. * @param scene The scene the material will be use in.
  46573. */
  46574. function PBRMaterial(name, scene) {
  46575. var _this = _super.call(this, name, scene) || this;
  46576. /**
  46577. * Intensity of the direct lights e.g. the four lights available in your scene.
  46578. * This impacts both the direct diffuse and specular highlights.
  46579. */
  46580. _this.directIntensity = 1.0;
  46581. /**
  46582. * Intensity of the emissive part of the material.
  46583. * This helps controlling the emissive effect without modifying the emissive color.
  46584. */
  46585. _this.emissiveIntensity = 1.0;
  46586. /**
  46587. * Intensity of the environment e.g. how much the environment will light the object
  46588. * either through harmonics for rough material or through the refelction for shiny ones.
  46589. */
  46590. _this.environmentIntensity = 1.0;
  46591. /**
  46592. * This is a special control allowing the reduction of the specular highlights coming from the
  46593. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  46594. */
  46595. _this.specularIntensity = 1.0;
  46596. /**
  46597. * Debug Control allowing disabling the bump map on this material.
  46598. */
  46599. _this.disableBumpMap = false;
  46600. /**
  46601. * AKA Occlusion Texture Intensity in other nomenclature.
  46602. */
  46603. _this.ambientTextureStrength = 1.0;
  46604. /**
  46605. * Defines how much the AO map is occluding the analytical lights (point spot...).
  46606. * 1 means it completely occludes it
  46607. * 0 mean it has no impact
  46608. */
  46609. _this.ambientTextureImpactOnAnalyticalLights = PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  46610. /**
  46611. * The color of a material in ambient lighting.
  46612. */
  46613. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  46614. /**
  46615. * AKA Diffuse Color in other nomenclature.
  46616. */
  46617. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  46618. /**
  46619. * AKA Specular Color in other nomenclature.
  46620. */
  46621. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  46622. /**
  46623. * The color reflected from the material.
  46624. */
  46625. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  46626. /**
  46627. * The color emitted from the material.
  46628. */
  46629. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  46630. /**
  46631. * AKA Glossiness in other nomenclature.
  46632. */
  46633. _this.microSurface = 1.0;
  46634. /**
  46635. * source material index of refraction (IOR)' / 'destination material IOR.
  46636. */
  46637. _this.indexOfRefraction = 0.66;
  46638. /**
  46639. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  46640. */
  46641. _this.invertRefractionY = false;
  46642. /**
  46643. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  46644. * Materials half opaque for instance using refraction could benefit from this control.
  46645. */
  46646. _this.linkRefractionWithTransparency = false;
  46647. /**
  46648. * If true, the light map contains occlusion information instead of lighting info.
  46649. */
  46650. _this.useLightmapAsShadowmap = false;
  46651. /**
  46652. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  46653. */
  46654. _this.useAlphaFromAlbedoTexture = false;
  46655. /**
  46656. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  46657. */
  46658. _this.forceAlphaTest = false;
  46659. /**
  46660. * Defines the alpha limits in alpha test mode.
  46661. */
  46662. _this.alphaCutOff = 0.4;
  46663. /**
  46664. * Specifies that the material will keep the specular highlights over a transparent surface (only the most limunous ones).
  46665. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  46666. */
  46667. _this.useSpecularOverAlpha = true;
  46668. /**
  46669. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  46670. */
  46671. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  46672. /**
  46673. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  46674. */
  46675. _this.useRoughnessFromMetallicTextureAlpha = true;
  46676. /**
  46677. * Specifies if the metallic texture contains the roughness information in its green channel.
  46678. */
  46679. _this.useRoughnessFromMetallicTextureGreen = false;
  46680. /**
  46681. * Specifies if the metallic texture contains the metallness information in its blue channel.
  46682. */
  46683. _this.useMetallnessFromMetallicTextureBlue = false;
  46684. /**
  46685. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  46686. */
  46687. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  46688. /**
  46689. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  46690. */
  46691. _this.useAmbientInGrayScale = false;
  46692. /**
  46693. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  46694. * The material will try to infer what glossiness each pixel should be.
  46695. */
  46696. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  46697. /**
  46698. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  46699. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  46700. */
  46701. _this.useRadianceOverAlpha = true;
  46702. /**
  46703. * Allows using an object space normal map (instead of tangent space).
  46704. */
  46705. _this.useObjectSpaceNormalMap = false;
  46706. /**
  46707. * Allows using the bump map in parallax mode.
  46708. */
  46709. _this.useParallax = false;
  46710. /**
  46711. * Allows using the bump map in parallax occlusion mode.
  46712. */
  46713. _this.useParallaxOcclusion = false;
  46714. /**
  46715. * Controls the scale bias of the parallax mode.
  46716. */
  46717. _this.parallaxScaleBias = 0.05;
  46718. /**
  46719. * If sets to true, disables all the lights affecting the material.
  46720. */
  46721. _this.disableLighting = false;
  46722. /**
  46723. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  46724. */
  46725. _this.forceIrradianceInFragment = false;
  46726. /**
  46727. * Number of Simultaneous lights allowed on the material.
  46728. */
  46729. _this.maxSimultaneousLights = 4;
  46730. /**
  46731. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  46732. */
  46733. _this.invertNormalMapX = false;
  46734. /**
  46735. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  46736. */
  46737. _this.invertNormalMapY = false;
  46738. /**
  46739. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  46740. */
  46741. _this.twoSidedLighting = false;
  46742. /**
  46743. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46744. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  46745. */
  46746. _this.useAlphaFresnel = false;
  46747. /**
  46748. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46749. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  46750. */
  46751. _this.useLinearAlphaFresnel = false;
  46752. /**
  46753. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46754. * And/Or occlude the blended part.
  46755. */
  46756. _this.environmentBRDFTexture = null;
  46757. /**
  46758. * Force normal to face away from face.
  46759. */
  46760. _this.forceNormalForward = false;
  46761. /**
  46762. * Enables specular anti aliasing in the PBR shader.
  46763. * It will both interacts on the Geometry for analytical and IBL lighting.
  46764. * It also prefilter the roughness map based on the bump values.
  46765. */
  46766. _this.enableSpecularAntiAliasing = false;
  46767. /**
  46768. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  46769. * makes the reflect vector face the model (under horizon).
  46770. */
  46771. _this.useHorizonOcclusion = true;
  46772. /**
  46773. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  46774. * too much the area relying on ambient texture to define their ambient occlusion.
  46775. */
  46776. _this.useRadianceOcclusion = true;
  46777. /**
  46778. * If set to true, no lighting calculations will be applied.
  46779. */
  46780. _this.unlit = false;
  46781. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  46782. return _this;
  46783. }
  46784. Object.defineProperty(PBRMaterial.prototype, "usePhysicalLightFalloff", {
  46785. /**
  46786. * BJS is using an harcoded light falloff based on a manually sets up range.
  46787. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  46788. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  46789. */
  46790. get: function () {
  46791. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  46792. },
  46793. /**
  46794. * BJS is using an harcoded light falloff based on a manually sets up range.
  46795. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  46796. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  46797. */
  46798. set: function (value) {
  46799. if (value !== this.usePhysicalLightFalloff) {
  46800. // Ensure the effect will be rebuilt.
  46801. this._markAllSubMeshesAsTexturesDirty();
  46802. if (value) {
  46803. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  46804. }
  46805. else {
  46806. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  46807. }
  46808. }
  46809. },
  46810. enumerable: true,
  46811. configurable: true
  46812. });
  46813. Object.defineProperty(PBRMaterial.prototype, "useGLTFLightFalloff", {
  46814. /**
  46815. * In order to support the falloff compatibility with gltf, a special mode has been added
  46816. * to reproduce the gltf light falloff.
  46817. */
  46818. get: function () {
  46819. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  46820. },
  46821. /**
  46822. * In order to support the falloff compatibility with gltf, a special mode has been added
  46823. * to reproduce the gltf light falloff.
  46824. */
  46825. set: function (value) {
  46826. if (value !== this.useGLTFLightFalloff) {
  46827. // Ensure the effect will be rebuilt.
  46828. this._markAllSubMeshesAsTexturesDirty();
  46829. if (value) {
  46830. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  46831. }
  46832. else {
  46833. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  46834. }
  46835. }
  46836. },
  46837. enumerable: true,
  46838. configurable: true
  46839. });
  46840. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  46841. /**
  46842. * Gets the image processing configuration used either in this material.
  46843. */
  46844. get: function () {
  46845. return this._imageProcessingConfiguration;
  46846. },
  46847. /**
  46848. * Sets the Default image processing configuration used either in the this material.
  46849. *
  46850. * If sets to null, the scene one is in use.
  46851. */
  46852. set: function (value) {
  46853. this._attachImageProcessingConfiguration(value);
  46854. // Ensure the effect will be rebuilt.
  46855. this._markAllSubMeshesAsTexturesDirty();
  46856. },
  46857. enumerable: true,
  46858. configurable: true
  46859. });
  46860. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  46861. /**
  46862. * Gets wether the color curves effect is enabled.
  46863. */
  46864. get: function () {
  46865. return this.imageProcessingConfiguration.colorCurvesEnabled;
  46866. },
  46867. /**
  46868. * Sets wether the color curves effect is enabled.
  46869. */
  46870. set: function (value) {
  46871. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  46872. },
  46873. enumerable: true,
  46874. configurable: true
  46875. });
  46876. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  46877. /**
  46878. * Gets wether the color grading effect is enabled.
  46879. */
  46880. get: function () {
  46881. return this.imageProcessingConfiguration.colorGradingEnabled;
  46882. },
  46883. /**
  46884. * Gets wether the color grading effect is enabled.
  46885. */
  46886. set: function (value) {
  46887. this.imageProcessingConfiguration.colorGradingEnabled = value;
  46888. },
  46889. enumerable: true,
  46890. configurable: true
  46891. });
  46892. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  46893. /**
  46894. * Gets wether tonemapping is enabled or not.
  46895. */
  46896. get: function () {
  46897. return this._imageProcessingConfiguration.toneMappingEnabled;
  46898. },
  46899. /**
  46900. * Sets wether tonemapping is enabled or not
  46901. */
  46902. set: function (value) {
  46903. this._imageProcessingConfiguration.toneMappingEnabled = value;
  46904. },
  46905. enumerable: true,
  46906. configurable: true
  46907. });
  46908. ;
  46909. ;
  46910. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  46911. /**
  46912. * The camera exposure used on this material.
  46913. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  46914. * This corresponds to a photographic exposure.
  46915. */
  46916. get: function () {
  46917. return this._imageProcessingConfiguration.exposure;
  46918. },
  46919. /**
  46920. * The camera exposure used on this material.
  46921. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  46922. * This corresponds to a photographic exposure.
  46923. */
  46924. set: function (value) {
  46925. this._imageProcessingConfiguration.exposure = value;
  46926. },
  46927. enumerable: true,
  46928. configurable: true
  46929. });
  46930. ;
  46931. ;
  46932. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  46933. /**
  46934. * Gets The camera contrast used on this material.
  46935. */
  46936. get: function () {
  46937. return this._imageProcessingConfiguration.contrast;
  46938. },
  46939. /**
  46940. * Sets The camera contrast used on this material.
  46941. */
  46942. set: function (value) {
  46943. this._imageProcessingConfiguration.contrast = value;
  46944. },
  46945. enumerable: true,
  46946. configurable: true
  46947. });
  46948. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  46949. /**
  46950. * Gets the Color Grading 2D Lookup Texture.
  46951. */
  46952. get: function () {
  46953. return this._imageProcessingConfiguration.colorGradingTexture;
  46954. },
  46955. /**
  46956. * Sets the Color Grading 2D Lookup Texture.
  46957. */
  46958. set: function (value) {
  46959. this._imageProcessingConfiguration.colorGradingTexture = value;
  46960. },
  46961. enumerable: true,
  46962. configurable: true
  46963. });
  46964. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  46965. /**
  46966. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  46967. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  46968. * 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;
  46969. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  46970. */
  46971. get: function () {
  46972. return this._imageProcessingConfiguration.colorCurves;
  46973. },
  46974. /**
  46975. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  46976. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  46977. * 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;
  46978. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  46979. */
  46980. set: function (value) {
  46981. this._imageProcessingConfiguration.colorCurves = value;
  46982. },
  46983. enumerable: true,
  46984. configurable: true
  46985. });
  46986. /**
  46987. * Returns the name of this material class.
  46988. */
  46989. PBRMaterial.prototype.getClassName = function () {
  46990. return "PBRMaterial";
  46991. };
  46992. /**
  46993. * Returns an array of the actively used textures.
  46994. * @returns - Array of BaseTextures
  46995. */
  46996. PBRMaterial.prototype.getActiveTextures = function () {
  46997. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46998. if (this._albedoTexture) {
  46999. activeTextures.push(this._albedoTexture);
  47000. }
  47001. if (this._ambientTexture) {
  47002. activeTextures.push(this._ambientTexture);
  47003. }
  47004. if (this._opacityTexture) {
  47005. activeTextures.push(this._opacityTexture);
  47006. }
  47007. if (this._reflectionTexture) {
  47008. activeTextures.push(this._reflectionTexture);
  47009. }
  47010. if (this._emissiveTexture) {
  47011. activeTextures.push(this._emissiveTexture);
  47012. }
  47013. if (this._reflectivityTexture) {
  47014. activeTextures.push(this._reflectivityTexture);
  47015. }
  47016. if (this._metallicTexture) {
  47017. activeTextures.push(this._metallicTexture);
  47018. }
  47019. if (this._microSurfaceTexture) {
  47020. activeTextures.push(this._microSurfaceTexture);
  47021. }
  47022. if (this._bumpTexture) {
  47023. activeTextures.push(this._bumpTexture);
  47024. }
  47025. if (this._lightmapTexture) {
  47026. activeTextures.push(this._lightmapTexture);
  47027. }
  47028. if (this._refractionTexture) {
  47029. activeTextures.push(this._refractionTexture);
  47030. }
  47031. return activeTextures;
  47032. };
  47033. /**
  47034. * Checks to see if a texture is used in the material.
  47035. * @param texture - Base texture to use.
  47036. * @returns - Boolean specifying if a texture is used in the material.
  47037. */
  47038. PBRMaterial.prototype.hasTexture = function (texture) {
  47039. if (_super.prototype.hasTexture.call(this, texture)) {
  47040. return true;
  47041. }
  47042. if (this._albedoTexture === texture) {
  47043. return true;
  47044. }
  47045. if (this._ambientTexture === texture) {
  47046. return true;
  47047. }
  47048. if (this._opacityTexture === texture) {
  47049. return true;
  47050. }
  47051. if (this._reflectionTexture === texture) {
  47052. return true;
  47053. }
  47054. if (this._reflectivityTexture === texture) {
  47055. return true;
  47056. }
  47057. if (this._metallicTexture === texture) {
  47058. return true;
  47059. }
  47060. if (this._microSurfaceTexture === texture) {
  47061. return true;
  47062. }
  47063. if (this._bumpTexture === texture) {
  47064. return true;
  47065. }
  47066. if (this._lightmapTexture === texture) {
  47067. return true;
  47068. }
  47069. if (this._refractionTexture === texture) {
  47070. return true;
  47071. }
  47072. return false;
  47073. };
  47074. /**
  47075. * Makes a duplicate of the current material.
  47076. * @param name - name to use for the new material.
  47077. */
  47078. PBRMaterial.prototype.clone = function (name) {
  47079. var _this = this;
  47080. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  47081. clone.id = name;
  47082. clone.name = name;
  47083. return clone;
  47084. };
  47085. /**
  47086. * Serializes this PBR Material.
  47087. * @returns - An object with the serialized material.
  47088. */
  47089. PBRMaterial.prototype.serialize = function () {
  47090. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  47091. serializationObject.customType = "BABYLON.PBRMaterial";
  47092. return serializationObject;
  47093. };
  47094. // Statics
  47095. /**
  47096. * Parses a PBR Material from a serialized object.
  47097. * @param source - Serialized object.
  47098. * @param scene - BJS scene instance.
  47099. * @param rootUrl - url for the scene object
  47100. * @returns - PBRMaterial
  47101. */
  47102. PBRMaterial.Parse = function (source, scene, rootUrl) {
  47103. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  47104. };
  47105. /**
  47106. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  47107. */
  47108. PBRMaterial.PBRMATERIAL_OPAQUE = 0;
  47109. /**
  47110. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  47111. */
  47112. PBRMaterial.PBRMATERIAL_ALPHATEST = 1;
  47113. /**
  47114. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  47115. */
  47116. PBRMaterial.PBRMATERIAL_ALPHABLEND = 2;
  47117. /**
  47118. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  47119. * They are also discarded below the alpha cutoff threshold to improve performances.
  47120. */
  47121. PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND = 3;
  47122. /**
  47123. * Defines the default value of how much AO map is occluding the analytical lights
  47124. * (point spot...).
  47125. */
  47126. PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS = 1;
  47127. __decorate([
  47128. BABYLON.serialize(),
  47129. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47130. ], PBRMaterial.prototype, "directIntensity", void 0);
  47131. __decorate([
  47132. BABYLON.serialize(),
  47133. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47134. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  47135. __decorate([
  47136. BABYLON.serialize(),
  47137. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47138. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  47139. __decorate([
  47140. BABYLON.serialize(),
  47141. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47142. ], PBRMaterial.prototype, "specularIntensity", void 0);
  47143. __decorate([
  47144. BABYLON.serialize(),
  47145. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47146. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  47147. __decorate([
  47148. BABYLON.serializeAsTexture(),
  47149. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47150. ], PBRMaterial.prototype, "albedoTexture", void 0);
  47151. __decorate([
  47152. BABYLON.serializeAsTexture(),
  47153. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47154. ], PBRMaterial.prototype, "ambientTexture", void 0);
  47155. __decorate([
  47156. BABYLON.serialize(),
  47157. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47158. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  47159. __decorate([
  47160. BABYLON.serialize(),
  47161. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47162. ], PBRMaterial.prototype, "ambientTextureImpactOnAnalyticalLights", void 0);
  47163. __decorate([
  47164. BABYLON.serializeAsTexture(),
  47165. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  47166. ], PBRMaterial.prototype, "opacityTexture", void 0);
  47167. __decorate([
  47168. BABYLON.serializeAsTexture(),
  47169. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47170. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  47171. __decorate([
  47172. BABYLON.serializeAsTexture(),
  47173. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47174. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  47175. __decorate([
  47176. BABYLON.serializeAsTexture(),
  47177. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47178. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  47179. __decorate([
  47180. BABYLON.serializeAsTexture(),
  47181. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47182. ], PBRMaterial.prototype, "metallicTexture", void 0);
  47183. __decorate([
  47184. BABYLON.serialize(),
  47185. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47186. ], PBRMaterial.prototype, "metallic", void 0);
  47187. __decorate([
  47188. BABYLON.serialize(),
  47189. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47190. ], PBRMaterial.prototype, "roughness", void 0);
  47191. __decorate([
  47192. BABYLON.serializeAsTexture(),
  47193. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47194. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  47195. __decorate([
  47196. BABYLON.serializeAsTexture(),
  47197. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47198. ], PBRMaterial.prototype, "bumpTexture", void 0);
  47199. __decorate([
  47200. BABYLON.serializeAsTexture(),
  47201. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  47202. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  47203. __decorate([
  47204. BABYLON.serializeAsTexture(),
  47205. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47206. ], PBRMaterial.prototype, "refractionTexture", void 0);
  47207. __decorate([
  47208. BABYLON.serializeAsColor3("ambient"),
  47209. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47210. ], PBRMaterial.prototype, "ambientColor", void 0);
  47211. __decorate([
  47212. BABYLON.serializeAsColor3("albedo"),
  47213. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47214. ], PBRMaterial.prototype, "albedoColor", void 0);
  47215. __decorate([
  47216. BABYLON.serializeAsColor3("reflectivity"),
  47217. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47218. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  47219. __decorate([
  47220. BABYLON.serializeAsColor3("reflection"),
  47221. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47222. ], PBRMaterial.prototype, "reflectionColor", void 0);
  47223. __decorate([
  47224. BABYLON.serializeAsColor3("emissive"),
  47225. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47226. ], PBRMaterial.prototype, "emissiveColor", void 0);
  47227. __decorate([
  47228. BABYLON.serialize(),
  47229. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47230. ], PBRMaterial.prototype, "microSurface", void 0);
  47231. __decorate([
  47232. BABYLON.serialize(),
  47233. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47234. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  47235. __decorate([
  47236. BABYLON.serialize(),
  47237. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47238. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  47239. __decorate([
  47240. BABYLON.serialize(),
  47241. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47242. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  47243. __decorate([
  47244. BABYLON.serialize(),
  47245. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47246. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  47247. __decorate([
  47248. BABYLON.serialize(),
  47249. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  47250. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  47251. __decorate([
  47252. BABYLON.serialize(),
  47253. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  47254. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  47255. __decorate([
  47256. BABYLON.serialize(),
  47257. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  47258. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  47259. __decorate([
  47260. BABYLON.serialize(),
  47261. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47262. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  47263. __decorate([
  47264. BABYLON.serialize(),
  47265. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47266. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  47267. __decorate([
  47268. BABYLON.serialize(),
  47269. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47270. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  47271. __decorate([
  47272. BABYLON.serialize(),
  47273. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47274. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  47275. __decorate([
  47276. BABYLON.serialize(),
  47277. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47278. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  47279. __decorate([
  47280. BABYLON.serialize(),
  47281. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47282. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  47283. __decorate([
  47284. BABYLON.serialize(),
  47285. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47286. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  47287. __decorate([
  47288. BABYLON.serialize(),
  47289. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47290. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  47291. __decorate([
  47292. BABYLON.serialize()
  47293. ], PBRMaterial.prototype, "usePhysicalLightFalloff", null);
  47294. __decorate([
  47295. BABYLON.serialize()
  47296. ], PBRMaterial.prototype, "useGLTFLightFalloff", null);
  47297. __decorate([
  47298. BABYLON.serialize(),
  47299. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47300. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  47301. __decorate([
  47302. BABYLON.serialize(),
  47303. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47304. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  47305. __decorate([
  47306. BABYLON.serialize(),
  47307. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47308. ], PBRMaterial.prototype, "useParallax", void 0);
  47309. __decorate([
  47310. BABYLON.serialize(),
  47311. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47312. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  47313. __decorate([
  47314. BABYLON.serialize(),
  47315. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47316. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  47317. __decorate([
  47318. BABYLON.serialize(),
  47319. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  47320. ], PBRMaterial.prototype, "disableLighting", void 0);
  47321. __decorate([
  47322. BABYLON.serialize(),
  47323. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47324. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  47325. __decorate([
  47326. BABYLON.serialize(),
  47327. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  47328. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  47329. __decorate([
  47330. BABYLON.serialize(),
  47331. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47332. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  47333. __decorate([
  47334. BABYLON.serialize(),
  47335. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47336. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  47337. __decorate([
  47338. BABYLON.serialize(),
  47339. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47340. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  47341. __decorate([
  47342. BABYLON.serialize(),
  47343. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47344. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  47345. __decorate([
  47346. BABYLON.serialize(),
  47347. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47348. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  47349. __decorate([
  47350. BABYLON.serializeAsTexture(),
  47351. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47352. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  47353. __decorate([
  47354. BABYLON.serialize(),
  47355. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47356. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  47357. __decorate([
  47358. BABYLON.serialize(),
  47359. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47360. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  47361. __decorate([
  47362. BABYLON.serialize(),
  47363. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47364. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  47365. __decorate([
  47366. BABYLON.serialize(),
  47367. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47368. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  47369. __decorate([
  47370. BABYLON.serialize(),
  47371. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  47372. ], PBRMaterial.prototype, "unlit", void 0);
  47373. return PBRMaterial;
  47374. }(BABYLON.PBRBaseMaterial));
  47375. BABYLON.PBRMaterial = PBRMaterial;
  47376. })(BABYLON || (BABYLON = {}));
  47377. //# sourceMappingURL=babylon.pbrMaterial.js.map
  47378. var BABYLON;
  47379. (function (BABYLON) {
  47380. /**
  47381. * The PBR material of BJS following the metal roughness convention.
  47382. *
  47383. * This fits to the PBR convention in the GLTF definition:
  47384. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  47385. */
  47386. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  47387. __extends(PBRMetallicRoughnessMaterial, _super);
  47388. /**
  47389. * Instantiates a new PBRMetalRoughnessMaterial instance.
  47390. *
  47391. * @param name The material name
  47392. * @param scene The scene the material will be use in.
  47393. */
  47394. function PBRMetallicRoughnessMaterial(name, scene) {
  47395. var _this = _super.call(this, name, scene) || this;
  47396. _this._useRoughnessFromMetallicTextureAlpha = false;
  47397. _this._useRoughnessFromMetallicTextureGreen = true;
  47398. _this._useMetallnessFromMetallicTextureBlue = true;
  47399. _this.metallic = 1.0;
  47400. _this.roughness = 1.0;
  47401. return _this;
  47402. }
  47403. /**
  47404. * Return the currrent class name of the material.
  47405. */
  47406. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  47407. return "PBRMetallicRoughnessMaterial";
  47408. };
  47409. /**
  47410. * Return the active textures of the material.
  47411. */
  47412. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  47413. var activeTextures = _super.prototype.getActiveTextures.call(this);
  47414. if (this.baseTexture) {
  47415. activeTextures.push(this.baseTexture);
  47416. }
  47417. if (this.metallicRoughnessTexture) {
  47418. activeTextures.push(this.metallicRoughnessTexture);
  47419. }
  47420. return activeTextures;
  47421. };
  47422. /**
  47423. * Checks to see if a texture is used in the material.
  47424. * @param texture - Base texture to use.
  47425. * @returns - Boolean specifying if a texture is used in the material.
  47426. */
  47427. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  47428. if (_super.prototype.hasTexture.call(this, texture)) {
  47429. return true;
  47430. }
  47431. if (this.baseTexture === texture) {
  47432. return true;
  47433. }
  47434. if (this.metallicRoughnessTexture === texture) {
  47435. return true;
  47436. }
  47437. return false;
  47438. };
  47439. /**
  47440. * Makes a duplicate of the current material.
  47441. * @param name - name to use for the new material.
  47442. */
  47443. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  47444. var _this = this;
  47445. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  47446. clone.id = name;
  47447. clone.name = name;
  47448. return clone;
  47449. };
  47450. /**
  47451. * Serialize the material to a parsable JSON object.
  47452. */
  47453. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  47454. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  47455. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  47456. return serializationObject;
  47457. };
  47458. /**
  47459. * Parses a JSON object correponding to the serialize function.
  47460. */
  47461. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  47462. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  47463. };
  47464. __decorate([
  47465. BABYLON.serializeAsColor3(),
  47466. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  47467. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  47468. __decorate([
  47469. BABYLON.serializeAsTexture(),
  47470. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  47471. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  47472. __decorate([
  47473. BABYLON.serialize(),
  47474. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47475. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  47476. __decorate([
  47477. BABYLON.serialize(),
  47478. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47479. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  47480. __decorate([
  47481. BABYLON.serializeAsTexture(),
  47482. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  47483. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  47484. return PBRMetallicRoughnessMaterial;
  47485. }(BABYLON.PBRBaseSimpleMaterial));
  47486. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  47487. })(BABYLON || (BABYLON = {}));
  47488. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  47489. var BABYLON;
  47490. (function (BABYLON) {
  47491. /**
  47492. * The PBR material of BJS following the specular glossiness convention.
  47493. *
  47494. * This fits to the PBR convention in the GLTF definition:
  47495. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  47496. */
  47497. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  47498. __extends(PBRSpecularGlossinessMaterial, _super);
  47499. /**
  47500. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  47501. *
  47502. * @param name The material name
  47503. * @param scene The scene the material will be use in.
  47504. */
  47505. function PBRSpecularGlossinessMaterial(name, scene) {
  47506. var _this = _super.call(this, name, scene) || this;
  47507. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  47508. return _this;
  47509. }
  47510. /**
  47511. * Return the currrent class name of the material.
  47512. */
  47513. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  47514. return "PBRSpecularGlossinessMaterial";
  47515. };
  47516. /**
  47517. * Return the active textures of the material.
  47518. */
  47519. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  47520. var activeTextures = _super.prototype.getActiveTextures.call(this);
  47521. if (this.diffuseTexture) {
  47522. activeTextures.push(this.diffuseTexture);
  47523. }
  47524. if (this.specularGlossinessTexture) {
  47525. activeTextures.push(this.specularGlossinessTexture);
  47526. }
  47527. return activeTextures;
  47528. };
  47529. /**
  47530. * Checks to see if a texture is used in the material.
  47531. * @param texture - Base texture to use.
  47532. * @returns - Boolean specifying if a texture is used in the material.
  47533. */
  47534. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  47535. if (_super.prototype.hasTexture.call(this, texture)) {
  47536. return true;
  47537. }
  47538. if (this.diffuseTexture === texture) {
  47539. return true;
  47540. }
  47541. if (this.specularGlossinessTexture === texture) {
  47542. return true;
  47543. }
  47544. return false;
  47545. };
  47546. /**
  47547. * Makes a duplicate of the current material.
  47548. * @param name - name to use for the new material.
  47549. */
  47550. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  47551. var _this = this;
  47552. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  47553. clone.id = name;
  47554. clone.name = name;
  47555. return clone;
  47556. };
  47557. /**
  47558. * Serialize the material to a parsable JSON object.
  47559. */
  47560. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  47561. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  47562. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  47563. return serializationObject;
  47564. };
  47565. /**
  47566. * Parses a JSON object correponding to the serialize function.
  47567. */
  47568. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  47569. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  47570. };
  47571. __decorate([
  47572. BABYLON.serializeAsColor3("diffuse"),
  47573. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  47574. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  47575. __decorate([
  47576. BABYLON.serializeAsTexture(),
  47577. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  47578. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  47579. __decorate([
  47580. BABYLON.serializeAsColor3("specular"),
  47581. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  47582. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  47583. __decorate([
  47584. BABYLON.serialize(),
  47585. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  47586. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  47587. __decorate([
  47588. BABYLON.serializeAsTexture(),
  47589. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  47590. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  47591. return PBRSpecularGlossinessMaterial;
  47592. }(BABYLON.PBRBaseSimpleMaterial));
  47593. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  47594. })(BABYLON || (BABYLON = {}));
  47595. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  47596. var BABYLON;
  47597. (function (BABYLON) {
  47598. /**
  47599. * @ignore
  47600. * This is a list of all the different input types that are available in the application.
  47601. * Fo instance: ArcRotateCameraGamepadInput...
  47602. */
  47603. BABYLON.CameraInputTypes = {};
  47604. /**
  47605. * This represents the input manager used within a camera.
  47606. * It helps dealing with all the different kind of input attached to a camera.
  47607. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  47608. */
  47609. var CameraInputsManager = /** @class */ (function () {
  47610. /**
  47611. * Instantiate a new Camera Input Manager.
  47612. * @param camera Defines the camera the input manager blongs to
  47613. */
  47614. function CameraInputsManager(camera) {
  47615. this.attached = {};
  47616. this.camera = camera;
  47617. this.checkInputs = function () { };
  47618. }
  47619. /**
  47620. * Add an input method to a camera
  47621. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  47622. * @param input camera input method
  47623. */
  47624. CameraInputsManager.prototype.add = function (input) {
  47625. var type = input.getSimpleName();
  47626. if (this.attached[type]) {
  47627. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  47628. return;
  47629. }
  47630. this.attached[type] = input;
  47631. input.camera = this.camera;
  47632. //for checkInputs, we are dynamically creating a function
  47633. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  47634. if (input.checkInputs) {
  47635. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  47636. }
  47637. if (this.attachedElement) {
  47638. input.attachControl(this.attachedElement);
  47639. }
  47640. };
  47641. /**
  47642. * Remove a specific input method from a camera
  47643. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  47644. * @param inputToRemove camera input method
  47645. */
  47646. CameraInputsManager.prototype.remove = function (inputToRemove) {
  47647. for (var cam in this.attached) {
  47648. var input = this.attached[cam];
  47649. if (input === inputToRemove) {
  47650. input.detachControl(this.attachedElement);
  47651. input.camera = null;
  47652. delete this.attached[cam];
  47653. this.rebuildInputCheck();
  47654. }
  47655. }
  47656. };
  47657. /**
  47658. * Remove a specific input type from a camera
  47659. * example: camera.inputs.remove("ArcRotateCameraGamepadInput");
  47660. * @param inputType the type of the input to remove
  47661. */
  47662. CameraInputsManager.prototype.removeByType = function (inputType) {
  47663. for (var cam in this.attached) {
  47664. var input = this.attached[cam];
  47665. if (input.getClassName() === inputType) {
  47666. input.detachControl(this.attachedElement);
  47667. input.camera = null;
  47668. delete this.attached[cam];
  47669. this.rebuildInputCheck();
  47670. }
  47671. }
  47672. };
  47673. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  47674. var current = this.checkInputs;
  47675. return function () {
  47676. current();
  47677. fn();
  47678. };
  47679. };
  47680. /**
  47681. * Attach the input controls to the currently attached dom element to listen the events from.
  47682. * @param input Defines the input to attach
  47683. */
  47684. CameraInputsManager.prototype.attachInput = function (input) {
  47685. if (this.attachedElement) {
  47686. input.attachControl(this.attachedElement, this.noPreventDefault);
  47687. }
  47688. };
  47689. /**
  47690. * Attach the current manager inputs controls to a specific dom element to listen the events from.
  47691. * @param element Defines the dom element to collect the events from
  47692. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  47693. */
  47694. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  47695. if (noPreventDefault === void 0) { noPreventDefault = false; }
  47696. if (this.attachedElement) {
  47697. return;
  47698. }
  47699. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  47700. this.attachedElement = element;
  47701. this.noPreventDefault = noPreventDefault;
  47702. for (var cam in this.attached) {
  47703. this.attached[cam].attachControl(element, noPreventDefault);
  47704. }
  47705. };
  47706. /**
  47707. * Detach the current manager inputs controls from a specific dom element.
  47708. * @param element Defines the dom element to collect the events from
  47709. * @param disconnect Defines whether the input should be removed from the current list of attached inputs
  47710. */
  47711. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  47712. if (disconnect === void 0) { disconnect = false; }
  47713. if (this.attachedElement !== element) {
  47714. return;
  47715. }
  47716. for (var cam in this.attached) {
  47717. this.attached[cam].detachControl(element);
  47718. if (disconnect) {
  47719. this.attached[cam].camera = null;
  47720. }
  47721. }
  47722. this.attachedElement = null;
  47723. };
  47724. /**
  47725. * Rebuild the dynamic inputCheck function from the current list of
  47726. * defined inputs in the manager.
  47727. */
  47728. CameraInputsManager.prototype.rebuildInputCheck = function () {
  47729. this.checkInputs = function () { };
  47730. for (var cam in this.attached) {
  47731. var input = this.attached[cam];
  47732. if (input.checkInputs) {
  47733. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  47734. }
  47735. }
  47736. };
  47737. /**
  47738. * Remove all attached input methods from a camera
  47739. */
  47740. CameraInputsManager.prototype.clear = function () {
  47741. if (this.attachedElement) {
  47742. this.detachElement(this.attachedElement, true);
  47743. }
  47744. this.attached = {};
  47745. this.attachedElement = null;
  47746. this.checkInputs = function () { };
  47747. };
  47748. /**
  47749. * Serialize the current input manager attached to a camera.
  47750. * This ensures than once parsed,
  47751. * the input associated to the camera will be identical to the current ones
  47752. * @param serializedCamera Defines the camera serialization JSON the input serialization should write to
  47753. */
  47754. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  47755. var inputs = {};
  47756. for (var cam in this.attached) {
  47757. var input = this.attached[cam];
  47758. var res = BABYLON.SerializationHelper.Serialize(input);
  47759. inputs[input.getClassName()] = res;
  47760. }
  47761. serializedCamera.inputsmgr = inputs;
  47762. };
  47763. /**
  47764. * Parses an input manager serialized JSON to restore the previous list of inputs
  47765. * and states associated to a camera.
  47766. * @param parsedCamera Defines the JSON to parse
  47767. */
  47768. CameraInputsManager.prototype.parse = function (parsedCamera) {
  47769. var parsedInputs = parsedCamera.inputsmgr;
  47770. if (parsedInputs) {
  47771. this.clear();
  47772. for (var n in parsedInputs) {
  47773. var construct = BABYLON.CameraInputTypes[n];
  47774. if (construct) {
  47775. var parsedinput = parsedInputs[n];
  47776. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  47777. this.add(input);
  47778. }
  47779. }
  47780. }
  47781. else {
  47782. //2016-03-08 this part is for managing backward compatibility
  47783. for (var n in this.attached) {
  47784. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  47785. if (construct) {
  47786. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  47787. this.remove(this.attached[n]);
  47788. this.add(input);
  47789. }
  47790. }
  47791. }
  47792. };
  47793. return CameraInputsManager;
  47794. }());
  47795. BABYLON.CameraInputsManager = CameraInputsManager;
  47796. })(BABYLON || (BABYLON = {}));
  47797. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  47798. var BABYLON;
  47799. (function (BABYLON) {
  47800. /**
  47801. * A target camera takes a mesh or position as a target and continues to look at it while it moves.
  47802. * This is the base of the follow, arc rotate cameras and Free camera
  47803. * @see http://doc.babylonjs.com/features/cameras
  47804. */
  47805. var TargetCamera = /** @class */ (function (_super) {
  47806. __extends(TargetCamera, _super);
  47807. /**
  47808. * Instantiates a target camera that takes a meshor position as a target and continues to look at it while it moves.
  47809. * This is the base of the follow, arc rotate cameras and Free camera
  47810. * @see http://doc.babylonjs.com/features/cameras
  47811. * @param name Defines the name of the camera in the scene
  47812. * @param position Defines the start position of the camera in the scene
  47813. * @param scene Defines the scene the camera belongs to
  47814. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  47815. */
  47816. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  47817. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47818. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  47819. /**
  47820. * Define the current direction the camera is moving to
  47821. */
  47822. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  47823. /**
  47824. * Define the current rotation the camera is rotating to
  47825. */
  47826. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  47827. /**
  47828. * Define the current rotation of the camera
  47829. */
  47830. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  47831. /**
  47832. * Define the current speed of the camera
  47833. */
  47834. _this.speed = 2.0;
  47835. /**
  47836. * Add cconstraint to the camera to prevent it to move freely in all directions and
  47837. * around all axis.
  47838. */
  47839. _this.noRotationConstraint = false;
  47840. /**
  47841. * Define the current target of the camera as an object or a position.
  47842. */
  47843. _this.lockedTarget = null;
  47844. /** @hidden */
  47845. _this._currentTarget = BABYLON.Vector3.Zero();
  47846. /** @hidden */
  47847. _this._viewMatrix = BABYLON.Matrix.Zero();
  47848. /** @hidden */
  47849. _this._camMatrix = BABYLON.Matrix.Zero();
  47850. /** @hidden */
  47851. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  47852. /** @hidden */
  47853. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  47854. /** @hidden */
  47855. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  47856. /** @hidden */
  47857. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  47858. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  47859. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  47860. _this._defaultUp = BABYLON.Vector3.Up();
  47861. _this._cachedRotationZ = 0;
  47862. _this._cachedQuaternionRotationZ = 0;
  47863. return _this;
  47864. }
  47865. /**
  47866. * Gets the position in front of the camera at a given distance.
  47867. * @param distance The distance from the camera we want the position to be
  47868. * @returns the position
  47869. */
  47870. TargetCamera.prototype.getFrontPosition = function (distance) {
  47871. this.getWorldMatrix();
  47872. var direction = this.getTarget().subtract(this.position);
  47873. direction.normalize();
  47874. direction.scaleInPlace(distance);
  47875. return this.globalPosition.add(direction);
  47876. };
  47877. /** @hidden */
  47878. TargetCamera.prototype._getLockedTargetPosition = function () {
  47879. if (!this.lockedTarget) {
  47880. return null;
  47881. }
  47882. if (this.lockedTarget.absolutePosition) {
  47883. this.lockedTarget.computeWorldMatrix();
  47884. }
  47885. return this.lockedTarget.absolutePosition || this.lockedTarget;
  47886. };
  47887. /**
  47888. * Store current camera state of the camera (fov, position, rotation, etc..)
  47889. * @returns the camera
  47890. */
  47891. TargetCamera.prototype.storeState = function () {
  47892. this._storedPosition = this.position.clone();
  47893. this._storedRotation = this.rotation.clone();
  47894. if (this.rotationQuaternion) {
  47895. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  47896. }
  47897. return _super.prototype.storeState.call(this);
  47898. };
  47899. /**
  47900. * Restored camera state. You must call storeState() first
  47901. * @returns whether it was successful or not
  47902. * @hidden
  47903. */
  47904. TargetCamera.prototype._restoreStateValues = function () {
  47905. if (!_super.prototype._restoreStateValues.call(this)) {
  47906. return false;
  47907. }
  47908. this.position = this._storedPosition.clone();
  47909. this.rotation = this._storedRotation.clone();
  47910. if (this.rotationQuaternion) {
  47911. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  47912. }
  47913. this.cameraDirection.copyFromFloats(0, 0, 0);
  47914. this.cameraRotation.copyFromFloats(0, 0);
  47915. return true;
  47916. };
  47917. /** @hidden */
  47918. TargetCamera.prototype._initCache = function () {
  47919. _super.prototype._initCache.call(this);
  47920. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47921. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47922. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47923. };
  47924. /** @hidden */
  47925. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  47926. if (!ignoreParentClass) {
  47927. _super.prototype._updateCache.call(this);
  47928. }
  47929. var lockedTargetPosition = this._getLockedTargetPosition();
  47930. if (!lockedTargetPosition) {
  47931. this._cache.lockedTarget = null;
  47932. }
  47933. else {
  47934. if (!this._cache.lockedTarget) {
  47935. this._cache.lockedTarget = lockedTargetPosition.clone();
  47936. }
  47937. else {
  47938. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  47939. }
  47940. }
  47941. this._cache.rotation.copyFrom(this.rotation);
  47942. if (this.rotationQuaternion)
  47943. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47944. };
  47945. // Synchronized
  47946. /** @hidden */
  47947. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  47948. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  47949. return false;
  47950. }
  47951. var lockedTargetPosition = this._getLockedTargetPosition();
  47952. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  47953. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  47954. };
  47955. // Methods
  47956. /** @hidden */
  47957. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  47958. var engine = this.getEngine();
  47959. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  47960. };
  47961. // Target
  47962. /** @hidden */
  47963. TargetCamera.prototype.setTarget = function (target) {
  47964. this.upVector.normalize();
  47965. if (this.position.z === target.z) {
  47966. this.position.z += BABYLON.Epsilon;
  47967. }
  47968. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUp, this._camMatrix);
  47969. this._camMatrix.invert();
  47970. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  47971. var vDir = target.subtract(this.position);
  47972. if (vDir.x >= 0.0) {
  47973. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  47974. }
  47975. else {
  47976. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  47977. }
  47978. this.rotation.z = 0;
  47979. if (isNaN(this.rotation.x)) {
  47980. this.rotation.x = 0;
  47981. }
  47982. if (isNaN(this.rotation.y)) {
  47983. this.rotation.y = 0;
  47984. }
  47985. if (isNaN(this.rotation.z)) {
  47986. this.rotation.z = 0;
  47987. }
  47988. if (this.rotationQuaternion) {
  47989. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  47990. }
  47991. };
  47992. /**
  47993. * Return the current target position of the camera. This value is expressed in local space.
  47994. * @returns the target position
  47995. */
  47996. TargetCamera.prototype.getTarget = function () {
  47997. return this._currentTarget;
  47998. };
  47999. /** @hidden */
  48000. TargetCamera.prototype._decideIfNeedsToMove = function () {
  48001. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  48002. };
  48003. /** @hidden */
  48004. TargetCamera.prototype._updatePosition = function () {
  48005. if (this.parent) {
  48006. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  48007. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  48008. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  48009. return;
  48010. }
  48011. this.position.addInPlace(this.cameraDirection);
  48012. };
  48013. /** @hidden */
  48014. TargetCamera.prototype._checkInputs = function () {
  48015. var needToMove = this._decideIfNeedsToMove();
  48016. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  48017. // Move
  48018. if (needToMove) {
  48019. this._updatePosition();
  48020. }
  48021. // Rotate
  48022. if (needToRotate) {
  48023. this.rotation.x += this.cameraRotation.x;
  48024. this.rotation.y += this.cameraRotation.y;
  48025. //rotate, if quaternion is set and rotation was used
  48026. if (this.rotationQuaternion) {
  48027. var len = this.rotation.lengthSquared();
  48028. if (len) {
  48029. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  48030. }
  48031. }
  48032. if (!this.noRotationConstraint) {
  48033. var limit = (Math.PI / 2) * 0.95;
  48034. if (this.rotation.x > limit)
  48035. this.rotation.x = limit;
  48036. if (this.rotation.x < -limit)
  48037. this.rotation.x = -limit;
  48038. }
  48039. }
  48040. // Inertia
  48041. if (needToMove) {
  48042. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  48043. this.cameraDirection.x = 0;
  48044. }
  48045. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  48046. this.cameraDirection.y = 0;
  48047. }
  48048. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  48049. this.cameraDirection.z = 0;
  48050. }
  48051. this.cameraDirection.scaleInPlace(this.inertia);
  48052. }
  48053. if (needToRotate) {
  48054. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  48055. this.cameraRotation.x = 0;
  48056. }
  48057. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  48058. this.cameraRotation.y = 0;
  48059. }
  48060. this.cameraRotation.scaleInPlace(this.inertia);
  48061. }
  48062. _super.prototype._checkInputs.call(this);
  48063. };
  48064. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  48065. if (this.rotationQuaternion) {
  48066. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  48067. }
  48068. else {
  48069. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  48070. }
  48071. };
  48072. /**
  48073. * Update the up vector to apply the rotation of the camera (So if you changed the camera rotation.z this will let you update the up vector as well)
  48074. * @returns the current camera
  48075. */
  48076. TargetCamera.prototype._rotateUpVectorWithCameraRotationMatrix = function () {
  48077. BABYLON.Vector3.TransformNormalToRef(this._defaultUp, this._cameraRotationMatrix, this.upVector);
  48078. return this;
  48079. };
  48080. /** @hidden */
  48081. TargetCamera.prototype._getViewMatrix = function () {
  48082. if (this.lockedTarget) {
  48083. this.setTarget(this._getLockedTargetPosition());
  48084. }
  48085. // Compute
  48086. this._updateCameraRotationMatrix();
  48087. // Apply the changed rotation to the upVector
  48088. if (this.rotationQuaternion && this._cachedQuaternionRotationZ != this.rotationQuaternion.z) {
  48089. this._rotateUpVectorWithCameraRotationMatrix();
  48090. this._cachedQuaternionRotationZ = this.rotationQuaternion.z;
  48091. }
  48092. else if (this._cachedRotationZ != this.rotation.z) {
  48093. this._rotateUpVectorWithCameraRotationMatrix();
  48094. this._cachedRotationZ = this.rotation.z;
  48095. }
  48096. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  48097. // Computing target and final matrix
  48098. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  48099. this._computeViewMatrix(this.position, this._currentTarget, this.upVector);
  48100. return this._viewMatrix;
  48101. };
  48102. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  48103. if (this.parent) {
  48104. var parentWorldMatrix = this.parent.getWorldMatrix();
  48105. BABYLON.Vector3.TransformCoordinatesToRef(position, parentWorldMatrix, this._globalPosition);
  48106. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  48107. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  48108. this._markSyncedWithParent();
  48109. }
  48110. else {
  48111. this._globalPosition.copyFrom(position);
  48112. this._globalCurrentTarget.copyFrom(target);
  48113. this._globalCurrentUpVector.copyFrom(up);
  48114. }
  48115. if (this.getScene().useRightHandedSystem) {
  48116. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  48117. }
  48118. else {
  48119. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  48120. }
  48121. };
  48122. /**
  48123. * @hidden
  48124. */
  48125. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  48126. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  48127. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  48128. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  48129. if (!this.rotationQuaternion) {
  48130. this.rotationQuaternion = new BABYLON.Quaternion();
  48131. }
  48132. rigCamera._cameraRigParams = {};
  48133. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  48134. }
  48135. return rigCamera;
  48136. }
  48137. return null;
  48138. };
  48139. /**
  48140. * @hidden
  48141. */
  48142. TargetCamera.prototype._updateRigCameras = function () {
  48143. var camLeft = this._rigCameras[0];
  48144. var camRight = this._rigCameras[1];
  48145. switch (this.cameraRigMode) {
  48146. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48147. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48148. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48149. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48150. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  48151. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  48152. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  48153. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  48154. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  48155. camLeft.setTarget(this.getTarget());
  48156. camRight.setTarget(this.getTarget());
  48157. break;
  48158. case BABYLON.Camera.RIG_MODE_VR:
  48159. if (camLeft.rotationQuaternion) {
  48160. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  48161. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  48162. }
  48163. else {
  48164. camLeft.rotation.copyFrom(this.rotation);
  48165. camRight.rotation.copyFrom(this.rotation);
  48166. }
  48167. camLeft.position.copyFrom(this.position);
  48168. camRight.position.copyFrom(this.position);
  48169. break;
  48170. }
  48171. _super.prototype._updateRigCameras.call(this);
  48172. };
  48173. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  48174. if (!this._rigCamTransformMatrix) {
  48175. this._rigCamTransformMatrix = new BABYLON.Matrix();
  48176. }
  48177. var target = this.getTarget();
  48178. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  48179. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  48180. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  48181. };
  48182. /**
  48183. * Gets the current object class name.
  48184. * @return the class name
  48185. */
  48186. TargetCamera.prototype.getClassName = function () {
  48187. return "TargetCamera";
  48188. };
  48189. __decorate([
  48190. BABYLON.serializeAsVector3()
  48191. ], TargetCamera.prototype, "rotation", void 0);
  48192. __decorate([
  48193. BABYLON.serialize()
  48194. ], TargetCamera.prototype, "speed", void 0);
  48195. __decorate([
  48196. BABYLON.serializeAsMeshReference("lockedTargetId")
  48197. ], TargetCamera.prototype, "lockedTarget", void 0);
  48198. return TargetCamera;
  48199. }(BABYLON.Camera));
  48200. BABYLON.TargetCamera = TargetCamera;
  48201. })(BABYLON || (BABYLON = {}));
  48202. //# sourceMappingURL=babylon.targetCamera.js.map
  48203. var BABYLON;
  48204. (function (BABYLON) {
  48205. /**
  48206. * Manage the mouse inputs to control the movement of a free camera.
  48207. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48208. */
  48209. var FreeCameraMouseInput = /** @class */ (function () {
  48210. /**
  48211. * Manage the mouse inputs to control the movement of a free camera.
  48212. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48213. * @param touchEnabled Defines if touch is enabled or not
  48214. */
  48215. function FreeCameraMouseInput(
  48216. /**
  48217. * Define if touch is enabled in the mouse input
  48218. */
  48219. touchEnabled) {
  48220. if (touchEnabled === void 0) { touchEnabled = true; }
  48221. this.touchEnabled = touchEnabled;
  48222. /**
  48223. * Defines the buttons associated with the input to handle camera move.
  48224. */
  48225. this.buttons = [0, 1, 2];
  48226. /**
  48227. * Defines the pointer angular sensibility along the X and Y axis or how fast is the camera rotating.
  48228. */
  48229. this.angularSensibility = 2000.0;
  48230. this.previousPosition = null;
  48231. }
  48232. /**
  48233. * Attach the input controls to a specific dom element to get the input from.
  48234. * @param element Defines the element the controls should be listened from
  48235. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  48236. */
  48237. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  48238. var _this = this;
  48239. var engine = this.camera.getEngine();
  48240. if (!this._pointerInput) {
  48241. this._pointerInput = function (p, s) {
  48242. var evt = p.event;
  48243. if (engine.isInVRExclusivePointerMode) {
  48244. return;
  48245. }
  48246. if (!_this.touchEnabled && evt.pointerType === "touch") {
  48247. return;
  48248. }
  48249. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  48250. return;
  48251. }
  48252. var srcElement = (evt.srcElement || evt.target);
  48253. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  48254. try {
  48255. srcElement.setPointerCapture(evt.pointerId);
  48256. }
  48257. catch (e) {
  48258. //Nothing to do with the error. Execution will continue.
  48259. }
  48260. _this.previousPosition = {
  48261. x: evt.clientX,
  48262. y: evt.clientY
  48263. };
  48264. if (!noPreventDefault) {
  48265. evt.preventDefault();
  48266. element.focus();
  48267. }
  48268. }
  48269. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  48270. try {
  48271. srcElement.releasePointerCapture(evt.pointerId);
  48272. }
  48273. catch (e) {
  48274. //Nothing to do with the error.
  48275. }
  48276. _this.previousPosition = null;
  48277. if (!noPreventDefault) {
  48278. evt.preventDefault();
  48279. }
  48280. }
  48281. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  48282. if (!_this.previousPosition || engine.isPointerLock) {
  48283. return;
  48284. }
  48285. var offsetX = evt.clientX - _this.previousPosition.x;
  48286. if (_this.camera.getScene().useRightHandedSystem)
  48287. offsetX *= -1;
  48288. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  48289. offsetX *= -1;
  48290. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  48291. var offsetY = evt.clientY - _this.previousPosition.y;
  48292. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  48293. _this.previousPosition = {
  48294. x: evt.clientX,
  48295. y: evt.clientY
  48296. };
  48297. if (!noPreventDefault) {
  48298. evt.preventDefault();
  48299. }
  48300. }
  48301. };
  48302. }
  48303. this._onMouseMove = function (evt) {
  48304. if (!engine.isPointerLock) {
  48305. return;
  48306. }
  48307. if (engine.isInVRExclusivePointerMode) {
  48308. return;
  48309. }
  48310. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  48311. if (_this.camera.getScene().useRightHandedSystem)
  48312. offsetX *= -1;
  48313. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  48314. offsetX *= -1;
  48315. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  48316. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  48317. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  48318. _this.previousPosition = null;
  48319. if (!noPreventDefault) {
  48320. evt.preventDefault();
  48321. }
  48322. };
  48323. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  48324. element.addEventListener("mousemove", this._onMouseMove, false);
  48325. };
  48326. /**
  48327. * Detach the current controls from the specified dom element.
  48328. * @param element Defines the element to stop listening the inputs from
  48329. */
  48330. FreeCameraMouseInput.prototype.detachControl = function (element) {
  48331. if (this._observer && element) {
  48332. this.camera.getScene().onPointerObservable.remove(this._observer);
  48333. if (this._onMouseMove) {
  48334. element.removeEventListener("mousemove", this._onMouseMove);
  48335. }
  48336. this._observer = null;
  48337. this._onMouseMove = null;
  48338. this.previousPosition = null;
  48339. }
  48340. };
  48341. /**
  48342. * Gets the class name of the current intput.
  48343. * @returns the class name
  48344. */
  48345. FreeCameraMouseInput.prototype.getClassName = function () {
  48346. return "FreeCameraMouseInput";
  48347. };
  48348. /**
  48349. * Get the friendly name associated with the input class.
  48350. * @returns the input friendly name
  48351. */
  48352. FreeCameraMouseInput.prototype.getSimpleName = function () {
  48353. return "mouse";
  48354. };
  48355. __decorate([
  48356. BABYLON.serialize()
  48357. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  48358. __decorate([
  48359. BABYLON.serialize()
  48360. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  48361. return FreeCameraMouseInput;
  48362. }());
  48363. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  48364. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  48365. })(BABYLON || (BABYLON = {}));
  48366. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  48367. var BABYLON;
  48368. (function (BABYLON) {
  48369. /**
  48370. * Manage the keyboard inputs to control the movement of a free camera.
  48371. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48372. */
  48373. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  48374. function FreeCameraKeyboardMoveInput() {
  48375. /**
  48376. * Gets or Set the list of keyboard keys used to control the forward move of the camera.
  48377. */
  48378. this.keysUp = [38];
  48379. /**
  48380. * Gets or Set the list of keyboard keys used to control the backward move of the camera.
  48381. */
  48382. this.keysDown = [40];
  48383. /**
  48384. * Gets or Set the list of keyboard keys used to control the left strafe move of the camera.
  48385. */
  48386. this.keysLeft = [37];
  48387. /**
  48388. * Gets or Set the list of keyboard keys used to control the right strafe move of the camera.
  48389. */
  48390. this.keysRight = [39];
  48391. this._keys = new Array();
  48392. }
  48393. /**
  48394. * Attach the input controls to a specific dom element to get the input from.
  48395. * @param element Defines the element the controls should be listened from
  48396. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  48397. */
  48398. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  48399. var _this = this;
  48400. if (this._onCanvasBlurObserver) {
  48401. return;
  48402. }
  48403. this._scene = this.camera.getScene();
  48404. this._engine = this._scene.getEngine();
  48405. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  48406. _this._keys = [];
  48407. });
  48408. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  48409. var evt = info.event;
  48410. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  48411. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  48412. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  48413. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  48414. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  48415. var index = _this._keys.indexOf(evt.keyCode);
  48416. if (index === -1) {
  48417. _this._keys.push(evt.keyCode);
  48418. }
  48419. if (!noPreventDefault) {
  48420. evt.preventDefault();
  48421. }
  48422. }
  48423. }
  48424. else {
  48425. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  48426. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  48427. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  48428. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  48429. var index = _this._keys.indexOf(evt.keyCode);
  48430. if (index >= 0) {
  48431. _this._keys.splice(index, 1);
  48432. }
  48433. if (!noPreventDefault) {
  48434. evt.preventDefault();
  48435. }
  48436. }
  48437. }
  48438. });
  48439. };
  48440. /**
  48441. * Detach the current controls from the specified dom element.
  48442. * @param element Defines the element to stop listening the inputs from
  48443. */
  48444. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  48445. if (this._scene) {
  48446. if (this._onKeyboardObserver) {
  48447. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  48448. }
  48449. if (this._onCanvasBlurObserver) {
  48450. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  48451. }
  48452. this._onKeyboardObserver = null;
  48453. this._onCanvasBlurObserver = null;
  48454. }
  48455. this._keys = [];
  48456. };
  48457. /**
  48458. * Update the current camera state depending on the inputs that have been used this frame.
  48459. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  48460. */
  48461. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  48462. if (this._onKeyboardObserver) {
  48463. var camera = this.camera;
  48464. // Keyboard
  48465. for (var index = 0; index < this._keys.length; index++) {
  48466. var keyCode = this._keys[index];
  48467. var speed = camera._computeLocalCameraSpeed();
  48468. if (this.keysLeft.indexOf(keyCode) !== -1) {
  48469. camera._localDirection.copyFromFloats(-speed, 0, 0);
  48470. }
  48471. else if (this.keysUp.indexOf(keyCode) !== -1) {
  48472. camera._localDirection.copyFromFloats(0, 0, speed);
  48473. }
  48474. else if (this.keysRight.indexOf(keyCode) !== -1) {
  48475. camera._localDirection.copyFromFloats(speed, 0, 0);
  48476. }
  48477. else if (this.keysDown.indexOf(keyCode) !== -1) {
  48478. camera._localDirection.copyFromFloats(0, 0, -speed);
  48479. }
  48480. if (camera.getScene().useRightHandedSystem) {
  48481. camera._localDirection.z *= -1;
  48482. }
  48483. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  48484. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  48485. camera.cameraDirection.addInPlace(camera._transformedDirection);
  48486. }
  48487. }
  48488. };
  48489. /**
  48490. * Gets the class name of the current intput.
  48491. * @returns the class name
  48492. */
  48493. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  48494. return "FreeCameraKeyboardMoveInput";
  48495. };
  48496. /** @hidden */
  48497. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  48498. this._keys = [];
  48499. };
  48500. /**
  48501. * Get the friendly name associated with the input class.
  48502. * @returns the input friendly name
  48503. */
  48504. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  48505. return "keyboard";
  48506. };
  48507. __decorate([
  48508. BABYLON.serialize()
  48509. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  48510. __decorate([
  48511. BABYLON.serialize()
  48512. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  48513. __decorate([
  48514. BABYLON.serialize()
  48515. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  48516. __decorate([
  48517. BABYLON.serialize()
  48518. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  48519. return FreeCameraKeyboardMoveInput;
  48520. }());
  48521. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  48522. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  48523. })(BABYLON || (BABYLON = {}));
  48524. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  48525. var BABYLON;
  48526. (function (BABYLON) {
  48527. /**
  48528. * Default Inputs manager for the FreeCamera.
  48529. * It groups all the default supported inputs for ease of use.
  48530. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48531. */
  48532. var FreeCameraInputsManager = /** @class */ (function (_super) {
  48533. __extends(FreeCameraInputsManager, _super);
  48534. /**
  48535. * Instantiates a new FreeCameraInputsManager.
  48536. * @param camera Defines the camera the inputs belong to
  48537. */
  48538. function FreeCameraInputsManager(camera) {
  48539. return _super.call(this, camera) || this;
  48540. }
  48541. /**
  48542. * Add keyboard input support to the input manager.
  48543. * @returns the current input manager
  48544. */
  48545. FreeCameraInputsManager.prototype.addKeyboard = function () {
  48546. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  48547. return this;
  48548. };
  48549. /**
  48550. * Add mouse input support to the input manager.
  48551. * @param touchEnabled if the FreeCameraMouseInput should support touch (default: true)
  48552. * @returns the current input manager
  48553. */
  48554. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  48555. if (touchEnabled === void 0) { touchEnabled = true; }
  48556. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  48557. return this;
  48558. };
  48559. /**
  48560. * Add orientation input support to the input manager.
  48561. * @returns the current input manager
  48562. */
  48563. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  48564. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  48565. return this;
  48566. };
  48567. /**
  48568. * Add touch input support to the input manager.
  48569. * @returns the current input manager
  48570. */
  48571. FreeCameraInputsManager.prototype.addTouch = function () {
  48572. this.add(new BABYLON.FreeCameraTouchInput());
  48573. return this;
  48574. };
  48575. /**
  48576. * Add virtual joystick input support to the input manager.
  48577. * @returns the current input manager
  48578. */
  48579. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  48580. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  48581. return this;
  48582. };
  48583. return FreeCameraInputsManager;
  48584. }(BABYLON.CameraInputsManager));
  48585. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  48586. })(BABYLON || (BABYLON = {}));
  48587. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  48588. var BABYLON;
  48589. (function (BABYLON) {
  48590. BABYLON.Node.AddNodeConstructor("FreeCamera", function (name, scene) {
  48591. // Forcing to use the Universal camera
  48592. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  48593. });
  48594. /**
  48595. * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
  48596. * Please consider using the new UniversalCamera instead as it adds more functionality like the gamepad.
  48597. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  48598. */
  48599. var FreeCamera = /** @class */ (function (_super) {
  48600. __extends(FreeCamera, _super);
  48601. /**
  48602. * Instantiates a Free Camera.
  48603. * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
  48604. * Please consider using the new UniversalCamera instead as it adds more functionality like touch to this camera.
  48605. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  48606. * @param name Define the name of the camera in the scene
  48607. * @param position Define the start position of the camera in the scene
  48608. * @param scene Define the scene the camera belongs to
  48609. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  48610. */
  48611. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  48612. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  48613. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  48614. /**
  48615. * Define the collision ellipsoid of the camera.
  48616. * This is helpful to simulate a camera body like the player body around the camera
  48617. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#arcrotatecamera
  48618. */
  48619. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  48620. /**
  48621. * Define an offset for the position of the ellipsoid around the camera.
  48622. * This can be helpful to determine the center of the body near the gravity center of the body
  48623. * instead of its head.
  48624. */
  48625. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  48626. /**
  48627. * Enable or disable collisions of the camera with the rest of the scene objects.
  48628. */
  48629. _this.checkCollisions = false;
  48630. /**
  48631. * Enable or disable gravity on the camera.
  48632. */
  48633. _this.applyGravity = false;
  48634. _this._needMoveForGravity = false;
  48635. _this._oldPosition = BABYLON.Vector3.Zero();
  48636. _this._diffPosition = BABYLON.Vector3.Zero();
  48637. _this._newPosition = BABYLON.Vector3.Zero();
  48638. // Collisions
  48639. _this._collisionMask = -1;
  48640. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  48641. if (collidedMesh === void 0) { collidedMesh = null; }
  48642. //TODO move this to the collision coordinator!
  48643. if (_this.getScene().workerCollisions)
  48644. newPosition.multiplyInPlace(_this._collider._radius);
  48645. var updatePosition = function (newPos) {
  48646. _this._newPosition.copyFrom(newPos);
  48647. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  48648. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  48649. _this.position.addInPlace(_this._diffPosition);
  48650. if (_this.onCollide && collidedMesh) {
  48651. _this.onCollide(collidedMesh);
  48652. }
  48653. }
  48654. };
  48655. updatePosition(newPosition);
  48656. };
  48657. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  48658. _this.inputs.addKeyboard().addMouse();
  48659. return _this;
  48660. }
  48661. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  48662. /**
  48663. * Gets the input sensibility for a mouse input. (default is 2000.0)
  48664. * Higher values reduce sensitivity.
  48665. */
  48666. get: function () {
  48667. var mouse = this.inputs.attached["mouse"];
  48668. if (mouse)
  48669. return mouse.angularSensibility;
  48670. return 0;
  48671. },
  48672. /**
  48673. * Sets the input sensibility for a mouse input. (default is 2000.0)
  48674. * Higher values reduce sensitivity.
  48675. */
  48676. set: function (value) {
  48677. var mouse = this.inputs.attached["mouse"];
  48678. if (mouse)
  48679. mouse.angularSensibility = value;
  48680. },
  48681. enumerable: true,
  48682. configurable: true
  48683. });
  48684. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  48685. /**
  48686. * Gets or Set the list of keyboard keys used to control the forward move of the camera.
  48687. */
  48688. get: function () {
  48689. var keyboard = this.inputs.attached["keyboard"];
  48690. if (keyboard)
  48691. return keyboard.keysUp;
  48692. return [];
  48693. },
  48694. set: function (value) {
  48695. var keyboard = this.inputs.attached["keyboard"];
  48696. if (keyboard)
  48697. keyboard.keysUp = value;
  48698. },
  48699. enumerable: true,
  48700. configurable: true
  48701. });
  48702. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  48703. /**
  48704. * Gets or Set the list of keyboard keys used to control the backward move of the camera.
  48705. */
  48706. get: function () {
  48707. var keyboard = this.inputs.attached["keyboard"];
  48708. if (keyboard)
  48709. return keyboard.keysDown;
  48710. return [];
  48711. },
  48712. set: function (value) {
  48713. var keyboard = this.inputs.attached["keyboard"];
  48714. if (keyboard)
  48715. keyboard.keysDown = value;
  48716. },
  48717. enumerable: true,
  48718. configurable: true
  48719. });
  48720. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  48721. /**
  48722. * Gets or Set the list of keyboard keys used to control the left strafe move of the camera.
  48723. */
  48724. get: function () {
  48725. var keyboard = this.inputs.attached["keyboard"];
  48726. if (keyboard)
  48727. return keyboard.keysLeft;
  48728. return [];
  48729. },
  48730. set: function (value) {
  48731. var keyboard = this.inputs.attached["keyboard"];
  48732. if (keyboard)
  48733. keyboard.keysLeft = value;
  48734. },
  48735. enumerable: true,
  48736. configurable: true
  48737. });
  48738. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  48739. /**
  48740. * Gets or Set the list of keyboard keys used to control the right strafe move of the camera.
  48741. */
  48742. get: function () {
  48743. var keyboard = this.inputs.attached["keyboard"];
  48744. if (keyboard)
  48745. return keyboard.keysRight;
  48746. return [];
  48747. },
  48748. set: function (value) {
  48749. var keyboard = this.inputs.attached["keyboard"];
  48750. if (keyboard)
  48751. keyboard.keysRight = value;
  48752. },
  48753. enumerable: true,
  48754. configurable: true
  48755. });
  48756. /**
  48757. * Attached controls to the current camera.
  48758. * @param element Defines the element the controls should be listened from
  48759. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  48760. */
  48761. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  48762. this.inputs.attachElement(element, noPreventDefault);
  48763. };
  48764. /**
  48765. * Detach the current controls from the camera.
  48766. * The camera will stop reacting to inputs.
  48767. * @param element Defines the element to stop listening the inputs from
  48768. */
  48769. FreeCamera.prototype.detachControl = function (element) {
  48770. this.inputs.detachElement(element);
  48771. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  48772. this.cameraRotation = new BABYLON.Vector2(0, 0);
  48773. };
  48774. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  48775. /**
  48776. * Define a collision mask to limit the list of object the camera can collide with
  48777. */
  48778. get: function () {
  48779. return this._collisionMask;
  48780. },
  48781. set: function (mask) {
  48782. this._collisionMask = !isNaN(mask) ? mask : -1;
  48783. },
  48784. enumerable: true,
  48785. configurable: true
  48786. });
  48787. /** @hidden */
  48788. FreeCamera.prototype._collideWithWorld = function (displacement) {
  48789. var globalPosition;
  48790. if (this.parent) {
  48791. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  48792. }
  48793. else {
  48794. globalPosition = this.position;
  48795. }
  48796. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  48797. this._oldPosition.addInPlace(this.ellipsoidOffset);
  48798. if (!this._collider) {
  48799. this._collider = new BABYLON.Collider();
  48800. }
  48801. this._collider._radius = this.ellipsoid;
  48802. this._collider.collisionMask = this._collisionMask;
  48803. //no need for clone, as long as gravity is not on.
  48804. var actualDisplacement = displacement;
  48805. //add gravity to the direction to prevent the dual-collision checking
  48806. if (this.applyGravity) {
  48807. //this prevents mending with cameraDirection, a global variable of the free camera class.
  48808. actualDisplacement = displacement.add(this.getScene().gravity);
  48809. }
  48810. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  48811. };
  48812. /** @hidden */
  48813. FreeCamera.prototype._checkInputs = function () {
  48814. if (!this._localDirection) {
  48815. this._localDirection = BABYLON.Vector3.Zero();
  48816. this._transformedDirection = BABYLON.Vector3.Zero();
  48817. }
  48818. this.inputs.checkInputs();
  48819. _super.prototype._checkInputs.call(this);
  48820. };
  48821. /** @hidden */
  48822. FreeCamera.prototype._decideIfNeedsToMove = function () {
  48823. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  48824. };
  48825. /** @hidden */
  48826. FreeCamera.prototype._updatePosition = function () {
  48827. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  48828. this._collideWithWorld(this.cameraDirection);
  48829. }
  48830. else {
  48831. _super.prototype._updatePosition.call(this);
  48832. }
  48833. };
  48834. /**
  48835. * Destroy the camera and release the current resources hold by it.
  48836. */
  48837. FreeCamera.prototype.dispose = function () {
  48838. this.inputs.clear();
  48839. _super.prototype.dispose.call(this);
  48840. };
  48841. /**
  48842. * Gets the current object class name.
  48843. * @return the class name
  48844. */
  48845. FreeCamera.prototype.getClassName = function () {
  48846. return "FreeCamera";
  48847. };
  48848. __decorate([
  48849. BABYLON.serializeAsVector3()
  48850. ], FreeCamera.prototype, "ellipsoid", void 0);
  48851. __decorate([
  48852. BABYLON.serializeAsVector3()
  48853. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  48854. __decorate([
  48855. BABYLON.serialize()
  48856. ], FreeCamera.prototype, "checkCollisions", void 0);
  48857. __decorate([
  48858. BABYLON.serialize()
  48859. ], FreeCamera.prototype, "applyGravity", void 0);
  48860. return FreeCamera;
  48861. }(BABYLON.TargetCamera));
  48862. BABYLON.FreeCamera = FreeCamera;
  48863. })(BABYLON || (BABYLON = {}));
  48864. //# sourceMappingURL=babylon.freeCamera.js.map
  48865. var BABYLON;
  48866. (function (BABYLON) {
  48867. /**
  48868. * Manage the keyboard inputs to control the movement of an arc rotate camera.
  48869. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48870. */
  48871. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  48872. function ArcRotateCameraKeyboardMoveInput() {
  48873. /**
  48874. * Defines the list of key codes associated with the up action (increase alpha)
  48875. */
  48876. this.keysUp = [38];
  48877. /**
  48878. * Defines the list of key codes associated with the down action (decrease alpha)
  48879. */
  48880. this.keysDown = [40];
  48881. /**
  48882. * Defines the list of key codes associated with the left action (increase beta)
  48883. */
  48884. this.keysLeft = [37];
  48885. /**
  48886. * Defines the list of key codes associated with the right action (decrease beta)
  48887. */
  48888. this.keysRight = [39];
  48889. /**
  48890. * Defines the list of key codes associated with the reset action.
  48891. * Those keys reset the camera to its last stored state (with the method camera.storeState())
  48892. */
  48893. this.keysReset = [220];
  48894. /**
  48895. * Defines the panning sensibility of the inputs.
  48896. * (How fast is the camera paning)
  48897. */
  48898. this.panningSensibility = 50.0;
  48899. /**
  48900. * Defines the zooming sensibility of the inputs.
  48901. * (How fast is the camera zooming)
  48902. */
  48903. this.zoomingSensibility = 25.0;
  48904. /**
  48905. * Defines wether maintaining the alt key down switch the movement mode from
  48906. * orientation to zoom.
  48907. */
  48908. this.useAltToZoom = true;
  48909. /**
  48910. * Rotation speed of the camera
  48911. */
  48912. this.angularSpeed = 0.01;
  48913. this._keys = new Array();
  48914. }
  48915. /**
  48916. * Attach the input controls to a specific dom element to get the input from.
  48917. * @param element Defines the element the controls should be listened from
  48918. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  48919. */
  48920. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  48921. var _this = this;
  48922. if (this._onCanvasBlurObserver) {
  48923. return;
  48924. }
  48925. this._scene = this.camera.getScene();
  48926. this._engine = this._scene.getEngine();
  48927. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  48928. _this._keys = [];
  48929. });
  48930. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  48931. var evt = info.event;
  48932. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  48933. _this._ctrlPressed = evt.ctrlKey;
  48934. _this._altPressed = evt.altKey;
  48935. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  48936. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  48937. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  48938. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  48939. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  48940. var index = _this._keys.indexOf(evt.keyCode);
  48941. if (index === -1) {
  48942. _this._keys.push(evt.keyCode);
  48943. }
  48944. if (evt.preventDefault) {
  48945. if (!noPreventDefault) {
  48946. evt.preventDefault();
  48947. }
  48948. }
  48949. }
  48950. }
  48951. else {
  48952. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  48953. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  48954. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  48955. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  48956. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  48957. var index = _this._keys.indexOf(evt.keyCode);
  48958. if (index >= 0) {
  48959. _this._keys.splice(index, 1);
  48960. }
  48961. if (evt.preventDefault) {
  48962. if (!noPreventDefault) {
  48963. evt.preventDefault();
  48964. }
  48965. }
  48966. }
  48967. }
  48968. });
  48969. };
  48970. /**
  48971. * Detach the current controls from the specified dom element.
  48972. * @param element Defines the element to stop listening the inputs from
  48973. */
  48974. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  48975. if (this._scene) {
  48976. if (this._onKeyboardObserver) {
  48977. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  48978. }
  48979. if (this._onCanvasBlurObserver) {
  48980. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  48981. }
  48982. this._onKeyboardObserver = null;
  48983. this._onCanvasBlurObserver = null;
  48984. }
  48985. this._keys = [];
  48986. };
  48987. /**
  48988. * Update the current camera state depending on the inputs that have been used this frame.
  48989. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  48990. */
  48991. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  48992. if (this._onKeyboardObserver) {
  48993. var camera = this.camera;
  48994. for (var index = 0; index < this._keys.length; index++) {
  48995. var keyCode = this._keys[index];
  48996. if (this.keysLeft.indexOf(keyCode) !== -1) {
  48997. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48998. camera.inertialPanningX -= 1 / this.panningSensibility;
  48999. }
  49000. else {
  49001. camera.inertialAlphaOffset -= this.angularSpeed;
  49002. }
  49003. }
  49004. else if (this.keysUp.indexOf(keyCode) !== -1) {
  49005. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  49006. camera.inertialPanningY += 1 / this.panningSensibility;
  49007. }
  49008. else if (this._altPressed && this.useAltToZoom) {
  49009. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  49010. }
  49011. else {
  49012. camera.inertialBetaOffset -= this.angularSpeed;
  49013. }
  49014. }
  49015. else if (this.keysRight.indexOf(keyCode) !== -1) {
  49016. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  49017. camera.inertialPanningX += 1 / this.panningSensibility;
  49018. }
  49019. else {
  49020. camera.inertialAlphaOffset += this.angularSpeed;
  49021. }
  49022. }
  49023. else if (this.keysDown.indexOf(keyCode) !== -1) {
  49024. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  49025. camera.inertialPanningY -= 1 / this.panningSensibility;
  49026. }
  49027. else if (this._altPressed && this.useAltToZoom) {
  49028. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  49029. }
  49030. else {
  49031. camera.inertialBetaOffset += this.angularSpeed;
  49032. }
  49033. }
  49034. else if (this.keysReset.indexOf(keyCode) !== -1) {
  49035. if (camera.useInputToRestoreState) {
  49036. camera.restoreState();
  49037. }
  49038. }
  49039. }
  49040. }
  49041. };
  49042. /**
  49043. * Gets the class name of the current intput.
  49044. * @returns the class name
  49045. */
  49046. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  49047. return "ArcRotateCameraKeyboardMoveInput";
  49048. };
  49049. /**
  49050. * Get the friendly name associated with the input class.
  49051. * @returns the input friendly name
  49052. */
  49053. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  49054. return "keyboard";
  49055. };
  49056. __decorate([
  49057. BABYLON.serialize()
  49058. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  49059. __decorate([
  49060. BABYLON.serialize()
  49061. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  49062. __decorate([
  49063. BABYLON.serialize()
  49064. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  49065. __decorate([
  49066. BABYLON.serialize()
  49067. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  49068. __decorate([
  49069. BABYLON.serialize()
  49070. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  49071. __decorate([
  49072. BABYLON.serialize()
  49073. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  49074. __decorate([
  49075. BABYLON.serialize()
  49076. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  49077. __decorate([
  49078. BABYLON.serialize()
  49079. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  49080. __decorate([
  49081. BABYLON.serialize()
  49082. ], ArcRotateCameraKeyboardMoveInput.prototype, "angularSpeed", void 0);
  49083. return ArcRotateCameraKeyboardMoveInput;
  49084. }());
  49085. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  49086. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  49087. })(BABYLON || (BABYLON = {}));
  49088. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  49089. var BABYLON;
  49090. (function (BABYLON) {
  49091. /**
  49092. * Manage the mouse wheel inputs to control an arc rotate camera.
  49093. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  49094. */
  49095. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  49096. function ArcRotateCameraMouseWheelInput() {
  49097. /**
  49098. * Gets or Set the mouse wheel precision or how fast is the camera zooming.
  49099. */
  49100. this.wheelPrecision = 3.0;
  49101. /**
  49102. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  49103. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  49104. */
  49105. this.wheelDeltaPercentage = 0;
  49106. }
  49107. /**
  49108. * Attach the input controls to a specific dom element to get the input from.
  49109. * @param element Defines the element the controls should be listened from
  49110. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  49111. */
  49112. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  49113. var _this = this;
  49114. this._wheel = function (p, s) {
  49115. //sanity check - this should be a PointerWheel event.
  49116. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  49117. return;
  49118. var event = p.event;
  49119. var delta = 0;
  49120. if (event.wheelDelta) {
  49121. if (_this.wheelDeltaPercentage) {
  49122. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  49123. if (event.wheelDelta > 0) {
  49124. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  49125. }
  49126. else {
  49127. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  49128. }
  49129. }
  49130. else {
  49131. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  49132. }
  49133. }
  49134. else if (event.detail) {
  49135. delta = -event.detail / _this.wheelPrecision;
  49136. }
  49137. if (delta)
  49138. _this.camera.inertialRadiusOffset += delta;
  49139. if (event.preventDefault) {
  49140. if (!noPreventDefault) {
  49141. event.preventDefault();
  49142. }
  49143. }
  49144. };
  49145. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  49146. };
  49147. /**
  49148. * Detach the current controls from the specified dom element.
  49149. * @param element Defines the element to stop listening the inputs from
  49150. */
  49151. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  49152. if (this._observer && element) {
  49153. this.camera.getScene().onPointerObservable.remove(this._observer);
  49154. this._observer = null;
  49155. this._wheel = null;
  49156. }
  49157. };
  49158. /**
  49159. * Gets the class name of the current intput.
  49160. * @returns the class name
  49161. */
  49162. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  49163. return "ArcRotateCameraMouseWheelInput";
  49164. };
  49165. /**
  49166. * Get the friendly name associated with the input class.
  49167. * @returns the input friendly name
  49168. */
  49169. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  49170. return "mousewheel";
  49171. };
  49172. __decorate([
  49173. BABYLON.serialize()
  49174. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  49175. __decorate([
  49176. BABYLON.serialize()
  49177. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  49178. return ArcRotateCameraMouseWheelInput;
  49179. }());
  49180. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  49181. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  49182. })(BABYLON || (BABYLON = {}));
  49183. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  49184. var BABYLON;
  49185. (function (BABYLON) {
  49186. /**
  49187. * Manage the pointers inputs to control an arc rotate camera.
  49188. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  49189. */
  49190. var ArcRotateCameraPointersInput = /** @class */ (function () {
  49191. function ArcRotateCameraPointersInput() {
  49192. /**
  49193. * Defines the buttons associated with the input to handle camera move.
  49194. */
  49195. this.buttons = [0, 1, 2];
  49196. /**
  49197. * Defines the pointer angular sensibility along the X axis or how fast is the camera rotating.
  49198. */
  49199. this.angularSensibilityX = 1000.0;
  49200. /**
  49201. * Defines the pointer angular sensibility along the Y axis or how fast is the camera rotating.
  49202. */
  49203. this.angularSensibilityY = 1000.0;
  49204. /**
  49205. * Defines the pointer pinch precision or how fast is the camera zooming.
  49206. */
  49207. this.pinchPrecision = 12.0;
  49208. /**
  49209. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  49210. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  49211. */
  49212. this.pinchDeltaPercentage = 0;
  49213. /**
  49214. * Defines the pointer panning sensibility or how fast is the camera moving.
  49215. */
  49216. this.panningSensibility = 1000.0;
  49217. /**
  49218. * Defines whether panning (2 fingers swipe) is enabled through multitouch.
  49219. */
  49220. this.multiTouchPanning = true;
  49221. /**
  49222. * Defines whether panning is enabled for both pan (2 fingers swipe) and zoom (pinch) through multitouch.
  49223. */
  49224. this.multiTouchPanAndZoom = true;
  49225. /**
  49226. * Revers pinch action direction.
  49227. */
  49228. this.pinchInwards = true;
  49229. this._isPanClick = false;
  49230. }
  49231. /**
  49232. * Attach the input controls to a specific dom element to get the input from.
  49233. * @param element Defines the element the controls should be listened from
  49234. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  49235. */
  49236. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  49237. var _this = this;
  49238. var engine = this.camera.getEngine();
  49239. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  49240. var pointA = null;
  49241. var pointB = null;
  49242. var previousPinchSquaredDistance = 0;
  49243. var initialDistance = 0;
  49244. var twoFingerActivityCount = 0;
  49245. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  49246. this._pointerInput = function (p, s) {
  49247. var evt = p.event;
  49248. var isTouch = p.event.pointerType === "touch";
  49249. if (engine.isInVRExclusivePointerMode) {
  49250. return;
  49251. }
  49252. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  49253. return;
  49254. }
  49255. var srcElement = (evt.srcElement || evt.target);
  49256. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  49257. try {
  49258. srcElement.setPointerCapture(evt.pointerId);
  49259. }
  49260. catch (e) {
  49261. //Nothing to do with the error. Execution will continue.
  49262. }
  49263. // Manage panning with pan button click
  49264. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  49265. // manage pointers
  49266. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  49267. if (pointA === null) {
  49268. pointA = cacheSoloPointer;
  49269. }
  49270. else if (pointB === null) {
  49271. pointB = cacheSoloPointer;
  49272. }
  49273. if (!noPreventDefault) {
  49274. evt.preventDefault();
  49275. element.focus();
  49276. }
  49277. }
  49278. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  49279. if (_this.camera.useInputToRestoreState) {
  49280. _this.camera.restoreState();
  49281. }
  49282. }
  49283. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  49284. try {
  49285. srcElement.releasePointerCapture(evt.pointerId);
  49286. }
  49287. catch (e) {
  49288. //Nothing to do with the error.
  49289. }
  49290. cacheSoloPointer = null;
  49291. previousPinchSquaredDistance = 0;
  49292. previousMultiTouchPanPosition.isPaning = false;
  49293. previousMultiTouchPanPosition.isPinching = false;
  49294. twoFingerActivityCount = 0;
  49295. initialDistance = 0;
  49296. if (!isTouch) {
  49297. pointB = null; // Mouse and pen are mono pointer
  49298. }
  49299. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  49300. //but emptying completly pointers collection is required to fix a bug on iPhone :
  49301. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  49302. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  49303. if (engine._badOS) {
  49304. pointA = pointB = null;
  49305. }
  49306. else {
  49307. //only remove the impacted pointer in case of multitouch allowing on most
  49308. //platforms switching from rotate to zoom and pan seamlessly.
  49309. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  49310. pointA = pointB;
  49311. pointB = null;
  49312. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  49313. }
  49314. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  49315. pointB = null;
  49316. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  49317. }
  49318. else {
  49319. pointA = pointB = null;
  49320. }
  49321. }
  49322. if (!noPreventDefault) {
  49323. evt.preventDefault();
  49324. }
  49325. }
  49326. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  49327. if (!noPreventDefault) {
  49328. evt.preventDefault();
  49329. }
  49330. // One button down
  49331. if (pointA && pointB === null && cacheSoloPointer) {
  49332. if (_this.panningSensibility !== 0 &&
  49333. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  49334. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  49335. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  49336. }
  49337. else {
  49338. var offsetX = evt.clientX - cacheSoloPointer.x;
  49339. var offsetY = evt.clientY - cacheSoloPointer.y;
  49340. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  49341. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  49342. }
  49343. cacheSoloPointer.x = evt.clientX;
  49344. cacheSoloPointer.y = evt.clientY;
  49345. }
  49346. // Two buttons down: pinch/pan
  49347. else if (pointA && pointB) {
  49348. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  49349. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  49350. ed.x = evt.clientX;
  49351. ed.y = evt.clientY;
  49352. var direction = _this.pinchInwards ? 1 : -1;
  49353. var distX = pointA.x - pointB.x;
  49354. var distY = pointA.y - pointB.y;
  49355. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  49356. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  49357. if (previousPinchSquaredDistance === 0) {
  49358. initialDistance = pinchDistance;
  49359. previousPinchSquaredDistance = pinchSquaredDistance;
  49360. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  49361. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  49362. return;
  49363. }
  49364. if (_this.multiTouchPanAndZoom) {
  49365. if (_this.pinchDeltaPercentage) {
  49366. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  49367. }
  49368. else {
  49369. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  49370. (_this.pinchPrecision *
  49371. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  49372. direction);
  49373. }
  49374. if (_this.panningSensibility !== 0) {
  49375. var pointersCenterX = (pointA.x + pointB.x) / 2;
  49376. var pointersCenterY = (pointA.y + pointB.y) / 2;
  49377. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  49378. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  49379. previousMultiTouchPanPosition.x = pointersCenterX;
  49380. previousMultiTouchPanPosition.y = pointersCenterY;
  49381. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  49382. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  49383. }
  49384. }
  49385. else {
  49386. twoFingerActivityCount++;
  49387. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  49388. if (_this.pinchDeltaPercentage) {
  49389. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  49390. }
  49391. else {
  49392. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  49393. (_this.pinchPrecision *
  49394. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  49395. direction);
  49396. }
  49397. previousMultiTouchPanPosition.isPaning = false;
  49398. previousMultiTouchPanPosition.isPinching = true;
  49399. }
  49400. else {
  49401. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  49402. if (!previousMultiTouchPanPosition.isPaning) {
  49403. previousMultiTouchPanPosition.isPaning = true;
  49404. previousMultiTouchPanPosition.isPinching = false;
  49405. previousMultiTouchPanPosition.x = ed.x;
  49406. previousMultiTouchPanPosition.y = ed.y;
  49407. return;
  49408. }
  49409. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  49410. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  49411. }
  49412. }
  49413. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  49414. previousMultiTouchPanPosition.x = ed.x;
  49415. previousMultiTouchPanPosition.y = ed.y;
  49416. }
  49417. }
  49418. previousPinchSquaredDistance = pinchSquaredDistance;
  49419. }
  49420. }
  49421. };
  49422. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  49423. this._onContextMenu = function (evt) {
  49424. evt.preventDefault();
  49425. };
  49426. if (!this.camera._useCtrlForPanning) {
  49427. element.addEventListener("contextmenu", this._onContextMenu, false);
  49428. }
  49429. this._onLostFocus = function () {
  49430. //this._keys = [];
  49431. pointA = pointB = null;
  49432. previousPinchSquaredDistance = 0;
  49433. previousMultiTouchPanPosition.isPaning = false;
  49434. previousMultiTouchPanPosition.isPinching = false;
  49435. twoFingerActivityCount = 0;
  49436. cacheSoloPointer = null;
  49437. initialDistance = 0;
  49438. };
  49439. this._onMouseMove = function (evt) {
  49440. if (!engine.isPointerLock) {
  49441. return;
  49442. }
  49443. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  49444. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  49445. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  49446. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  49447. if (!noPreventDefault) {
  49448. evt.preventDefault();
  49449. }
  49450. };
  49451. this._onGestureStart = function (e) {
  49452. if (window.MSGesture === undefined) {
  49453. return;
  49454. }
  49455. if (!_this._MSGestureHandler) {
  49456. _this._MSGestureHandler = new MSGesture();
  49457. _this._MSGestureHandler.target = element;
  49458. }
  49459. _this._MSGestureHandler.addPointer(e.pointerId);
  49460. };
  49461. this._onGesture = function (e) {
  49462. _this.camera.radius *= e.scale;
  49463. if (e.preventDefault) {
  49464. if (!noPreventDefault) {
  49465. e.stopPropagation();
  49466. e.preventDefault();
  49467. }
  49468. }
  49469. };
  49470. element.addEventListener("mousemove", this._onMouseMove, false);
  49471. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  49472. element.addEventListener("MSGestureChange", this._onGesture, false);
  49473. BABYLON.Tools.RegisterTopRootEvents([
  49474. { name: "blur", handler: this._onLostFocus }
  49475. ]);
  49476. };
  49477. /**
  49478. * Detach the current controls from the specified dom element.
  49479. * @param element Defines the element to stop listening the inputs from
  49480. */
  49481. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  49482. if (this._onLostFocus) {
  49483. BABYLON.Tools.UnregisterTopRootEvents([
  49484. { name: "blur", handler: this._onLostFocus }
  49485. ]);
  49486. }
  49487. if (element && this._observer) {
  49488. this.camera.getScene().onPointerObservable.remove(this._observer);
  49489. this._observer = null;
  49490. if (this._onContextMenu) {
  49491. element.removeEventListener("contextmenu", this._onContextMenu);
  49492. }
  49493. if (this._onMouseMove) {
  49494. element.removeEventListener("mousemove", this._onMouseMove);
  49495. }
  49496. if (this._onGestureStart) {
  49497. element.removeEventListener("MSPointerDown", this._onGestureStart);
  49498. }
  49499. if (this._onGesture) {
  49500. element.removeEventListener("MSGestureChange", this._onGesture);
  49501. }
  49502. this._isPanClick = false;
  49503. this.pinchInwards = true;
  49504. this._onMouseMove = null;
  49505. this._onGestureStart = null;
  49506. this._onGesture = null;
  49507. this._MSGestureHandler = null;
  49508. this._onLostFocus = null;
  49509. this._onContextMenu = null;
  49510. }
  49511. };
  49512. /**
  49513. * Gets the class name of the current intput.
  49514. * @returns the class name
  49515. */
  49516. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  49517. return "ArcRotateCameraPointersInput";
  49518. };
  49519. /**
  49520. * Get the friendly name associated with the input class.
  49521. * @returns the input friendly name
  49522. */
  49523. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  49524. return "pointers";
  49525. };
  49526. __decorate([
  49527. BABYLON.serialize()
  49528. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  49529. __decorate([
  49530. BABYLON.serialize()
  49531. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  49532. __decorate([
  49533. BABYLON.serialize()
  49534. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  49535. __decorate([
  49536. BABYLON.serialize()
  49537. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  49538. __decorate([
  49539. BABYLON.serialize()
  49540. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  49541. __decorate([
  49542. BABYLON.serialize()
  49543. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  49544. __decorate([
  49545. BABYLON.serialize()
  49546. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  49547. __decorate([
  49548. BABYLON.serialize()
  49549. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  49550. return ArcRotateCameraPointersInput;
  49551. }());
  49552. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  49553. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  49554. })(BABYLON || (BABYLON = {}));
  49555. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  49556. var BABYLON;
  49557. (function (BABYLON) {
  49558. /**
  49559. * Default Inputs manager for the ArcRotateCamera.
  49560. * It groups all the default supported inputs for ease of use.
  49561. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  49562. */
  49563. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  49564. __extends(ArcRotateCameraInputsManager, _super);
  49565. /**
  49566. * Instantiates a new ArcRotateCameraInputsManager.
  49567. * @param camera Defines the camera the inputs belong to
  49568. */
  49569. function ArcRotateCameraInputsManager(camera) {
  49570. return _super.call(this, camera) || this;
  49571. }
  49572. /**
  49573. * Add mouse wheel input support to the input manager.
  49574. * @returns the current input manager
  49575. */
  49576. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  49577. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  49578. return this;
  49579. };
  49580. /**
  49581. * Add pointers input support to the input manager.
  49582. * @returns the current input manager
  49583. */
  49584. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  49585. this.add(new BABYLON.ArcRotateCameraPointersInput());
  49586. return this;
  49587. };
  49588. /**
  49589. * Add keyboard input support to the input manager.
  49590. * @returns the current input manager
  49591. */
  49592. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  49593. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  49594. return this;
  49595. };
  49596. /**
  49597. * Add orientation input support to the input manager.
  49598. * @returns the current input manager
  49599. */
  49600. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  49601. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  49602. return this;
  49603. };
  49604. return ArcRotateCameraInputsManager;
  49605. }(BABYLON.CameraInputsManager));
  49606. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  49607. })(BABYLON || (BABYLON = {}));
  49608. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  49609. var BABYLON;
  49610. (function (BABYLON) {
  49611. BABYLON.Node.AddNodeConstructor("ArcRotateCamera", function (name, scene) {
  49612. return function () { return new ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  49613. });
  49614. /**
  49615. * This represents an orbital type of camera.
  49616. *
  49617. * This camera always points towards a given target position and can be rotated around that target with the target as the centre of rotation. It can be controlled with cursors and mouse, or with touch events.
  49618. * Think of this camera as one orbiting its target position, or more imaginatively as a spy satellite orbiting the earth. Its position relative to the target (earth) can be set by three parameters, alpha (radians) the longitudinal rotation, beta (radians) the latitudinal rotation and radius the distance from the target position.
  49619. * @see http://doc.babylonjs.com/babylon101/cameras#arc-rotate-camera
  49620. */
  49621. var ArcRotateCamera = /** @class */ (function (_super) {
  49622. __extends(ArcRotateCamera, _super);
  49623. /**
  49624. * Instantiates a new ArcRotateCamera in a given scene
  49625. * @param name Defines the name of the camera
  49626. * @param alpha Defines the camera rotation along the logitudinal axis
  49627. * @param beta Defines the camera rotation along the latitudinal axis
  49628. * @param radius Defines the camera distance from its target
  49629. * @param target Defines the camera target
  49630. * @param scene Defines the scene the camera belongs to
  49631. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  49632. */
  49633. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  49634. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  49635. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  49636. /**
  49637. * Current inertia value on the longitudinal axis.
  49638. * The bigger this number the longer it will take for the camera to stop.
  49639. */
  49640. _this.inertialAlphaOffset = 0;
  49641. /**
  49642. * Current inertia value on the latitudinal axis.
  49643. * The bigger this number the longer it will take for the camera to stop.
  49644. */
  49645. _this.inertialBetaOffset = 0;
  49646. /**
  49647. * Current inertia value on the radius axis.
  49648. * The bigger this number the longer it will take for the camera to stop.
  49649. */
  49650. _this.inertialRadiusOffset = 0;
  49651. /**
  49652. * Minimum allowed angle on the longitudinal axis.
  49653. * This can help limiting how the Camera is able to move in the scene.
  49654. */
  49655. _this.lowerAlphaLimit = null;
  49656. /**
  49657. * Maximum allowed angle on the longitudinal axis.
  49658. * This can help limiting how the Camera is able to move in the scene.
  49659. */
  49660. _this.upperAlphaLimit = null;
  49661. /**
  49662. * Minimum allowed angle on the latitudinal axis.
  49663. * This can help limiting how the Camera is able to move in the scene.
  49664. */
  49665. _this.lowerBetaLimit = 0.01;
  49666. /**
  49667. * Maximum allowed angle on the latitudinal axis.
  49668. * This can help limiting how the Camera is able to move in the scene.
  49669. */
  49670. _this.upperBetaLimit = Math.PI;
  49671. /**
  49672. * Minimum allowed distance of the camera to the target (The camera can not get closer).
  49673. * This can help limiting how the Camera is able to move in the scene.
  49674. */
  49675. _this.lowerRadiusLimit = null;
  49676. /**
  49677. * Maximum allowed distance of the camera to the target (The camera can not get further).
  49678. * This can help limiting how the Camera is able to move in the scene.
  49679. */
  49680. _this.upperRadiusLimit = null;
  49681. /**
  49682. * Defines the current inertia value used during panning of the camera along the X axis.
  49683. */
  49684. _this.inertialPanningX = 0;
  49685. /**
  49686. * Defines the current inertia value used during panning of the camera along the Y axis.
  49687. */
  49688. _this.inertialPanningY = 0;
  49689. /**
  49690. * Defines the distance used to consider the camera in pan mode vs pinch/zoom.
  49691. * Basically if your fingers moves away from more than this distance you will be considered
  49692. * in pinch mode.
  49693. */
  49694. _this.pinchToPanMaxDistance = 20;
  49695. /**
  49696. * Defines the maximum distance the camera can pan.
  49697. * This could help keeping the cammera always in your scene.
  49698. */
  49699. _this.panningDistanceLimit = null;
  49700. /**
  49701. * Defines the target of the camera before paning.
  49702. */
  49703. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  49704. /**
  49705. * Defines the value of the inertia used during panning.
  49706. * 0 would mean stop inertia and one would mean no decelleration at all.
  49707. */
  49708. _this.panningInertia = 0.9;
  49709. //-- end properties for backward compatibility for inputs
  49710. /**
  49711. * Defines how much the radius should be scaled while zomming on a particular mesh (through the zoomOn function)
  49712. */
  49713. _this.zoomOnFactor = 1;
  49714. /**
  49715. * Defines a screen offset for the camera position.
  49716. */
  49717. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  49718. /**
  49719. * Allows the camera to be completely reversed.
  49720. * If false the camera can not arrive upside down.
  49721. */
  49722. _this.allowUpsideDown = true;
  49723. /**
  49724. * Define if double tap/click is used to restore the previously saved state of the camera.
  49725. */
  49726. _this.useInputToRestoreState = true;
  49727. /** @hidden */
  49728. _this._viewMatrix = new BABYLON.Matrix();
  49729. /**
  49730. * Defines the allowed panning axis.
  49731. */
  49732. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  49733. /**
  49734. * Observable triggered when the mesh target has been changed on the camera.
  49735. */
  49736. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  49737. /**
  49738. * Defines whether the camera should check collision with the objects oh the scene.
  49739. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#how-can-i-do-this
  49740. */
  49741. _this.checkCollisions = false;
  49742. /**
  49743. * Defines the collision radius of the camera.
  49744. * This simulates a sphere around the camera.
  49745. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#arcrotatecamera
  49746. */
  49747. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  49748. _this._previousPosition = BABYLON.Vector3.Zero();
  49749. _this._collisionVelocity = BABYLON.Vector3.Zero();
  49750. _this._newPosition = BABYLON.Vector3.Zero();
  49751. _this._computationVector = BABYLON.Vector3.Zero();
  49752. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  49753. if (collidedMesh === void 0) { collidedMesh = null; }
  49754. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  49755. newPosition.multiplyInPlace(_this._collider._radius);
  49756. }
  49757. if (!collidedMesh) {
  49758. _this._previousPosition.copyFrom(_this.position);
  49759. }
  49760. else {
  49761. _this.setPosition(newPosition);
  49762. if (_this.onCollide) {
  49763. _this.onCollide(collidedMesh);
  49764. }
  49765. }
  49766. // Recompute because of constraints
  49767. var cosa = Math.cos(_this.alpha);
  49768. var sina = Math.sin(_this.alpha);
  49769. var cosb = Math.cos(_this.beta);
  49770. var sinb = Math.sin(_this.beta);
  49771. if (sinb === 0) {
  49772. sinb = 0.0001;
  49773. }
  49774. var target = _this._getTargetPosition();
  49775. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  49776. target.addToRef(_this._computationVector, _this._newPosition);
  49777. _this.position.copyFrom(_this._newPosition);
  49778. var up = _this.upVector;
  49779. if (_this.allowUpsideDown && _this.beta < 0) {
  49780. up = up.clone();
  49781. up = up.negate();
  49782. }
  49783. _this._computeViewMatrix(_this.position, target, up);
  49784. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  49785. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  49786. _this._collisionTriggered = false;
  49787. };
  49788. _this._target = BABYLON.Vector3.Zero();
  49789. if (target) {
  49790. _this.setTarget(target);
  49791. }
  49792. _this.alpha = alpha;
  49793. _this.beta = beta;
  49794. _this.radius = radius;
  49795. _this.getViewMatrix();
  49796. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  49797. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  49798. return _this;
  49799. }
  49800. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  49801. /**
  49802. * Defines the target point of the camera.
  49803. * The camera looks towards it form the radius distance.
  49804. */
  49805. get: function () {
  49806. return this._target;
  49807. },
  49808. set: function (value) {
  49809. this.setTarget(value);
  49810. },
  49811. enumerable: true,
  49812. configurable: true
  49813. });
  49814. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  49815. //-- begin properties for backward compatibility for inputs
  49816. /**
  49817. * Gets or Set the pointer angular sensibility along the X axis or how fast is the camera rotating.
  49818. */
  49819. get: function () {
  49820. var pointers = this.inputs.attached["pointers"];
  49821. if (pointers)
  49822. return pointers.angularSensibilityX;
  49823. return 0;
  49824. },
  49825. set: function (value) {
  49826. var pointers = this.inputs.attached["pointers"];
  49827. if (pointers) {
  49828. pointers.angularSensibilityX = value;
  49829. }
  49830. },
  49831. enumerable: true,
  49832. configurable: true
  49833. });
  49834. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  49835. /**
  49836. * Gets or Set the pointer angular sensibility along the Y axis or how fast is the camera rotating.
  49837. */
  49838. get: function () {
  49839. var pointers = this.inputs.attached["pointers"];
  49840. if (pointers)
  49841. return pointers.angularSensibilityY;
  49842. return 0;
  49843. },
  49844. set: function (value) {
  49845. var pointers = this.inputs.attached["pointers"];
  49846. if (pointers) {
  49847. pointers.angularSensibilityY = value;
  49848. }
  49849. },
  49850. enumerable: true,
  49851. configurable: true
  49852. });
  49853. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  49854. /**
  49855. * Gets or Set the pointer pinch precision or how fast is the camera zooming.
  49856. */
  49857. get: function () {
  49858. var pointers = this.inputs.attached["pointers"];
  49859. if (pointers)
  49860. return pointers.pinchPrecision;
  49861. return 0;
  49862. },
  49863. set: function (value) {
  49864. var pointers = this.inputs.attached["pointers"];
  49865. if (pointers) {
  49866. pointers.pinchPrecision = value;
  49867. }
  49868. },
  49869. enumerable: true,
  49870. configurable: true
  49871. });
  49872. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  49873. /**
  49874. * Gets or Set the pointer pinch delta percentage or how fast is the camera zooming.
  49875. * It will be used instead of pinchDeltaPrecision if different from 0.
  49876. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  49877. */
  49878. get: function () {
  49879. var pointers = this.inputs.attached["pointers"];
  49880. if (pointers)
  49881. return pointers.pinchDeltaPercentage;
  49882. return 0;
  49883. },
  49884. set: function (value) {
  49885. var pointers = this.inputs.attached["pointers"];
  49886. if (pointers) {
  49887. pointers.pinchDeltaPercentage = value;
  49888. }
  49889. },
  49890. enumerable: true,
  49891. configurable: true
  49892. });
  49893. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  49894. /**
  49895. * Gets or Set the pointer panning sensibility or how fast is the camera moving.
  49896. */
  49897. get: function () {
  49898. var pointers = this.inputs.attached["pointers"];
  49899. if (pointers)
  49900. return pointers.panningSensibility;
  49901. return 0;
  49902. },
  49903. set: function (value) {
  49904. var pointers = this.inputs.attached["pointers"];
  49905. if (pointers) {
  49906. pointers.panningSensibility = value;
  49907. }
  49908. },
  49909. enumerable: true,
  49910. configurable: true
  49911. });
  49912. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  49913. /**
  49914. * Gets or Set the list of keyboard keys used to control beta angle in a positive direction.
  49915. */
  49916. get: function () {
  49917. var keyboard = this.inputs.attached["keyboard"];
  49918. if (keyboard)
  49919. return keyboard.keysUp;
  49920. return [];
  49921. },
  49922. set: function (value) {
  49923. var keyboard = this.inputs.attached["keyboard"];
  49924. if (keyboard)
  49925. keyboard.keysUp = value;
  49926. },
  49927. enumerable: true,
  49928. configurable: true
  49929. });
  49930. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  49931. /**
  49932. * Gets or Set the list of keyboard keys used to control beta angle in a negative direction.
  49933. */
  49934. get: function () {
  49935. var keyboard = this.inputs.attached["keyboard"];
  49936. if (keyboard)
  49937. return keyboard.keysDown;
  49938. return [];
  49939. },
  49940. set: function (value) {
  49941. var keyboard = this.inputs.attached["keyboard"];
  49942. if (keyboard)
  49943. keyboard.keysDown = value;
  49944. },
  49945. enumerable: true,
  49946. configurable: true
  49947. });
  49948. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  49949. /**
  49950. * Gets or Set the list of keyboard keys used to control alpha angle in a negative direction.
  49951. */
  49952. get: function () {
  49953. var keyboard = this.inputs.attached["keyboard"];
  49954. if (keyboard)
  49955. return keyboard.keysLeft;
  49956. return [];
  49957. },
  49958. set: function (value) {
  49959. var keyboard = this.inputs.attached["keyboard"];
  49960. if (keyboard)
  49961. keyboard.keysLeft = value;
  49962. },
  49963. enumerable: true,
  49964. configurable: true
  49965. });
  49966. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  49967. /**
  49968. * Gets or Set the list of keyboard keys used to control alpha angle in a positive direction.
  49969. */
  49970. get: function () {
  49971. var keyboard = this.inputs.attached["keyboard"];
  49972. if (keyboard)
  49973. return keyboard.keysRight;
  49974. return [];
  49975. },
  49976. set: function (value) {
  49977. var keyboard = this.inputs.attached["keyboard"];
  49978. if (keyboard)
  49979. keyboard.keysRight = value;
  49980. },
  49981. enumerable: true,
  49982. configurable: true
  49983. });
  49984. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  49985. /**
  49986. * Gets or Set the mouse wheel precision or how fast is the camera zooming.
  49987. */
  49988. get: function () {
  49989. var mousewheel = this.inputs.attached["mousewheel"];
  49990. if (mousewheel)
  49991. return mousewheel.wheelPrecision;
  49992. return 0;
  49993. },
  49994. set: function (value) {
  49995. var mousewheel = this.inputs.attached["mousewheel"];
  49996. if (mousewheel)
  49997. mousewheel.wheelPrecision = value;
  49998. },
  49999. enumerable: true,
  50000. configurable: true
  50001. });
  50002. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  50003. /**
  50004. * Gets or Set the mouse wheel delta percentage or how fast is the camera zooming.
  50005. * It will be used instead of pinchDeltaPrecision if different from 0.
  50006. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  50007. */
  50008. get: function () {
  50009. var mousewheel = this.inputs.attached["mousewheel"];
  50010. if (mousewheel)
  50011. return mousewheel.wheelDeltaPercentage;
  50012. return 0;
  50013. },
  50014. set: function (value) {
  50015. var mousewheel = this.inputs.attached["mousewheel"];
  50016. if (mousewheel)
  50017. mousewheel.wheelDeltaPercentage = value;
  50018. },
  50019. enumerable: true,
  50020. configurable: true
  50021. });
  50022. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  50023. /**
  50024. * Gets the bouncing behavior of the camera if it has been enabled.
  50025. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  50026. */
  50027. get: function () {
  50028. return this._bouncingBehavior;
  50029. },
  50030. enumerable: true,
  50031. configurable: true
  50032. });
  50033. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  50034. /**
  50035. * Defines if the bouncing behavior of the camera is enabled on the camera.
  50036. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  50037. */
  50038. get: function () {
  50039. return this._bouncingBehavior != null;
  50040. },
  50041. set: function (value) {
  50042. if (value === this.useBouncingBehavior) {
  50043. return;
  50044. }
  50045. if (value) {
  50046. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  50047. this.addBehavior(this._bouncingBehavior);
  50048. }
  50049. else if (this._bouncingBehavior) {
  50050. this.removeBehavior(this._bouncingBehavior);
  50051. this._bouncingBehavior = null;
  50052. }
  50053. },
  50054. enumerable: true,
  50055. configurable: true
  50056. });
  50057. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  50058. /**
  50059. * Gets the framing behavior of the camera if it has been enabled.
  50060. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  50061. */
  50062. get: function () {
  50063. return this._framingBehavior;
  50064. },
  50065. enumerable: true,
  50066. configurable: true
  50067. });
  50068. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  50069. /**
  50070. * Defines if the framing behavior of the camera is enabled on the camera.
  50071. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  50072. */
  50073. get: function () {
  50074. return this._framingBehavior != null;
  50075. },
  50076. set: function (value) {
  50077. if (value === this.useFramingBehavior) {
  50078. return;
  50079. }
  50080. if (value) {
  50081. this._framingBehavior = new BABYLON.FramingBehavior();
  50082. this.addBehavior(this._framingBehavior);
  50083. }
  50084. else if (this._framingBehavior) {
  50085. this.removeBehavior(this._framingBehavior);
  50086. this._framingBehavior = null;
  50087. }
  50088. },
  50089. enumerable: true,
  50090. configurable: true
  50091. });
  50092. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  50093. /**
  50094. * Gets the auto rotation behavior of the camera if it has been enabled.
  50095. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  50096. */
  50097. get: function () {
  50098. return this._autoRotationBehavior;
  50099. },
  50100. enumerable: true,
  50101. configurable: true
  50102. });
  50103. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  50104. /**
  50105. * Defines if the auto rotation behavior of the camera is enabled on the camera.
  50106. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  50107. */
  50108. get: function () {
  50109. return this._autoRotationBehavior != null;
  50110. },
  50111. set: function (value) {
  50112. if (value === this.useAutoRotationBehavior) {
  50113. return;
  50114. }
  50115. if (value) {
  50116. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  50117. this.addBehavior(this._autoRotationBehavior);
  50118. }
  50119. else if (this._autoRotationBehavior) {
  50120. this.removeBehavior(this._autoRotationBehavior);
  50121. this._autoRotationBehavior = null;
  50122. }
  50123. },
  50124. enumerable: true,
  50125. configurable: true
  50126. });
  50127. // Cache
  50128. /** @hidden */
  50129. ArcRotateCamera.prototype._initCache = function () {
  50130. _super.prototype._initCache.call(this);
  50131. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  50132. this._cache.alpha = undefined;
  50133. this._cache.beta = undefined;
  50134. this._cache.radius = undefined;
  50135. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  50136. };
  50137. /** @hidden */
  50138. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  50139. if (!ignoreParentClass) {
  50140. _super.prototype._updateCache.call(this);
  50141. }
  50142. this._cache._target.copyFrom(this._getTargetPosition());
  50143. this._cache.alpha = this.alpha;
  50144. this._cache.beta = this.beta;
  50145. this._cache.radius = this.radius;
  50146. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  50147. };
  50148. ArcRotateCamera.prototype._getTargetPosition = function () {
  50149. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  50150. var pos = this._targetHost.getAbsolutePosition();
  50151. if (this._targetBoundingCenter) {
  50152. pos.addToRef(this._targetBoundingCenter, this._target);
  50153. }
  50154. else {
  50155. this._target.copyFrom(pos);
  50156. }
  50157. }
  50158. var lockedTargetPosition = this._getLockedTargetPosition();
  50159. if (lockedTargetPosition) {
  50160. return lockedTargetPosition;
  50161. }
  50162. return this._target;
  50163. };
  50164. /**
  50165. * Stores the current state of the camera (alpha, beta, radius and target)
  50166. * @returns the camera itself
  50167. */
  50168. ArcRotateCamera.prototype.storeState = function () {
  50169. this._storedAlpha = this.alpha;
  50170. this._storedBeta = this.beta;
  50171. this._storedRadius = this.radius;
  50172. this._storedTarget = this._getTargetPosition().clone();
  50173. return _super.prototype.storeState.call(this);
  50174. };
  50175. /**
  50176. * @hidden
  50177. * Restored camera state. You must call storeState() first
  50178. */
  50179. ArcRotateCamera.prototype._restoreStateValues = function () {
  50180. if (!_super.prototype._restoreStateValues.call(this)) {
  50181. return false;
  50182. }
  50183. this.alpha = this._storedAlpha;
  50184. this.beta = this._storedBeta;
  50185. this.radius = this._storedRadius;
  50186. this.setTarget(this._storedTarget.clone());
  50187. this.inertialAlphaOffset = 0;
  50188. this.inertialBetaOffset = 0;
  50189. this.inertialRadiusOffset = 0;
  50190. this.inertialPanningX = 0;
  50191. this.inertialPanningY = 0;
  50192. return true;
  50193. };
  50194. // Synchronized
  50195. /** @hidden */
  50196. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  50197. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  50198. return false;
  50199. return this._cache._target.equals(this._getTargetPosition())
  50200. && this._cache.alpha === this.alpha
  50201. && this._cache.beta === this.beta
  50202. && this._cache.radius === this.radius
  50203. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  50204. };
  50205. /**
  50206. * Attached controls to the current camera.
  50207. * @param element Defines the element the controls should be listened from
  50208. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  50209. * @param useCtrlForPanning Defines whether ctrl is used for paning within the controls
  50210. * @param panningMouseButton Defines whether panning is allowed through mouse click button
  50211. */
  50212. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  50213. var _this = this;
  50214. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  50215. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  50216. this._useCtrlForPanning = useCtrlForPanning;
  50217. this._panningMouseButton = panningMouseButton;
  50218. this.inputs.attachElement(element, noPreventDefault);
  50219. this._reset = function () {
  50220. _this.inertialAlphaOffset = 0;
  50221. _this.inertialBetaOffset = 0;
  50222. _this.inertialRadiusOffset = 0;
  50223. _this.inertialPanningX = 0;
  50224. _this.inertialPanningY = 0;
  50225. };
  50226. };
  50227. /**
  50228. * Detach the current controls from the camera.
  50229. * The camera will stop reacting to inputs.
  50230. * @param element Defines the element to stop listening the inputs from
  50231. */
  50232. ArcRotateCamera.prototype.detachControl = function (element) {
  50233. this.inputs.detachElement(element);
  50234. if (this._reset) {
  50235. this._reset();
  50236. }
  50237. };
  50238. /** @hidden */
  50239. ArcRotateCamera.prototype._checkInputs = function () {
  50240. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  50241. if (this._collisionTriggered) {
  50242. return;
  50243. }
  50244. this.inputs.checkInputs();
  50245. // Inertia
  50246. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  50247. var inertialAlphaOffset = this.inertialAlphaOffset;
  50248. if (this.beta <= 0)
  50249. inertialAlphaOffset *= -1;
  50250. if (this.getScene().useRightHandedSystem)
  50251. inertialAlphaOffset *= -1;
  50252. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  50253. inertialAlphaOffset *= -1;
  50254. this.alpha += inertialAlphaOffset;
  50255. this.beta += this.inertialBetaOffset;
  50256. this.radius -= this.inertialRadiusOffset;
  50257. this.inertialAlphaOffset *= this.inertia;
  50258. this.inertialBetaOffset *= this.inertia;
  50259. this.inertialRadiusOffset *= this.inertia;
  50260. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  50261. this.inertialAlphaOffset = 0;
  50262. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  50263. this.inertialBetaOffset = 0;
  50264. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  50265. this.inertialRadiusOffset = 0;
  50266. }
  50267. // Panning inertia
  50268. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  50269. if (!this._localDirection) {
  50270. this._localDirection = BABYLON.Vector3.Zero();
  50271. this._transformedDirection = BABYLON.Vector3.Zero();
  50272. }
  50273. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  50274. this._localDirection.multiplyInPlace(this.panningAxis);
  50275. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  50276. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  50277. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  50278. if (!this.panningAxis.y) {
  50279. this._transformedDirection.y = 0;
  50280. }
  50281. if (!this._targetHost) {
  50282. if (this.panningDistanceLimit) {
  50283. this._transformedDirection.addInPlace(this._target);
  50284. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  50285. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  50286. this._target.copyFrom(this._transformedDirection);
  50287. }
  50288. }
  50289. else {
  50290. this._target.addInPlace(this._transformedDirection);
  50291. }
  50292. }
  50293. this.inertialPanningX *= this.panningInertia;
  50294. this.inertialPanningY *= this.panningInertia;
  50295. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  50296. this.inertialPanningX = 0;
  50297. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  50298. this.inertialPanningY = 0;
  50299. }
  50300. // Limits
  50301. this._checkLimits();
  50302. _super.prototype._checkInputs.call(this);
  50303. };
  50304. ArcRotateCamera.prototype._checkLimits = function () {
  50305. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  50306. if (this.allowUpsideDown && this.beta > Math.PI) {
  50307. this.beta = this.beta - (2 * Math.PI);
  50308. }
  50309. }
  50310. else {
  50311. if (this.beta < this.lowerBetaLimit) {
  50312. this.beta = this.lowerBetaLimit;
  50313. }
  50314. }
  50315. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  50316. if (this.allowUpsideDown && this.beta < -Math.PI) {
  50317. this.beta = this.beta + (2 * Math.PI);
  50318. }
  50319. }
  50320. else {
  50321. if (this.beta > this.upperBetaLimit) {
  50322. this.beta = this.upperBetaLimit;
  50323. }
  50324. }
  50325. if (this.lowerAlphaLimit !== null && this.alpha < this.lowerAlphaLimit) {
  50326. this.alpha = this.lowerAlphaLimit;
  50327. }
  50328. if (this.upperAlphaLimit !== null && this.alpha > this.upperAlphaLimit) {
  50329. this.alpha = this.upperAlphaLimit;
  50330. }
  50331. if (this.lowerRadiusLimit !== null && this.radius < this.lowerRadiusLimit) {
  50332. this.radius = this.lowerRadiusLimit;
  50333. }
  50334. if (this.upperRadiusLimit !== null && this.radius > this.upperRadiusLimit) {
  50335. this.radius = this.upperRadiusLimit;
  50336. }
  50337. };
  50338. /**
  50339. * Rebuilds angles (alpha, beta) and radius from the give position and target.
  50340. */
  50341. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  50342. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  50343. this.radius = this._computationVector.length();
  50344. if (this.radius === 0) {
  50345. this.radius = 0.0001; // Just to avoid division by zero
  50346. }
  50347. // Alpha
  50348. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  50349. if (this._computationVector.z < 0) {
  50350. this.alpha = 2 * Math.PI - this.alpha;
  50351. }
  50352. // Beta
  50353. this.beta = Math.acos(this._computationVector.y / this.radius);
  50354. this._checkLimits();
  50355. };
  50356. /**
  50357. * Use a position to define the current camera related information like aplha, beta and radius
  50358. * @param position Defines the position to set the camera at
  50359. */
  50360. ArcRotateCamera.prototype.setPosition = function (position) {
  50361. if (this.position.equals(position)) {
  50362. return;
  50363. }
  50364. this.position.copyFrom(position);
  50365. this.rebuildAnglesAndRadius();
  50366. };
  50367. /**
  50368. * Defines the target the camera should look at.
  50369. * This will automatically adapt alpha beta and radius to fit within the new target.
  50370. * @param target Defines the new target as a Vector or a mesh
  50371. * @param toBoundingCenter In case of a mesh target, defines wether to target the mesh position or its bounding information center
  50372. * @param allowSamePosition If false, prevents reapplying the new computed position if it is identical to the current one (optim)
  50373. */
  50374. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  50375. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  50376. if (allowSamePosition === void 0) { allowSamePosition = false; }
  50377. if (target.getBoundingInfo) {
  50378. if (toBoundingCenter) {
  50379. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  50380. }
  50381. else {
  50382. this._targetBoundingCenter = null;
  50383. }
  50384. this._targetHost = target;
  50385. this._target = this._getTargetPosition();
  50386. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  50387. }
  50388. else {
  50389. var newTarget = target;
  50390. var currentTarget = this._getTargetPosition();
  50391. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  50392. return;
  50393. }
  50394. this._targetHost = null;
  50395. this._target = newTarget;
  50396. this._targetBoundingCenter = null;
  50397. this.onMeshTargetChangedObservable.notifyObservers(null);
  50398. }
  50399. this.rebuildAnglesAndRadius();
  50400. };
  50401. /** @hidden */
  50402. ArcRotateCamera.prototype._getViewMatrix = function () {
  50403. // Compute
  50404. var cosa = Math.cos(this.alpha);
  50405. var sina = Math.sin(this.alpha);
  50406. var cosb = Math.cos(this.beta);
  50407. var sinb = Math.sin(this.beta);
  50408. if (sinb === 0) {
  50409. sinb = 0.0001;
  50410. }
  50411. var target = this._getTargetPosition();
  50412. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  50413. target.addToRef(this._computationVector, this._newPosition);
  50414. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  50415. if (!this._collider) {
  50416. this._collider = new BABYLON.Collider();
  50417. }
  50418. this._collider._radius = this.collisionRadius;
  50419. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  50420. this._collisionTriggered = true;
  50421. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  50422. }
  50423. else {
  50424. this.position.copyFrom(this._newPosition);
  50425. var up = this.upVector;
  50426. if (this.allowUpsideDown && sinb < 0) {
  50427. up = up.clone();
  50428. up = up.negate();
  50429. }
  50430. this._computeViewMatrix(this.position, target, up);
  50431. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  50432. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  50433. }
  50434. this._currentTarget = target;
  50435. return this._viewMatrix;
  50436. };
  50437. /**
  50438. * Zooms on a mesh to be at the min distance where we could see it fully in the current viewport.
  50439. * @param meshes Defines the mesh to zoom on
  50440. * @param doNotUpdateMaxZ Defines whether or not maxZ should be updated whilst zooming on the mesh (this can happen if the mesh is big and the maxradius pretty small for instance)
  50441. */
  50442. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  50443. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  50444. meshes = meshes || this.getScene().meshes;
  50445. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  50446. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  50447. this.radius = distance * this.zoomOnFactor;
  50448. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  50449. };
  50450. /**
  50451. * Focus on a mesh or a bounding box. This adapts the target and maxRadius if necessary but does not update the current radius.
  50452. * The target will be changed but the radius
  50453. * @param meshesOrMinMaxVectorAndDistance Defines the mesh or bounding info to focus on
  50454. * @param doNotUpdateMaxZ Defines whether or not maxZ should be updated whilst zooming on the mesh (this can happen if the mesh is big and the maxradius pretty small for instance)
  50455. */
  50456. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  50457. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  50458. var meshesOrMinMaxVector;
  50459. var distance;
  50460. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  50461. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  50462. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  50463. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  50464. }
  50465. else { //minMaxVector and distance
  50466. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  50467. meshesOrMinMaxVector = minMaxVectorAndDistance;
  50468. distance = minMaxVectorAndDistance.distance;
  50469. }
  50470. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  50471. if (!doNotUpdateMaxZ) {
  50472. this.maxZ = distance * 2;
  50473. }
  50474. };
  50475. /**
  50476. * @override
  50477. * Override Camera.createRigCamera
  50478. */
  50479. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  50480. var alphaShift = 0;
  50481. switch (this.cameraRigMode) {
  50482. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  50483. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  50484. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  50485. case BABYLON.Camera.RIG_MODE_VR:
  50486. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  50487. break;
  50488. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  50489. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  50490. break;
  50491. }
  50492. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  50493. rigCam._cameraRigParams = {};
  50494. return rigCam;
  50495. };
  50496. /**
  50497. * @hidden
  50498. * @override
  50499. * Override Camera._updateRigCameras
  50500. */
  50501. ArcRotateCamera.prototype._updateRigCameras = function () {
  50502. var camLeft = this._rigCameras[0];
  50503. var camRight = this._rigCameras[1];
  50504. camLeft.beta = camRight.beta = this.beta;
  50505. camLeft.radius = camRight.radius = this.radius;
  50506. switch (this.cameraRigMode) {
  50507. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  50508. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  50509. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  50510. case BABYLON.Camera.RIG_MODE_VR:
  50511. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  50512. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  50513. break;
  50514. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  50515. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  50516. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  50517. break;
  50518. }
  50519. _super.prototype._updateRigCameras.call(this);
  50520. };
  50521. /**
  50522. * Destroy the camera and release the current resources hold by it.
  50523. */
  50524. ArcRotateCamera.prototype.dispose = function () {
  50525. this.inputs.clear();
  50526. _super.prototype.dispose.call(this);
  50527. };
  50528. /**
  50529. * Gets the current object class name.
  50530. * @return the class name
  50531. */
  50532. ArcRotateCamera.prototype.getClassName = function () {
  50533. return "ArcRotateCamera";
  50534. };
  50535. __decorate([
  50536. BABYLON.serialize()
  50537. ], ArcRotateCamera.prototype, "alpha", void 0);
  50538. __decorate([
  50539. BABYLON.serialize()
  50540. ], ArcRotateCamera.prototype, "beta", void 0);
  50541. __decorate([
  50542. BABYLON.serialize()
  50543. ], ArcRotateCamera.prototype, "radius", void 0);
  50544. __decorate([
  50545. BABYLON.serializeAsVector3("target")
  50546. ], ArcRotateCamera.prototype, "_target", void 0);
  50547. __decorate([
  50548. BABYLON.serialize()
  50549. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  50550. __decorate([
  50551. BABYLON.serialize()
  50552. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  50553. __decorate([
  50554. BABYLON.serialize()
  50555. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  50556. __decorate([
  50557. BABYLON.serialize()
  50558. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  50559. __decorate([
  50560. BABYLON.serialize()
  50561. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  50562. __decorate([
  50563. BABYLON.serialize()
  50564. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  50565. __decorate([
  50566. BABYLON.serialize()
  50567. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  50568. __decorate([
  50569. BABYLON.serialize()
  50570. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  50571. __decorate([
  50572. BABYLON.serialize()
  50573. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  50574. __decorate([
  50575. BABYLON.serialize()
  50576. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  50577. __decorate([
  50578. BABYLON.serialize()
  50579. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  50580. __decorate([
  50581. BABYLON.serialize()
  50582. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  50583. __decorate([
  50584. BABYLON.serialize()
  50585. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  50586. __decorate([
  50587. BABYLON.serializeAsVector3()
  50588. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  50589. __decorate([
  50590. BABYLON.serialize()
  50591. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  50592. __decorate([
  50593. BABYLON.serialize()
  50594. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  50595. __decorate([
  50596. BABYLON.serialize()
  50597. ], ArcRotateCamera.prototype, "targetScreenOffset", void 0);
  50598. __decorate([
  50599. BABYLON.serialize()
  50600. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  50601. __decorate([
  50602. BABYLON.serialize()
  50603. ], ArcRotateCamera.prototype, "useInputToRestoreState", void 0);
  50604. return ArcRotateCamera;
  50605. }(BABYLON.TargetCamera));
  50606. BABYLON.ArcRotateCamera = ArcRotateCamera;
  50607. })(BABYLON || (BABYLON = {}));
  50608. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  50609. var BABYLON;
  50610. (function (BABYLON) {
  50611. BABYLON.Node.AddNodeConstructor("Light_Type_3", function (name, scene) {
  50612. return function () { return new HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  50613. });
  50614. /**
  50615. * The HemisphericLight simulates the ambient environment light,
  50616. * so the passed direction is the light reflection direction, not the incoming direction.
  50617. */
  50618. var HemisphericLight = /** @class */ (function (_super) {
  50619. __extends(HemisphericLight, _super);
  50620. /**
  50621. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  50622. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  50623. * The HemisphericLight can't cast shadows.
  50624. * Documentation : http://doc.babylonjs.com/tutorials/lights
  50625. * @param name The friendly name of the light
  50626. * @param direction The direction of the light reflection
  50627. * @param scene The scene the light belongs to
  50628. */
  50629. function HemisphericLight(name, direction, scene) {
  50630. var _this = _super.call(this, name, scene) || this;
  50631. /**
  50632. * The groundColor is the light in the opposite direction to the one specified during creation.
  50633. * 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.
  50634. */
  50635. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  50636. _this.direction = direction || BABYLON.Vector3.Up();
  50637. return _this;
  50638. }
  50639. HemisphericLight.prototype._buildUniformLayout = function () {
  50640. this._uniformBuffer.addUniform("vLightData", 4);
  50641. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  50642. this._uniformBuffer.addUniform("vLightSpecular", 3);
  50643. this._uniformBuffer.addUniform("vLightGround", 3);
  50644. this._uniformBuffer.addUniform("shadowsInfo", 3);
  50645. this._uniformBuffer.addUniform("depthValues", 2);
  50646. this._uniformBuffer.create();
  50647. };
  50648. /**
  50649. * Returns the string "HemisphericLight".
  50650. * @return The class name
  50651. */
  50652. HemisphericLight.prototype.getClassName = function () {
  50653. return "HemisphericLight";
  50654. };
  50655. /**
  50656. * Sets the HemisphericLight direction towards the passed target (Vector3).
  50657. * Returns the updated direction.
  50658. * @param target The target the direction should point to
  50659. * @return The computed direction
  50660. */
  50661. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  50662. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  50663. return this.direction;
  50664. };
  50665. /**
  50666. * Returns the shadow generator associated to the light.
  50667. * @returns Always null for hemispheric lights because it does not support shadows.
  50668. */
  50669. HemisphericLight.prototype.getShadowGenerator = function () {
  50670. return null;
  50671. };
  50672. /**
  50673. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  50674. * @param effect The effect to update
  50675. * @param lightIndex The index of the light in the effect to update
  50676. * @returns The hemispheric light
  50677. */
  50678. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  50679. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  50680. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  50681. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  50682. return this;
  50683. };
  50684. /**
  50685. * Computes the world matrix of the node
  50686. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  50687. * @param useWasUpdatedFlag defines a reserved property
  50688. * @returns the world matrix
  50689. */
  50690. HemisphericLight.prototype.computeWorldMatrix = function (force, useWasUpdatedFlag) {
  50691. if (!this._worldMatrix) {
  50692. this._worldMatrix = BABYLON.Matrix.Identity();
  50693. }
  50694. return this._worldMatrix;
  50695. };
  50696. /**
  50697. * Returns the integer 3.
  50698. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  50699. */
  50700. HemisphericLight.prototype.getTypeID = function () {
  50701. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  50702. };
  50703. /**
  50704. * Prepares the list of defines specific to the light type.
  50705. * @param defines the list of defines
  50706. * @param lightIndex defines the index of the light for the effect
  50707. */
  50708. HemisphericLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  50709. defines["HEMILIGHT" + lightIndex] = true;
  50710. };
  50711. __decorate([
  50712. BABYLON.serializeAsColor3()
  50713. ], HemisphericLight.prototype, "groundColor", void 0);
  50714. __decorate([
  50715. BABYLON.serializeAsVector3()
  50716. ], HemisphericLight.prototype, "direction", void 0);
  50717. return HemisphericLight;
  50718. }(BABYLON.Light));
  50719. BABYLON.HemisphericLight = HemisphericLight;
  50720. })(BABYLON || (BABYLON = {}));
  50721. //# sourceMappingURL=babylon.hemisphericLight.js.map
  50722. var BABYLON;
  50723. (function (BABYLON) {
  50724. /**
  50725. * Base implementation IShadowLight
  50726. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  50727. */
  50728. var ShadowLight = /** @class */ (function (_super) {
  50729. __extends(ShadowLight, _super);
  50730. function ShadowLight() {
  50731. var _this = _super !== null && _super.apply(this, arguments) || this;
  50732. _this._needProjectionMatrixCompute = true;
  50733. return _this;
  50734. }
  50735. ShadowLight.prototype._setPosition = function (value) {
  50736. this._position = value;
  50737. };
  50738. Object.defineProperty(ShadowLight.prototype, "position", {
  50739. /**
  50740. * Sets the position the shadow will be casted from. Also use as the light position for both
  50741. * point and spot lights.
  50742. */
  50743. get: function () {
  50744. return this._position;
  50745. },
  50746. /**
  50747. * Sets the position the shadow will be casted from. Also use as the light position for both
  50748. * point and spot lights.
  50749. */
  50750. set: function (value) {
  50751. this._setPosition(value);
  50752. },
  50753. enumerable: true,
  50754. configurable: true
  50755. });
  50756. ShadowLight.prototype._setDirection = function (value) {
  50757. this._direction = value;
  50758. };
  50759. Object.defineProperty(ShadowLight.prototype, "direction", {
  50760. /**
  50761. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  50762. * Also use as the light direction on spot and directional lights.
  50763. */
  50764. get: function () {
  50765. return this._direction;
  50766. },
  50767. /**
  50768. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  50769. * Also use as the light direction on spot and directional lights.
  50770. */
  50771. set: function (value) {
  50772. this._setDirection(value);
  50773. },
  50774. enumerable: true,
  50775. configurable: true
  50776. });
  50777. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  50778. /**
  50779. * Gets the shadow projection clipping minimum z value.
  50780. */
  50781. get: function () {
  50782. return this._shadowMinZ;
  50783. },
  50784. /**
  50785. * Sets the shadow projection clipping minimum z value.
  50786. */
  50787. set: function (value) {
  50788. this._shadowMinZ = value;
  50789. this.forceProjectionMatrixCompute();
  50790. },
  50791. enumerable: true,
  50792. configurable: true
  50793. });
  50794. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  50795. /**
  50796. * Sets the shadow projection clipping maximum z value.
  50797. */
  50798. get: function () {
  50799. return this._shadowMaxZ;
  50800. },
  50801. /**
  50802. * Gets the shadow projection clipping maximum z value.
  50803. */
  50804. set: function (value) {
  50805. this._shadowMaxZ = value;
  50806. this.forceProjectionMatrixCompute();
  50807. },
  50808. enumerable: true,
  50809. configurable: true
  50810. });
  50811. /**
  50812. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  50813. * @returns true if the information has been computed, false if it does not need to (no parenting)
  50814. */
  50815. ShadowLight.prototype.computeTransformedInformation = function () {
  50816. if (this.parent && this.parent.getWorldMatrix) {
  50817. if (!this.transformedPosition) {
  50818. this.transformedPosition = BABYLON.Vector3.Zero();
  50819. }
  50820. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  50821. // In case the direction is present.
  50822. if (this.direction) {
  50823. if (!this.transformedDirection) {
  50824. this.transformedDirection = BABYLON.Vector3.Zero();
  50825. }
  50826. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  50827. }
  50828. return true;
  50829. }
  50830. return false;
  50831. };
  50832. /**
  50833. * Return the depth scale used for the shadow map.
  50834. * @returns the depth scale.
  50835. */
  50836. ShadowLight.prototype.getDepthScale = function () {
  50837. return 50.0;
  50838. };
  50839. /**
  50840. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  50841. * @param faceIndex The index of the face we are computed the direction to generate shadow
  50842. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  50843. */
  50844. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  50845. return this.transformedDirection ? this.transformedDirection : this.direction;
  50846. };
  50847. /**
  50848. * Returns the ShadowLight absolute position in the World.
  50849. * @returns the position vector in world space
  50850. */
  50851. ShadowLight.prototype.getAbsolutePosition = function () {
  50852. return this.transformedPosition ? this.transformedPosition : this.position;
  50853. };
  50854. /**
  50855. * Sets the ShadowLight direction toward the passed target.
  50856. * @param target The point tot target in local space
  50857. * @returns the updated ShadowLight direction
  50858. */
  50859. ShadowLight.prototype.setDirectionToTarget = function (target) {
  50860. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  50861. return this.direction;
  50862. };
  50863. /**
  50864. * Returns the light rotation in euler definition.
  50865. * @returns the x y z rotation in local space.
  50866. */
  50867. ShadowLight.prototype.getRotation = function () {
  50868. this.direction.normalize();
  50869. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  50870. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  50871. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  50872. };
  50873. /**
  50874. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  50875. * @returns true if a cube texture needs to be use
  50876. */
  50877. ShadowLight.prototype.needCube = function () {
  50878. return false;
  50879. };
  50880. /**
  50881. * Detects if the projection matrix requires to be recomputed this frame.
  50882. * @returns true if it requires to be recomputed otherwise, false.
  50883. */
  50884. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  50885. return this._needProjectionMatrixCompute;
  50886. };
  50887. /**
  50888. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  50889. */
  50890. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  50891. this._needProjectionMatrixCompute = true;
  50892. };
  50893. /** @hidden */
  50894. ShadowLight.prototype._initCache = function () {
  50895. _super.prototype._initCache.call(this);
  50896. this._cache.position = BABYLON.Vector3.Zero();
  50897. };
  50898. /** @hidden */
  50899. ShadowLight.prototype._isSynchronized = function () {
  50900. if (!this._cache.position.equals(this.position))
  50901. return false;
  50902. return true;
  50903. };
  50904. /**
  50905. * Computes the world matrix of the node
  50906. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  50907. * @returns the world matrix
  50908. */
  50909. ShadowLight.prototype.computeWorldMatrix = function (force) {
  50910. if (!force && this.isSynchronized()) {
  50911. this._currentRenderId = this.getScene().getRenderId();
  50912. return this._worldMatrix;
  50913. }
  50914. this._updateCache();
  50915. this._cache.position.copyFrom(this.position);
  50916. if (!this._worldMatrix) {
  50917. this._worldMatrix = BABYLON.Matrix.Identity();
  50918. }
  50919. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  50920. if (this.parent && this.parent.getWorldMatrix) {
  50921. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  50922. this._markSyncedWithParent();
  50923. }
  50924. // Cache the determinant
  50925. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  50926. return this._worldMatrix;
  50927. };
  50928. /**
  50929. * Gets the minZ used for shadow according to both the scene and the light.
  50930. * @param activeCamera The camera we are returning the min for
  50931. * @returns the depth min z
  50932. */
  50933. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  50934. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  50935. };
  50936. /**
  50937. * Gets the maxZ used for shadow according to both the scene and the light.
  50938. * @param activeCamera The camera we are returning the max for
  50939. * @returns the depth max z
  50940. */
  50941. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  50942. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  50943. };
  50944. /**
  50945. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  50946. * @param matrix The materix to updated with the projection information
  50947. * @param viewMatrix The transform matrix of the light
  50948. * @param renderList The list of mesh to render in the map
  50949. * @returns The current light
  50950. */
  50951. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50952. if (this.customProjectionMatrixBuilder) {
  50953. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  50954. }
  50955. else {
  50956. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  50957. }
  50958. return this;
  50959. };
  50960. __decorate([
  50961. BABYLON.serializeAsVector3()
  50962. ], ShadowLight.prototype, "position", null);
  50963. __decorate([
  50964. BABYLON.serializeAsVector3()
  50965. ], ShadowLight.prototype, "direction", null);
  50966. __decorate([
  50967. BABYLON.serialize()
  50968. ], ShadowLight.prototype, "shadowMinZ", null);
  50969. __decorate([
  50970. BABYLON.serialize()
  50971. ], ShadowLight.prototype, "shadowMaxZ", null);
  50972. return ShadowLight;
  50973. }(BABYLON.Light));
  50974. BABYLON.ShadowLight = ShadowLight;
  50975. })(BABYLON || (BABYLON = {}));
  50976. //# sourceMappingURL=babylon.shadowLight.js.map
  50977. var BABYLON;
  50978. (function (BABYLON) {
  50979. BABYLON.Node.AddNodeConstructor("Light_Type_0", function (name, scene) {
  50980. return function () { return new PointLight(name, BABYLON.Vector3.Zero(), scene); };
  50981. });
  50982. /**
  50983. * A point light is a light defined by an unique point in world space.
  50984. * The light is emitted in every direction from this point.
  50985. * A good example of a point light is a standard light bulb.
  50986. * Documentation: https://doc.babylonjs.com/babylon101/lights
  50987. */
  50988. var PointLight = /** @class */ (function (_super) {
  50989. __extends(PointLight, _super);
  50990. /**
  50991. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  50992. * A PointLight emits the light in every direction.
  50993. * It can cast shadows.
  50994. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  50995. * ```javascript
  50996. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  50997. * ```
  50998. * Documentation : http://doc.babylonjs.com/tutorials/lights
  50999. * @param name The light friendly name
  51000. * @param position The position of the point light in the scene
  51001. * @param scene The scene the lights belongs to
  51002. */
  51003. function PointLight(name, position, scene) {
  51004. var _this = _super.call(this, name, scene) || this;
  51005. _this._shadowAngle = Math.PI / 2;
  51006. _this.position = position;
  51007. return _this;
  51008. }
  51009. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  51010. /**
  51011. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  51012. * This specifies what angle the shadow will use to be created.
  51013. *
  51014. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  51015. */
  51016. get: function () {
  51017. return this._shadowAngle;
  51018. },
  51019. /**
  51020. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  51021. * This specifies what angle the shadow will use to be created.
  51022. *
  51023. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  51024. */
  51025. set: function (value) {
  51026. this._shadowAngle = value;
  51027. this.forceProjectionMatrixCompute();
  51028. },
  51029. enumerable: true,
  51030. configurable: true
  51031. });
  51032. Object.defineProperty(PointLight.prototype, "direction", {
  51033. /**
  51034. * Gets the direction if it has been set.
  51035. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  51036. */
  51037. get: function () {
  51038. return this._direction;
  51039. },
  51040. /**
  51041. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  51042. */
  51043. set: function (value) {
  51044. var previousNeedCube = this.needCube();
  51045. this._direction = value;
  51046. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  51047. this._shadowGenerator.recreateShadowMap();
  51048. }
  51049. },
  51050. enumerable: true,
  51051. configurable: true
  51052. });
  51053. /**
  51054. * Returns the string "PointLight"
  51055. * @returns the class name
  51056. */
  51057. PointLight.prototype.getClassName = function () {
  51058. return "PointLight";
  51059. };
  51060. /**
  51061. * Returns the integer 0.
  51062. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  51063. */
  51064. PointLight.prototype.getTypeID = function () {
  51065. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  51066. };
  51067. /**
  51068. * Specifies wether or not the shadowmap should be a cube texture.
  51069. * @returns true if the shadowmap needs to be a cube texture.
  51070. */
  51071. PointLight.prototype.needCube = function () {
  51072. return !this.direction;
  51073. };
  51074. /**
  51075. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  51076. * @param faceIndex The index of the face we are computed the direction to generate shadow
  51077. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  51078. */
  51079. PointLight.prototype.getShadowDirection = function (faceIndex) {
  51080. if (this.direction) {
  51081. return _super.prototype.getShadowDirection.call(this, faceIndex);
  51082. }
  51083. else {
  51084. switch (faceIndex) {
  51085. case 0:
  51086. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  51087. case 1:
  51088. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  51089. case 2:
  51090. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  51091. case 3:
  51092. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  51093. case 4:
  51094. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  51095. case 5:
  51096. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  51097. }
  51098. }
  51099. return BABYLON.Vector3.Zero();
  51100. };
  51101. /**
  51102. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  51103. * - fov = PI / 2
  51104. * - aspect ratio : 1.0
  51105. * - z-near and far equal to the active camera minZ and maxZ.
  51106. * Returns the PointLight.
  51107. */
  51108. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  51109. var activeCamera = this.getScene().activeCamera;
  51110. if (!activeCamera) {
  51111. return;
  51112. }
  51113. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  51114. };
  51115. PointLight.prototype._buildUniformLayout = function () {
  51116. this._uniformBuffer.addUniform("vLightData", 4);
  51117. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  51118. this._uniformBuffer.addUniform("vLightSpecular", 3);
  51119. this._uniformBuffer.addUniform("vLightFalloff", 4);
  51120. this._uniformBuffer.addUniform("shadowsInfo", 3);
  51121. this._uniformBuffer.addUniform("depthValues", 2);
  51122. this._uniformBuffer.create();
  51123. };
  51124. /**
  51125. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  51126. * @param effect The effect to update
  51127. * @param lightIndex The index of the light in the effect to update
  51128. * @returns The point light
  51129. */
  51130. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  51131. if (this.computeTransformedInformation()) {
  51132. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  51133. }
  51134. else {
  51135. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  51136. }
  51137. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, 0, 0, lightIndex);
  51138. return this;
  51139. };
  51140. /**
  51141. * Prepares the list of defines specific to the light type.
  51142. * @param defines the list of defines
  51143. * @param lightIndex defines the index of the light for the effect
  51144. */
  51145. PointLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  51146. defines["POINTLIGHT" + lightIndex] = true;
  51147. };
  51148. __decorate([
  51149. BABYLON.serialize()
  51150. ], PointLight.prototype, "shadowAngle", null);
  51151. return PointLight;
  51152. }(BABYLON.ShadowLight));
  51153. BABYLON.PointLight = PointLight;
  51154. })(BABYLON || (BABYLON = {}));
  51155. //# sourceMappingURL=babylon.pointLight.js.map
  51156. var BABYLON;
  51157. (function (BABYLON) {
  51158. BABYLON.Node.AddNodeConstructor("Light_Type_1", function (name, scene) {
  51159. return function () { return new DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  51160. });
  51161. /**
  51162. * A directional light is defined by a direction (what a surprise!).
  51163. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  51164. * 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.
  51165. * Documentation: https://doc.babylonjs.com/babylon101/lights
  51166. */
  51167. var DirectionalLight = /** @class */ (function (_super) {
  51168. __extends(DirectionalLight, _super);
  51169. /**
  51170. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  51171. * The directional light is emitted from everywhere in the given direction.
  51172. * It can cast shadows.
  51173. * Documentation : http://doc.babylonjs.com/tutorials/lights
  51174. * @param name The friendly name of the light
  51175. * @param direction The direction of the light
  51176. * @param scene The scene the light belongs to
  51177. */
  51178. function DirectionalLight(name, direction, scene) {
  51179. var _this = _super.call(this, name, scene) || this;
  51180. _this._shadowFrustumSize = 0;
  51181. _this._shadowOrthoScale = 0.1;
  51182. /**
  51183. * Automatically compute the projection matrix to best fit (including all the casters)
  51184. * on each frame.
  51185. */
  51186. _this.autoUpdateExtends = true;
  51187. // Cache
  51188. _this._orthoLeft = Number.MAX_VALUE;
  51189. _this._orthoRight = Number.MIN_VALUE;
  51190. _this._orthoTop = Number.MIN_VALUE;
  51191. _this._orthoBottom = Number.MAX_VALUE;
  51192. _this.position = direction.scale(-1.0);
  51193. _this.direction = direction;
  51194. return _this;
  51195. }
  51196. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  51197. /**
  51198. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  51199. */
  51200. get: function () {
  51201. return this._shadowFrustumSize;
  51202. },
  51203. /**
  51204. * Specifies a fix frustum size for the shadow generation.
  51205. */
  51206. set: function (value) {
  51207. this._shadowFrustumSize = value;
  51208. this.forceProjectionMatrixCompute();
  51209. },
  51210. enumerable: true,
  51211. configurable: true
  51212. });
  51213. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  51214. /**
  51215. * Gets the shadow projection scale against the optimal computed one.
  51216. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  51217. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  51218. */
  51219. get: function () {
  51220. return this._shadowOrthoScale;
  51221. },
  51222. /**
  51223. * Sets the shadow projection scale against the optimal computed one.
  51224. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  51225. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  51226. */
  51227. set: function (value) {
  51228. this._shadowOrthoScale = value;
  51229. this.forceProjectionMatrixCompute();
  51230. },
  51231. enumerable: true,
  51232. configurable: true
  51233. });
  51234. /**
  51235. * Returns the string "DirectionalLight".
  51236. * @return The class name
  51237. */
  51238. DirectionalLight.prototype.getClassName = function () {
  51239. return "DirectionalLight";
  51240. };
  51241. /**
  51242. * Returns the integer 1.
  51243. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  51244. */
  51245. DirectionalLight.prototype.getTypeID = function () {
  51246. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  51247. };
  51248. /**
  51249. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  51250. * Returns the DirectionalLight Shadow projection matrix.
  51251. */
  51252. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  51253. if (this.shadowFrustumSize > 0) {
  51254. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  51255. }
  51256. else {
  51257. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  51258. }
  51259. };
  51260. /**
  51261. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  51262. * Returns the DirectionalLight Shadow projection matrix.
  51263. */
  51264. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  51265. var activeCamera = this.getScene().activeCamera;
  51266. if (!activeCamera) {
  51267. return;
  51268. }
  51269. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  51270. };
  51271. /**
  51272. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  51273. * Returns the DirectionalLight Shadow projection matrix.
  51274. */
  51275. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  51276. var activeCamera = this.getScene().activeCamera;
  51277. if (!activeCamera) {
  51278. return;
  51279. }
  51280. // Check extends
  51281. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  51282. var tempVector3 = BABYLON.Vector3.Zero();
  51283. this._orthoLeft = Number.MAX_VALUE;
  51284. this._orthoRight = Number.MIN_VALUE;
  51285. this._orthoTop = Number.MIN_VALUE;
  51286. this._orthoBottom = Number.MAX_VALUE;
  51287. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  51288. var mesh = renderList[meshIndex];
  51289. if (!mesh) {
  51290. continue;
  51291. }
  51292. var boundingInfo = mesh.getBoundingInfo();
  51293. var boundingBox = boundingInfo.boundingBox;
  51294. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  51295. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  51296. if (tempVector3.x < this._orthoLeft)
  51297. this._orthoLeft = tempVector3.x;
  51298. if (tempVector3.y < this._orthoBottom)
  51299. this._orthoBottom = tempVector3.y;
  51300. if (tempVector3.x > this._orthoRight)
  51301. this._orthoRight = tempVector3.x;
  51302. if (tempVector3.y > this._orthoTop)
  51303. this._orthoTop = tempVector3.y;
  51304. }
  51305. }
  51306. }
  51307. var xOffset = this._orthoRight - this._orthoLeft;
  51308. var yOffset = this._orthoTop - this._orthoBottom;
  51309. 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);
  51310. };
  51311. DirectionalLight.prototype._buildUniformLayout = function () {
  51312. this._uniformBuffer.addUniform("vLightData", 4);
  51313. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  51314. this._uniformBuffer.addUniform("vLightSpecular", 3);
  51315. this._uniformBuffer.addUniform("shadowsInfo", 3);
  51316. this._uniformBuffer.addUniform("depthValues", 2);
  51317. this._uniformBuffer.create();
  51318. };
  51319. /**
  51320. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  51321. * @param effect The effect to update
  51322. * @param lightIndex The index of the light in the effect to update
  51323. * @returns The directional light
  51324. */
  51325. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  51326. if (this.computeTransformedInformation()) {
  51327. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  51328. return this;
  51329. }
  51330. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  51331. return this;
  51332. };
  51333. /**
  51334. * Gets the minZ used for shadow according to both the scene and the light.
  51335. *
  51336. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  51337. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  51338. * @param activeCamera The camera we are returning the min for
  51339. * @returns the depth min z
  51340. */
  51341. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  51342. return 1;
  51343. };
  51344. /**
  51345. * Gets the maxZ used for shadow according to both the scene and the light.
  51346. *
  51347. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  51348. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  51349. * @param activeCamera The camera we are returning the max for
  51350. * @returns the depth max z
  51351. */
  51352. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  51353. return 1;
  51354. };
  51355. /**
  51356. * Prepares the list of defines specific to the light type.
  51357. * @param defines the list of defines
  51358. * @param lightIndex defines the index of the light for the effect
  51359. */
  51360. DirectionalLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  51361. defines["DIRLIGHT" + lightIndex] = true;
  51362. };
  51363. __decorate([
  51364. BABYLON.serialize()
  51365. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  51366. __decorate([
  51367. BABYLON.serialize()
  51368. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  51369. __decorate([
  51370. BABYLON.serialize()
  51371. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  51372. return DirectionalLight;
  51373. }(BABYLON.ShadowLight));
  51374. BABYLON.DirectionalLight = DirectionalLight;
  51375. })(BABYLON || (BABYLON = {}));
  51376. //# sourceMappingURL=babylon.directionalLight.js.map
  51377. var BABYLON;
  51378. (function (BABYLON) {
  51379. BABYLON.Node.AddNodeConstructor("Light_Type_2", function (name, scene) {
  51380. return function () { return new SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  51381. });
  51382. /**
  51383. * A spot light is defined by a position, a direction, an angle, and an exponent.
  51384. * These values define a cone of light starting from the position, emitting toward the direction.
  51385. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  51386. * and the exponent defines the speed of the decay of the light with distance (reach).
  51387. * Documentation: https://doc.babylonjs.com/babylon101/lights
  51388. */
  51389. var SpotLight = /** @class */ (function (_super) {
  51390. __extends(SpotLight, _super);
  51391. /**
  51392. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  51393. * It can cast shadows.
  51394. * Documentation : http://doc.babylonjs.com/tutorials/lights
  51395. * @param name The light friendly name
  51396. * @param position The position of the spot light in the scene
  51397. * @param direction The direction of the light in the scene
  51398. * @param angle The cone angle of the light in Radians
  51399. * @param exponent The light decay speed with the distance from the emission spot
  51400. * @param scene The scene the lights belongs to
  51401. */
  51402. function SpotLight(name, position, direction, angle, exponent, scene) {
  51403. var _this = _super.call(this, name, scene) || this;
  51404. _this._innerAngle = 0;
  51405. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  51406. _this._projectionTextureLightNear = 1e-6;
  51407. _this._projectionTextureLightFar = 1000.0;
  51408. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  51409. _this._projectionTextureViewLightDirty = true;
  51410. _this._projectionTextureProjectionLightDirty = true;
  51411. _this._projectionTextureDirty = true;
  51412. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  51413. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  51414. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  51415. _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);
  51416. _this.position = position;
  51417. _this.direction = direction;
  51418. _this.angle = angle;
  51419. _this.exponent = exponent;
  51420. return _this;
  51421. }
  51422. Object.defineProperty(SpotLight.prototype, "angle", {
  51423. /**
  51424. * Gets the cone angle of the spot light in Radians.
  51425. */
  51426. get: function () {
  51427. return this._angle;
  51428. },
  51429. /**
  51430. * Sets the cone angle of the spot light in Radians.
  51431. */
  51432. set: function (value) {
  51433. this._angle = value;
  51434. this._cosHalfAngle = Math.cos(value * 0.5);
  51435. this._projectionTextureProjectionLightDirty = true;
  51436. this.forceProjectionMatrixCompute();
  51437. this._computeAngleValues();
  51438. },
  51439. enumerable: true,
  51440. configurable: true
  51441. });
  51442. Object.defineProperty(SpotLight.prototype, "innerAngle", {
  51443. /**
  51444. * Only used in gltf falloff mode, this defines the angle where
  51445. * the directional falloff will start before cutting at angle which could be seen
  51446. * as outer angle.
  51447. */
  51448. get: function () {
  51449. return this._innerAngle;
  51450. },
  51451. /**
  51452. * Only used in gltf falloff mode, this defines the angle where
  51453. * the directional falloff will start before cutting at angle which could be seen
  51454. * as outer angle.
  51455. */
  51456. set: function (value) {
  51457. this._innerAngle = value;
  51458. this._computeAngleValues();
  51459. },
  51460. enumerable: true,
  51461. configurable: true
  51462. });
  51463. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  51464. /**
  51465. * Allows scaling the angle of the light for shadow generation only.
  51466. */
  51467. get: function () {
  51468. return this._shadowAngleScale;
  51469. },
  51470. /**
  51471. * Allows scaling the angle of the light for shadow generation only.
  51472. */
  51473. set: function (value) {
  51474. this._shadowAngleScale = value;
  51475. this.forceProjectionMatrixCompute();
  51476. },
  51477. enumerable: true,
  51478. configurable: true
  51479. });
  51480. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  51481. /**
  51482. * Allows reading the projecton texture
  51483. */
  51484. get: function () {
  51485. return this._projectionTextureMatrix;
  51486. },
  51487. enumerable: true,
  51488. configurable: true
  51489. });
  51490. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  51491. /**
  51492. * Gets the near clip of the Spotlight for texture projection.
  51493. */
  51494. get: function () {
  51495. return this._projectionTextureLightNear;
  51496. },
  51497. /**
  51498. * Sets the near clip of the Spotlight for texture projection.
  51499. */
  51500. set: function (value) {
  51501. this._projectionTextureLightNear = value;
  51502. this._projectionTextureProjectionLightDirty = true;
  51503. },
  51504. enumerable: true,
  51505. configurable: true
  51506. });
  51507. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  51508. /**
  51509. * Gets the far clip of the Spotlight for texture projection.
  51510. */
  51511. get: function () {
  51512. return this._projectionTextureLightFar;
  51513. },
  51514. /**
  51515. * Sets the far clip of the Spotlight for texture projection.
  51516. */
  51517. set: function (value) {
  51518. this._projectionTextureLightFar = value;
  51519. this._projectionTextureProjectionLightDirty = true;
  51520. },
  51521. enumerable: true,
  51522. configurable: true
  51523. });
  51524. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  51525. /**
  51526. * Gets the Up vector of the Spotlight for texture projection.
  51527. */
  51528. get: function () {
  51529. return this._projectionTextureUpDirection;
  51530. },
  51531. /**
  51532. * Sets the Up vector of the Spotlight for texture projection.
  51533. */
  51534. set: function (value) {
  51535. this._projectionTextureUpDirection = value;
  51536. this._projectionTextureProjectionLightDirty = true;
  51537. },
  51538. enumerable: true,
  51539. configurable: true
  51540. });
  51541. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  51542. /**
  51543. * Gets the projection texture of the light.
  51544. */
  51545. get: function () {
  51546. return this._projectionTexture;
  51547. },
  51548. /**
  51549. * Sets the projection texture of the light.
  51550. */
  51551. set: function (value) {
  51552. this._projectionTexture = value;
  51553. this._projectionTextureDirty = true;
  51554. },
  51555. enumerable: true,
  51556. configurable: true
  51557. });
  51558. /**
  51559. * Returns the string "SpotLight".
  51560. * @returns the class name
  51561. */
  51562. SpotLight.prototype.getClassName = function () {
  51563. return "SpotLight";
  51564. };
  51565. /**
  51566. * Returns the integer 2.
  51567. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  51568. */
  51569. SpotLight.prototype.getTypeID = function () {
  51570. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  51571. };
  51572. /**
  51573. * Overrides the direction setter to recompute the projection texture view light Matrix.
  51574. */
  51575. SpotLight.prototype._setDirection = function (value) {
  51576. _super.prototype._setDirection.call(this, value);
  51577. this._projectionTextureViewLightDirty = true;
  51578. };
  51579. /**
  51580. * Overrides the position setter to recompute the projection texture view light Matrix.
  51581. */
  51582. SpotLight.prototype._setPosition = function (value) {
  51583. _super.prototype._setPosition.call(this, value);
  51584. this._projectionTextureViewLightDirty = true;
  51585. };
  51586. /**
  51587. * 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.
  51588. * Returns the SpotLight.
  51589. */
  51590. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  51591. var activeCamera = this.getScene().activeCamera;
  51592. if (!activeCamera) {
  51593. return;
  51594. }
  51595. this._shadowAngleScale = this._shadowAngleScale || 1;
  51596. var angle = this._shadowAngleScale * this._angle;
  51597. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  51598. };
  51599. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  51600. this._projectionTextureViewLightDirty = false;
  51601. this._projectionTextureDirty = true;
  51602. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  51603. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  51604. };
  51605. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  51606. this._projectionTextureProjectionLightDirty = false;
  51607. this._projectionTextureDirty = true;
  51608. var light_far = this.projectionTextureLightFar;
  51609. var light_near = this.projectionTextureLightNear;
  51610. var P = light_far / (light_far - light_near);
  51611. var Q = -P * light_near;
  51612. var S = 1.0 / Math.tan(this._angle / 2.0);
  51613. var A = 1.0;
  51614. 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);
  51615. };
  51616. /**
  51617. * Main function for light texture projection matrix computing.
  51618. */
  51619. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  51620. this._projectionTextureDirty = false;
  51621. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  51622. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  51623. };
  51624. SpotLight.prototype._buildUniformLayout = function () {
  51625. this._uniformBuffer.addUniform("vLightData", 4);
  51626. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  51627. this._uniformBuffer.addUniform("vLightSpecular", 3);
  51628. this._uniformBuffer.addUniform("vLightDirection", 3);
  51629. this._uniformBuffer.addUniform("vLightFalloff", 4);
  51630. this._uniformBuffer.addUniform("shadowsInfo", 3);
  51631. this._uniformBuffer.addUniform("depthValues", 2);
  51632. this._uniformBuffer.create();
  51633. };
  51634. SpotLight.prototype._computeAngleValues = function () {
  51635. this._lightAngleScale = 1.0 / Math.max(0.001, (Math.cos(this._innerAngle * 0.5) - this._cosHalfAngle));
  51636. this._lightAngleOffset = -this._cosHalfAngle * this._lightAngleScale;
  51637. };
  51638. /**
  51639. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  51640. * @param effect The effect to update
  51641. * @param lightIndex The index of the light in the effect to update
  51642. * @returns The spot light
  51643. */
  51644. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  51645. var normalizeDirection;
  51646. if (this.computeTransformedInformation()) {
  51647. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  51648. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  51649. }
  51650. else {
  51651. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  51652. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  51653. }
  51654. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, this._cosHalfAngle, lightIndex);
  51655. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, this._lightAngleScale, this._lightAngleOffset, lightIndex);
  51656. if (this.projectionTexture && this.projectionTexture.isReady()) {
  51657. if (this._projectionTextureViewLightDirty) {
  51658. this._computeProjectionTextureViewLightMatrix();
  51659. }
  51660. if (this._projectionTextureProjectionLightDirty) {
  51661. this._computeProjectionTextureProjectionLightMatrix();
  51662. }
  51663. if (this._projectionTextureDirty) {
  51664. this._computeProjectionTextureMatrix();
  51665. }
  51666. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  51667. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  51668. }
  51669. return this;
  51670. };
  51671. /**
  51672. * Disposes the light and the associated resources.
  51673. */
  51674. SpotLight.prototype.dispose = function () {
  51675. _super.prototype.dispose.call(this);
  51676. if (this._projectionTexture) {
  51677. this._projectionTexture.dispose();
  51678. }
  51679. };
  51680. /**
  51681. * Prepares the list of defines specific to the light type.
  51682. * @param defines the list of defines
  51683. * @param lightIndex defines the index of the light for the effect
  51684. */
  51685. SpotLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  51686. defines["SPOTLIGHT" + lightIndex] = true;
  51687. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = this.projectionTexture ? true : false;
  51688. };
  51689. __decorate([
  51690. BABYLON.serialize()
  51691. ], SpotLight.prototype, "angle", null);
  51692. __decorate([
  51693. BABYLON.serialize()
  51694. ], SpotLight.prototype, "innerAngle", null);
  51695. __decorate([
  51696. BABYLON.serialize()
  51697. ], SpotLight.prototype, "shadowAngleScale", null);
  51698. __decorate([
  51699. BABYLON.serialize()
  51700. ], SpotLight.prototype, "exponent", void 0);
  51701. __decorate([
  51702. BABYLON.serialize()
  51703. ], SpotLight.prototype, "projectionTextureLightNear", null);
  51704. __decorate([
  51705. BABYLON.serialize()
  51706. ], SpotLight.prototype, "projectionTextureLightFar", null);
  51707. __decorate([
  51708. BABYLON.serialize()
  51709. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  51710. __decorate([
  51711. BABYLON.serializeAsTexture("projectedLightTexture")
  51712. ], SpotLight.prototype, "_projectionTexture", void 0);
  51713. return SpotLight;
  51714. }(BABYLON.ShadowLight));
  51715. BABYLON.SpotLight = SpotLight;
  51716. })(BABYLON || (BABYLON = {}));
  51717. //# sourceMappingURL=babylon.spotLight.js.map
  51718. var BABYLON;
  51719. (function (BABYLON) {
  51720. /**
  51721. * Class used to override all child animations of a given target
  51722. */
  51723. var AnimationPropertiesOverride = /** @class */ (function () {
  51724. function AnimationPropertiesOverride() {
  51725. /**
  51726. * Gets or sets a value indicating if animation blending must be used
  51727. */
  51728. this.enableBlending = false;
  51729. /**
  51730. * Gets or sets the blending speed to use when enableBlending is true
  51731. */
  51732. this.blendingSpeed = 0.01;
  51733. /**
  51734. * Gets or sets the default loop mode to use
  51735. */
  51736. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  51737. }
  51738. return AnimationPropertiesOverride;
  51739. }());
  51740. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  51741. })(BABYLON || (BABYLON = {}));
  51742. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  51743. var BABYLON;
  51744. (function (BABYLON) {
  51745. /**
  51746. * Represents the range of an animation
  51747. */
  51748. var AnimationRange = /** @class */ (function () {
  51749. /**
  51750. * Initializes the range of an animation
  51751. * @param name The name of the animation range
  51752. * @param from The starting frame of the animation
  51753. * @param to The ending frame of the animation
  51754. */
  51755. function AnimationRange(
  51756. /**The name of the animation range**/
  51757. name,
  51758. /**The starting frame of the animation */
  51759. from,
  51760. /**The ending frame of the animation*/
  51761. to) {
  51762. this.name = name;
  51763. this.from = from;
  51764. this.to = to;
  51765. }
  51766. /**
  51767. * Makes a copy of the animation range
  51768. * @returns A copy of the animation range
  51769. */
  51770. AnimationRange.prototype.clone = function () {
  51771. return new AnimationRange(this.name, this.from, this.to);
  51772. };
  51773. return AnimationRange;
  51774. }());
  51775. BABYLON.AnimationRange = AnimationRange;
  51776. /**
  51777. * Composed of a frame, and an action function
  51778. */
  51779. var AnimationEvent = /** @class */ (function () {
  51780. /**
  51781. * Initializes the animation event
  51782. * @param frame The frame for which the event is triggered
  51783. * @param action The event to perform when triggered
  51784. * @param onlyOnce Specifies if the event should be triggered only once
  51785. */
  51786. function AnimationEvent(
  51787. /** The frame for which the event is triggered **/
  51788. frame,
  51789. /** The event to perform when triggered **/
  51790. action,
  51791. /** Specifies if the event should be triggered only once**/
  51792. onlyOnce) {
  51793. this.frame = frame;
  51794. this.action = action;
  51795. this.onlyOnce = onlyOnce;
  51796. /**
  51797. * Specifies if the animation event is done
  51798. */
  51799. this.isDone = false;
  51800. }
  51801. /** @hidden */
  51802. AnimationEvent.prototype._clone = function () {
  51803. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  51804. };
  51805. return AnimationEvent;
  51806. }());
  51807. BABYLON.AnimationEvent = AnimationEvent;
  51808. /**
  51809. * A cursor which tracks a point on a path
  51810. */
  51811. var PathCursor = /** @class */ (function () {
  51812. /**
  51813. * Initializes the path cursor
  51814. * @param path The path to track
  51815. */
  51816. function PathCursor(path) {
  51817. this.path = path;
  51818. /**
  51819. * Stores path cursor callbacks for when an onchange event is triggered
  51820. */
  51821. this._onchange = new Array();
  51822. /**
  51823. * The value of the path cursor
  51824. */
  51825. this.value = 0;
  51826. /**
  51827. * The animation array of the path cursor
  51828. */
  51829. this.animations = new Array();
  51830. }
  51831. /**
  51832. * Gets the cursor point on the path
  51833. * @returns A point on the path cursor at the cursor location
  51834. */
  51835. PathCursor.prototype.getPoint = function () {
  51836. var point = this.path.getPointAtLengthPosition(this.value);
  51837. return new BABYLON.Vector3(point.x, 0, point.y);
  51838. };
  51839. /**
  51840. * Moves the cursor ahead by the step amount
  51841. * @param step The amount to move the cursor forward
  51842. * @returns This path cursor
  51843. */
  51844. PathCursor.prototype.moveAhead = function (step) {
  51845. if (step === void 0) { step = 0.002; }
  51846. this.move(step);
  51847. return this;
  51848. };
  51849. /**
  51850. * Moves the cursor behind by the step amount
  51851. * @param step The amount to move the cursor back
  51852. * @returns This path cursor
  51853. */
  51854. PathCursor.prototype.moveBack = function (step) {
  51855. if (step === void 0) { step = 0.002; }
  51856. this.move(-step);
  51857. return this;
  51858. };
  51859. /**
  51860. * Moves the cursor by the step amount
  51861. * If the step amount is greater than one, an exception is thrown
  51862. * @param step The amount to move the cursor
  51863. * @returns This path cursor
  51864. */
  51865. PathCursor.prototype.move = function (step) {
  51866. if (Math.abs(step) > 1) {
  51867. throw "step size should be less than 1.";
  51868. }
  51869. this.value += step;
  51870. this.ensureLimits();
  51871. this.raiseOnChange();
  51872. return this;
  51873. };
  51874. /**
  51875. * Ensures that the value is limited between zero and one
  51876. * @returns This path cursor
  51877. */
  51878. PathCursor.prototype.ensureLimits = function () {
  51879. while (this.value > 1) {
  51880. this.value -= 1;
  51881. }
  51882. while (this.value < 0) {
  51883. this.value += 1;
  51884. }
  51885. return this;
  51886. };
  51887. /**
  51888. * Runs onchange callbacks on change (used by the animation engine)
  51889. * @returns This path cursor
  51890. */
  51891. PathCursor.prototype.raiseOnChange = function () {
  51892. var _this = this;
  51893. this._onchange.forEach(function (f) { return f(_this); });
  51894. return this;
  51895. };
  51896. /**
  51897. * Executes a function on change
  51898. * @param f A path cursor onchange callback
  51899. * @returns This path cursor
  51900. */
  51901. PathCursor.prototype.onchange = function (f) {
  51902. this._onchange.push(f);
  51903. return this;
  51904. };
  51905. return PathCursor;
  51906. }());
  51907. BABYLON.PathCursor = PathCursor;
  51908. /**
  51909. * Enum for the animation key frame interpolation type
  51910. */
  51911. var AnimationKeyInterpolation;
  51912. (function (AnimationKeyInterpolation) {
  51913. /**
  51914. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  51915. */
  51916. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  51917. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  51918. /**
  51919. * Class used to store any kind of animation
  51920. */
  51921. var Animation = /** @class */ (function () {
  51922. /**
  51923. * Initializes the animation
  51924. * @param name Name of the animation
  51925. * @param targetProperty Property to animate
  51926. * @param framePerSecond The frames per second of the animation
  51927. * @param dataType The data type of the animation
  51928. * @param loopMode The loop mode of the animation
  51929. * @param enableBlendings Specifies if blending should be enabled
  51930. */
  51931. function Animation(
  51932. /**Name of the animation */
  51933. name,
  51934. /**Property to animate */
  51935. targetProperty,
  51936. /**The frames per second of the animation */
  51937. framePerSecond,
  51938. /**The data type of the animation */
  51939. dataType,
  51940. /**The loop mode of the animation */
  51941. loopMode,
  51942. /**Specifies if blending should be enabled */
  51943. enableBlending) {
  51944. this.name = name;
  51945. this.targetProperty = targetProperty;
  51946. this.framePerSecond = framePerSecond;
  51947. this.dataType = dataType;
  51948. this.loopMode = loopMode;
  51949. this.enableBlending = enableBlending;
  51950. /**
  51951. * @hidden Internal use only
  51952. */
  51953. this._runtimeAnimations = new Array();
  51954. /**
  51955. * The set of event that will be linked to this animation
  51956. */
  51957. this._events = new Array();
  51958. /**
  51959. * Stores the blending speed of the animation
  51960. */
  51961. this.blendingSpeed = 0.01;
  51962. /**
  51963. * Stores the animation ranges for the animation
  51964. */
  51965. this._ranges = {};
  51966. this.targetPropertyPath = targetProperty.split(".");
  51967. this.dataType = dataType;
  51968. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  51969. }
  51970. /**
  51971. * @hidden Internal use
  51972. */
  51973. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  51974. var dataType = undefined;
  51975. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  51976. dataType = Animation.ANIMATIONTYPE_FLOAT;
  51977. }
  51978. else if (from instanceof BABYLON.Quaternion) {
  51979. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  51980. }
  51981. else if (from instanceof BABYLON.Vector3) {
  51982. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  51983. }
  51984. else if (from instanceof BABYLON.Vector2) {
  51985. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  51986. }
  51987. else if (from instanceof BABYLON.Color3) {
  51988. dataType = Animation.ANIMATIONTYPE_COLOR3;
  51989. }
  51990. else if (from instanceof BABYLON.Size) {
  51991. dataType = Animation.ANIMATIONTYPE_SIZE;
  51992. }
  51993. if (dataType == undefined) {
  51994. return null;
  51995. }
  51996. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  51997. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  51998. animation.setKeys(keys);
  51999. if (easingFunction !== undefined) {
  52000. animation.setEasingFunction(easingFunction);
  52001. }
  52002. return animation;
  52003. };
  52004. /**
  52005. * Sets up an animation
  52006. * @param property The property to animate
  52007. * @param animationType The animation type to apply
  52008. * @param framePerSecond The frames per second of the animation
  52009. * @param easingFunction The easing function used in the animation
  52010. * @returns The created animation
  52011. */
  52012. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  52013. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  52014. animation.setEasingFunction(easingFunction);
  52015. return animation;
  52016. };
  52017. /**
  52018. * Create and start an animation on a node
  52019. * @param name defines the name of the global animation that will be run on all nodes
  52020. * @param node defines the root node where the animation will take place
  52021. * @param targetProperty defines property to animate
  52022. * @param framePerSecond defines the number of frame per second yo use
  52023. * @param totalFrame defines the number of frames in total
  52024. * @param from defines the initial value
  52025. * @param to defines the final value
  52026. * @param loopMode defines which loop mode you want to use (off by default)
  52027. * @param easingFunction defines the easing function to use (linear by default)
  52028. * @param onAnimationEnd defines the callback to call when animation end
  52029. * @returns the animatable created for this animation
  52030. */
  52031. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  52032. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  52033. if (!animation) {
  52034. return null;
  52035. }
  52036. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  52037. };
  52038. /**
  52039. * Create and start an animation on a node and its descendants
  52040. * @param name defines the name of the global animation that will be run on all nodes
  52041. * @param node defines the root node where the animation will take place
  52042. * @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
  52043. * @param targetProperty defines property to animate
  52044. * @param framePerSecond defines the number of frame per second to use
  52045. * @param totalFrame defines the number of frames in total
  52046. * @param from defines the initial value
  52047. * @param to defines the final value
  52048. * @param loopMode defines which loop mode you want to use (off by default)
  52049. * @param easingFunction defines the easing function to use (linear by default)
  52050. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  52051. * @returns the list of animatables created for all nodes
  52052. * @example https://www.babylonjs-playground.com/#MH0VLI
  52053. */
  52054. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  52055. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  52056. if (!animation) {
  52057. return null;
  52058. }
  52059. var scene = node.getScene();
  52060. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  52061. };
  52062. /**
  52063. * Creates a new animation, merges it with the existing animations and starts it
  52064. * @param name Name of the animation
  52065. * @param node Node which contains the scene that begins the animations
  52066. * @param targetProperty Specifies which property to animate
  52067. * @param framePerSecond The frames per second of the animation
  52068. * @param totalFrame The total number of frames
  52069. * @param from The frame at the beginning of the animation
  52070. * @param to The frame at the end of the animation
  52071. * @param loopMode Specifies the loop mode of the animation
  52072. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  52073. * @param onAnimationEnd Callback to run once the animation is complete
  52074. * @returns Nullable animation
  52075. */
  52076. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  52077. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  52078. if (!animation) {
  52079. return null;
  52080. }
  52081. node.animations.push(animation);
  52082. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  52083. };
  52084. /**
  52085. * Transition property of an host to the target Value
  52086. * @param property The property to transition
  52087. * @param targetValue The target Value of the property
  52088. * @param host The object where the property to animate belongs
  52089. * @param scene Scene used to run the animation
  52090. * @param frameRate Framerate (in frame/s) to use
  52091. * @param transition The transition type we want to use
  52092. * @param duration The duration of the animation, in milliseconds
  52093. * @param onAnimationEnd Callback trigger at the end of the animation
  52094. * @returns Nullable animation
  52095. */
  52096. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  52097. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  52098. if (duration <= 0) {
  52099. host[property] = targetValue;
  52100. if (onAnimationEnd) {
  52101. onAnimationEnd();
  52102. }
  52103. return null;
  52104. }
  52105. var endFrame = frameRate * (duration / 1000);
  52106. transition.setKeys([{
  52107. frame: 0,
  52108. value: host[property].clone ? host[property].clone() : host[property]
  52109. },
  52110. {
  52111. frame: endFrame,
  52112. value: targetValue
  52113. }]);
  52114. if (!host.animations) {
  52115. host.animations = [];
  52116. }
  52117. host.animations.push(transition);
  52118. var animation = scene.beginAnimation(host, 0, endFrame, false);
  52119. animation.onAnimationEnd = onAnimationEnd;
  52120. return animation;
  52121. };
  52122. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  52123. /**
  52124. * Return the array of runtime animations currently using this animation
  52125. */
  52126. get: function () {
  52127. return this._runtimeAnimations;
  52128. },
  52129. enumerable: true,
  52130. configurable: true
  52131. });
  52132. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  52133. /**
  52134. * Specifies if any of the runtime animations are currently running
  52135. */
  52136. get: function () {
  52137. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  52138. var runtimeAnimation = _a[_i];
  52139. if (!runtimeAnimation.isStopped) {
  52140. return true;
  52141. }
  52142. }
  52143. return false;
  52144. },
  52145. enumerable: true,
  52146. configurable: true
  52147. });
  52148. // Methods
  52149. /**
  52150. * Converts the animation to a string
  52151. * @param fullDetails support for multiple levels of logging within scene loading
  52152. * @returns String form of the animation
  52153. */
  52154. Animation.prototype.toString = function (fullDetails) {
  52155. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  52156. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  52157. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  52158. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  52159. if (fullDetails) {
  52160. ret += ", Ranges: {";
  52161. var first = true;
  52162. for (var name in this._ranges) {
  52163. if (first) {
  52164. ret += ", ";
  52165. first = false;
  52166. }
  52167. ret += name;
  52168. }
  52169. ret += "}";
  52170. }
  52171. return ret;
  52172. };
  52173. /**
  52174. * Add an event to this animation
  52175. * @param event Event to add
  52176. */
  52177. Animation.prototype.addEvent = function (event) {
  52178. this._events.push(event);
  52179. };
  52180. /**
  52181. * Remove all events found at the given frame
  52182. * @param frame The frame to remove events from
  52183. */
  52184. Animation.prototype.removeEvents = function (frame) {
  52185. for (var index = 0; index < this._events.length; index++) {
  52186. if (this._events[index].frame === frame) {
  52187. this._events.splice(index, 1);
  52188. index--;
  52189. }
  52190. }
  52191. };
  52192. /**
  52193. * Retrieves all the events from the animation
  52194. * @returns Events from the animation
  52195. */
  52196. Animation.prototype.getEvents = function () {
  52197. return this._events;
  52198. };
  52199. /**
  52200. * Creates an animation range
  52201. * @param name Name of the animation range
  52202. * @param from Starting frame of the animation range
  52203. * @param to Ending frame of the animation
  52204. */
  52205. Animation.prototype.createRange = function (name, from, to) {
  52206. // check name not already in use; could happen for bones after serialized
  52207. if (!this._ranges[name]) {
  52208. this._ranges[name] = new AnimationRange(name, from, to);
  52209. }
  52210. };
  52211. /**
  52212. * Deletes an animation range by name
  52213. * @param name Name of the animation range to delete
  52214. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  52215. */
  52216. Animation.prototype.deleteRange = function (name, deleteFrames) {
  52217. if (deleteFrames === void 0) { deleteFrames = true; }
  52218. var range = this._ranges[name];
  52219. if (!range) {
  52220. return;
  52221. }
  52222. if (deleteFrames) {
  52223. var from = range.from;
  52224. var to = range.to;
  52225. // this loop MUST go high to low for multiple splices to work
  52226. for (var key = this._keys.length - 1; key >= 0; key--) {
  52227. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  52228. this._keys.splice(key, 1);
  52229. }
  52230. }
  52231. }
  52232. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  52233. };
  52234. /**
  52235. * Gets the animation range by name, or null if not defined
  52236. * @param name Name of the animation range
  52237. * @returns Nullable animation range
  52238. */
  52239. Animation.prototype.getRange = function (name) {
  52240. return this._ranges[name];
  52241. };
  52242. /**
  52243. * Gets the key frames from the animation
  52244. * @returns The key frames of the animation
  52245. */
  52246. Animation.prototype.getKeys = function () {
  52247. return this._keys;
  52248. };
  52249. /**
  52250. * Gets the highest frame rate of the animation
  52251. * @returns Highest frame rate of the animation
  52252. */
  52253. Animation.prototype.getHighestFrame = function () {
  52254. var ret = 0;
  52255. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  52256. if (ret < this._keys[key].frame) {
  52257. ret = this._keys[key].frame;
  52258. }
  52259. }
  52260. return ret;
  52261. };
  52262. /**
  52263. * Gets the easing function of the animation
  52264. * @returns Easing function of the animation
  52265. */
  52266. Animation.prototype.getEasingFunction = function () {
  52267. return this._easingFunction;
  52268. };
  52269. /**
  52270. * Sets the easing function of the animation
  52271. * @param easingFunction A custom mathematical formula for animation
  52272. */
  52273. Animation.prototype.setEasingFunction = function (easingFunction) {
  52274. this._easingFunction = easingFunction;
  52275. };
  52276. /**
  52277. * Interpolates a scalar linearly
  52278. * @param startValue Start value of the animation curve
  52279. * @param endValue End value of the animation curve
  52280. * @param gradient Scalar amount to interpolate
  52281. * @returns Interpolated scalar value
  52282. */
  52283. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  52284. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  52285. };
  52286. /**
  52287. * Interpolates a scalar cubically
  52288. * @param startValue Start value of the animation curve
  52289. * @param outTangent End tangent of the animation
  52290. * @param endValue End value of the animation curve
  52291. * @param inTangent Start tangent of the animation curve
  52292. * @param gradient Scalar amount to interpolate
  52293. * @returns Interpolated scalar value
  52294. */
  52295. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  52296. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  52297. };
  52298. /**
  52299. * Interpolates a quaternion using a spherical linear interpolation
  52300. * @param startValue Start value of the animation curve
  52301. * @param endValue End value of the animation curve
  52302. * @param gradient Scalar amount to interpolate
  52303. * @returns Interpolated quaternion value
  52304. */
  52305. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  52306. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  52307. };
  52308. /**
  52309. * Interpolates a quaternion cubically
  52310. * @param startValue Start value of the animation curve
  52311. * @param outTangent End tangent of the animation curve
  52312. * @param endValue End value of the animation curve
  52313. * @param inTangent Start tangent of the animation curve
  52314. * @param gradient Scalar amount to interpolate
  52315. * @returns Interpolated quaternion value
  52316. */
  52317. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  52318. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  52319. };
  52320. /**
  52321. * Interpolates a Vector3 linearl
  52322. * @param startValue Start value of the animation curve
  52323. * @param endValue End value of the animation curve
  52324. * @param gradient Scalar amount to interpolate
  52325. * @returns Interpolated scalar value
  52326. */
  52327. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  52328. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  52329. };
  52330. /**
  52331. * Interpolates a Vector3 cubically
  52332. * @param startValue Start value of the animation curve
  52333. * @param outTangent End tangent of the animation
  52334. * @param endValue End value of the animation curve
  52335. * @param inTangent Start tangent of the animation curve
  52336. * @param gradient Scalar amount to interpolate
  52337. * @returns InterpolatedVector3 value
  52338. */
  52339. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  52340. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  52341. };
  52342. /**
  52343. * Interpolates a Vector2 linearly
  52344. * @param startValue Start value of the animation curve
  52345. * @param endValue End value of the animation curve
  52346. * @param gradient Scalar amount to interpolate
  52347. * @returns Interpolated Vector2 value
  52348. */
  52349. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  52350. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  52351. };
  52352. /**
  52353. * Interpolates a Vector2 cubically
  52354. * @param startValue Start value of the animation curve
  52355. * @param outTangent End tangent of the animation
  52356. * @param endValue End value of the animation curve
  52357. * @param inTangent Start tangent of the animation curve
  52358. * @param gradient Scalar amount to interpolate
  52359. * @returns Interpolated Vector2 value
  52360. */
  52361. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  52362. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  52363. };
  52364. /**
  52365. * Interpolates a size linearly
  52366. * @param startValue Start value of the animation curve
  52367. * @param endValue End value of the animation curve
  52368. * @param gradient Scalar amount to interpolate
  52369. * @returns Interpolated Size value
  52370. */
  52371. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  52372. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  52373. };
  52374. /**
  52375. * Interpolates a Color3 linearly
  52376. * @param startValue Start value of the animation curve
  52377. * @param endValue End value of the animation curve
  52378. * @param gradient Scalar amount to interpolate
  52379. * @returns Interpolated Color3 value
  52380. */
  52381. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  52382. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  52383. };
  52384. /**
  52385. * @hidden Internal use only
  52386. */
  52387. Animation.prototype._getKeyValue = function (value) {
  52388. if (typeof value === "function") {
  52389. return value();
  52390. }
  52391. return value;
  52392. };
  52393. /**
  52394. * @hidden Internal use only
  52395. */
  52396. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  52397. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  52398. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  52399. }
  52400. var keys = this.getKeys();
  52401. // Try to get a hash to find the right key
  52402. 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));
  52403. if (keys[startKeyIndex].frame >= currentFrame) {
  52404. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  52405. startKeyIndex--;
  52406. }
  52407. }
  52408. for (var key = startKeyIndex; key < keys.length; key++) {
  52409. var endKey = keys[key + 1];
  52410. if (endKey.frame >= currentFrame) {
  52411. var startKey = keys[key];
  52412. var startValue = this._getKeyValue(startKey.value);
  52413. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  52414. return startValue;
  52415. }
  52416. var endValue = this._getKeyValue(endKey.value);
  52417. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  52418. var frameDelta = endKey.frame - startKey.frame;
  52419. // gradient : percent of currentFrame between the frame inf and the frame sup
  52420. var gradient = (currentFrame - startKey.frame) / frameDelta;
  52421. // check for easingFunction and correction of gradient
  52422. var easingFunction = this.getEasingFunction();
  52423. if (easingFunction != null) {
  52424. gradient = easingFunction.ease(gradient);
  52425. }
  52426. switch (this.dataType) {
  52427. // Float
  52428. case Animation.ANIMATIONTYPE_FLOAT:
  52429. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  52430. switch (loopMode) {
  52431. case Animation.ANIMATIONLOOPMODE_CYCLE:
  52432. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  52433. return floatValue;
  52434. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  52435. return offsetValue * repeatCount + floatValue;
  52436. }
  52437. break;
  52438. // Quaternion
  52439. case Animation.ANIMATIONTYPE_QUATERNION:
  52440. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  52441. switch (loopMode) {
  52442. case Animation.ANIMATIONLOOPMODE_CYCLE:
  52443. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  52444. return quatValue;
  52445. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  52446. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  52447. }
  52448. return quatValue;
  52449. // Vector3
  52450. case Animation.ANIMATIONTYPE_VECTOR3:
  52451. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  52452. switch (loopMode) {
  52453. case Animation.ANIMATIONLOOPMODE_CYCLE:
  52454. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  52455. return vec3Value;
  52456. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  52457. return vec3Value.add(offsetValue.scale(repeatCount));
  52458. }
  52459. // Vector2
  52460. case Animation.ANIMATIONTYPE_VECTOR2:
  52461. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  52462. switch (loopMode) {
  52463. case Animation.ANIMATIONLOOPMODE_CYCLE:
  52464. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  52465. return vec2Value;
  52466. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  52467. return vec2Value.add(offsetValue.scale(repeatCount));
  52468. }
  52469. // Size
  52470. case Animation.ANIMATIONTYPE_SIZE:
  52471. switch (loopMode) {
  52472. case Animation.ANIMATIONLOOPMODE_CYCLE:
  52473. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  52474. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  52475. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  52476. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  52477. }
  52478. // Color3
  52479. case Animation.ANIMATIONTYPE_COLOR3:
  52480. switch (loopMode) {
  52481. case Animation.ANIMATIONLOOPMODE_CYCLE:
  52482. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  52483. return this.color3InterpolateFunction(startValue, endValue, gradient);
  52484. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  52485. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  52486. }
  52487. // Matrix
  52488. case Animation.ANIMATIONTYPE_MATRIX:
  52489. switch (loopMode) {
  52490. case Animation.ANIMATIONLOOPMODE_CYCLE:
  52491. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  52492. if (Animation.AllowMatricesInterpolation) {
  52493. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  52494. }
  52495. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  52496. return startValue;
  52497. }
  52498. default:
  52499. break;
  52500. }
  52501. break;
  52502. }
  52503. }
  52504. return this._getKeyValue(keys[keys.length - 1].value);
  52505. };
  52506. /**
  52507. * Defines the function to use to interpolate matrices
  52508. * @param startValue defines the start matrix
  52509. * @param endValue defines the end matrix
  52510. * @param gradient defines the gradient between both matrices
  52511. * @param result defines an optional target matrix where to store the interpolation
  52512. * @returns the interpolated matrix
  52513. */
  52514. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  52515. if (Animation.AllowMatrixDecomposeForInterpolation) {
  52516. if (result) {
  52517. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  52518. return result;
  52519. }
  52520. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  52521. }
  52522. if (result) {
  52523. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  52524. return result;
  52525. }
  52526. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  52527. };
  52528. /**
  52529. * Makes a copy of the animation
  52530. * @returns Cloned animation
  52531. */
  52532. Animation.prototype.clone = function () {
  52533. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  52534. clone.enableBlending = this.enableBlending;
  52535. clone.blendingSpeed = this.blendingSpeed;
  52536. if (this._keys) {
  52537. clone.setKeys(this._keys);
  52538. }
  52539. if (this._ranges) {
  52540. clone._ranges = {};
  52541. for (var name in this._ranges) {
  52542. var range = this._ranges[name];
  52543. if (!range) {
  52544. continue;
  52545. }
  52546. clone._ranges[name] = range.clone();
  52547. }
  52548. }
  52549. return clone;
  52550. };
  52551. /**
  52552. * Sets the key frames of the animation
  52553. * @param values The animation key frames to set
  52554. */
  52555. Animation.prototype.setKeys = function (values) {
  52556. this._keys = values.slice(0);
  52557. };
  52558. /**
  52559. * Serializes the animation to an object
  52560. * @returns Serialized object
  52561. */
  52562. Animation.prototype.serialize = function () {
  52563. var serializationObject = {};
  52564. serializationObject.name = this.name;
  52565. serializationObject.property = this.targetProperty;
  52566. serializationObject.framePerSecond = this.framePerSecond;
  52567. serializationObject.dataType = this.dataType;
  52568. serializationObject.loopBehavior = this.loopMode;
  52569. serializationObject.enableBlending = this.enableBlending;
  52570. serializationObject.blendingSpeed = this.blendingSpeed;
  52571. var dataType = this.dataType;
  52572. serializationObject.keys = [];
  52573. var keys = this.getKeys();
  52574. for (var index = 0; index < keys.length; index++) {
  52575. var animationKey = keys[index];
  52576. var key = {};
  52577. key.frame = animationKey.frame;
  52578. switch (dataType) {
  52579. case Animation.ANIMATIONTYPE_FLOAT:
  52580. key.values = [animationKey.value];
  52581. break;
  52582. case Animation.ANIMATIONTYPE_QUATERNION:
  52583. case Animation.ANIMATIONTYPE_MATRIX:
  52584. case Animation.ANIMATIONTYPE_VECTOR3:
  52585. case Animation.ANIMATIONTYPE_COLOR3:
  52586. key.values = animationKey.value.asArray();
  52587. break;
  52588. }
  52589. serializationObject.keys.push(key);
  52590. }
  52591. serializationObject.ranges = [];
  52592. for (var name in this._ranges) {
  52593. var source = this._ranges[name];
  52594. if (!source) {
  52595. continue;
  52596. }
  52597. var range = {};
  52598. range.name = name;
  52599. range.from = source.from;
  52600. range.to = source.to;
  52601. serializationObject.ranges.push(range);
  52602. }
  52603. return serializationObject;
  52604. };
  52605. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  52606. /**
  52607. * Get the float animation type
  52608. */
  52609. get: function () {
  52610. return Animation._ANIMATIONTYPE_FLOAT;
  52611. },
  52612. enumerable: true,
  52613. configurable: true
  52614. });
  52615. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  52616. /**
  52617. * Get the Vector3 animation type
  52618. */
  52619. get: function () {
  52620. return Animation._ANIMATIONTYPE_VECTOR3;
  52621. },
  52622. enumerable: true,
  52623. configurable: true
  52624. });
  52625. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  52626. /**
  52627. * Get the Vector2 animation type
  52628. */
  52629. get: function () {
  52630. return Animation._ANIMATIONTYPE_VECTOR2;
  52631. },
  52632. enumerable: true,
  52633. configurable: true
  52634. });
  52635. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  52636. /**
  52637. * Get the Size animation type
  52638. */
  52639. get: function () {
  52640. return Animation._ANIMATIONTYPE_SIZE;
  52641. },
  52642. enumerable: true,
  52643. configurable: true
  52644. });
  52645. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  52646. /**
  52647. * Get the Quaternion animation type
  52648. */
  52649. get: function () {
  52650. return Animation._ANIMATIONTYPE_QUATERNION;
  52651. },
  52652. enumerable: true,
  52653. configurable: true
  52654. });
  52655. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  52656. /**
  52657. * Get the Matrix animation type
  52658. */
  52659. get: function () {
  52660. return Animation._ANIMATIONTYPE_MATRIX;
  52661. },
  52662. enumerable: true,
  52663. configurable: true
  52664. });
  52665. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  52666. /**
  52667. * Get the Color3 animation type
  52668. */
  52669. get: function () {
  52670. return Animation._ANIMATIONTYPE_COLOR3;
  52671. },
  52672. enumerable: true,
  52673. configurable: true
  52674. });
  52675. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  52676. /**
  52677. * Get the Relative Loop Mode
  52678. */
  52679. get: function () {
  52680. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  52681. },
  52682. enumerable: true,
  52683. configurable: true
  52684. });
  52685. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  52686. /**
  52687. * Get the Cycle Loop Mode
  52688. */
  52689. get: function () {
  52690. return Animation._ANIMATIONLOOPMODE_CYCLE;
  52691. },
  52692. enumerable: true,
  52693. configurable: true
  52694. });
  52695. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  52696. /**
  52697. * Get the Constant Loop Mode
  52698. */
  52699. get: function () {
  52700. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  52701. },
  52702. enumerable: true,
  52703. configurable: true
  52704. });
  52705. /** @hidden */
  52706. Animation._UniversalLerp = function (left, right, amount) {
  52707. var constructor = left.constructor;
  52708. if (constructor.Lerp) { // Lerp supported
  52709. return constructor.Lerp(left, right, amount);
  52710. }
  52711. else if (constructor.Slerp) { // Slerp supported
  52712. return constructor.Slerp(left, right, amount);
  52713. }
  52714. else if (left.toFixed) { // Number
  52715. return left * (1.0 - amount) + amount * right;
  52716. }
  52717. else { // Blending not supported
  52718. return right;
  52719. }
  52720. };
  52721. /**
  52722. * Parses an animation object and creates an animation
  52723. * @param parsedAnimation Parsed animation object
  52724. * @returns Animation object
  52725. */
  52726. Animation.Parse = function (parsedAnimation) {
  52727. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  52728. var dataType = parsedAnimation.dataType;
  52729. var keys = [];
  52730. var data;
  52731. var index;
  52732. if (parsedAnimation.enableBlending) {
  52733. animation.enableBlending = parsedAnimation.enableBlending;
  52734. }
  52735. if (parsedAnimation.blendingSpeed) {
  52736. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  52737. }
  52738. for (index = 0; index < parsedAnimation.keys.length; index++) {
  52739. var key = parsedAnimation.keys[index];
  52740. var inTangent;
  52741. var outTangent;
  52742. switch (dataType) {
  52743. case Animation.ANIMATIONTYPE_FLOAT:
  52744. data = key.values[0];
  52745. if (key.values.length >= 1) {
  52746. inTangent = key.values[1];
  52747. }
  52748. if (key.values.length >= 2) {
  52749. outTangent = key.values[2];
  52750. }
  52751. break;
  52752. case Animation.ANIMATIONTYPE_QUATERNION:
  52753. data = BABYLON.Quaternion.FromArray(key.values);
  52754. if (key.values.length >= 8) {
  52755. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  52756. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  52757. inTangent = _inTangent;
  52758. }
  52759. }
  52760. if (key.values.length >= 12) {
  52761. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  52762. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  52763. outTangent = _outTangent;
  52764. }
  52765. }
  52766. break;
  52767. case Animation.ANIMATIONTYPE_MATRIX:
  52768. data = BABYLON.Matrix.FromArray(key.values);
  52769. break;
  52770. case Animation.ANIMATIONTYPE_COLOR3:
  52771. data = BABYLON.Color3.FromArray(key.values);
  52772. break;
  52773. case Animation.ANIMATIONTYPE_VECTOR3:
  52774. default:
  52775. data = BABYLON.Vector3.FromArray(key.values);
  52776. break;
  52777. }
  52778. var keyData = {};
  52779. keyData.frame = key.frame;
  52780. keyData.value = data;
  52781. if (inTangent != undefined) {
  52782. keyData.inTangent = inTangent;
  52783. }
  52784. if (outTangent != undefined) {
  52785. keyData.outTangent = outTangent;
  52786. }
  52787. keys.push(keyData);
  52788. }
  52789. animation.setKeys(keys);
  52790. if (parsedAnimation.ranges) {
  52791. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  52792. data = parsedAnimation.ranges[index];
  52793. animation.createRange(data.name, data.from, data.to);
  52794. }
  52795. }
  52796. return animation;
  52797. };
  52798. /**
  52799. * Appends the serialized animations from the source animations
  52800. * @param source Source containing the animations
  52801. * @param destination Target to store the animations
  52802. */
  52803. Animation.AppendSerializedAnimations = function (source, destination) {
  52804. if (source.animations) {
  52805. destination.animations = [];
  52806. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  52807. var animation = source.animations[animationIndex];
  52808. destination.animations.push(animation.serialize());
  52809. }
  52810. }
  52811. };
  52812. /**
  52813. * Use matrix interpolation instead of using direct key value when animating matrices
  52814. */
  52815. Animation.AllowMatricesInterpolation = false;
  52816. /**
  52817. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  52818. */
  52819. Animation.AllowMatrixDecomposeForInterpolation = true;
  52820. // Statics
  52821. /**
  52822. * Float animation type
  52823. */
  52824. Animation._ANIMATIONTYPE_FLOAT = 0;
  52825. /**
  52826. * Vector3 animation type
  52827. */
  52828. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  52829. /**
  52830. * Quaternion animation type
  52831. */
  52832. Animation._ANIMATIONTYPE_QUATERNION = 2;
  52833. /**
  52834. * Matrix animation type
  52835. */
  52836. Animation._ANIMATIONTYPE_MATRIX = 3;
  52837. /**
  52838. * Color3 animation type
  52839. */
  52840. Animation._ANIMATIONTYPE_COLOR3 = 4;
  52841. /**
  52842. * Vector2 animation type
  52843. */
  52844. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  52845. /**
  52846. * Size animation type
  52847. */
  52848. Animation._ANIMATIONTYPE_SIZE = 6;
  52849. /**
  52850. * Relative Loop Mode
  52851. */
  52852. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  52853. /**
  52854. * Cycle Loop Mode
  52855. */
  52856. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  52857. /**
  52858. * Constant Loop Mode
  52859. */
  52860. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  52861. return Animation;
  52862. }());
  52863. BABYLON.Animation = Animation;
  52864. })(BABYLON || (BABYLON = {}));
  52865. //# sourceMappingURL=babylon.animation.js.map
  52866. var BABYLON;
  52867. (function (BABYLON) {
  52868. /**
  52869. * This class defines the direct association between an animation and a target
  52870. */
  52871. var TargetedAnimation = /** @class */ (function () {
  52872. function TargetedAnimation() {
  52873. }
  52874. return TargetedAnimation;
  52875. }());
  52876. BABYLON.TargetedAnimation = TargetedAnimation;
  52877. /**
  52878. * Use this class to create coordinated animations on multiple targets
  52879. */
  52880. var AnimationGroup = /** @class */ (function () {
  52881. /**
  52882. * Instantiates a new Animation Group.
  52883. * This helps managing several animations at once.
  52884. * @see http://doc.babylonjs.com/how_to/group
  52885. * @param name Defines the name of the group
  52886. * @param scene Defines the scene the group belongs to
  52887. */
  52888. function AnimationGroup(
  52889. /** The name of the animation group */
  52890. name, scene) {
  52891. if (scene === void 0) { scene = null; }
  52892. this.name = name;
  52893. this._targetedAnimations = new Array();
  52894. this._animatables = new Array();
  52895. this._from = Number.MAX_VALUE;
  52896. this._to = -Number.MAX_VALUE;
  52897. this._speedRatio = 1;
  52898. /**
  52899. * This observable will notify when one animation have ended.
  52900. */
  52901. this.onAnimationEndObservable = new BABYLON.Observable();
  52902. /**
  52903. * This observable will notify when all animations have ended.
  52904. */
  52905. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  52906. /**
  52907. * This observable will notify when all animations have paused.
  52908. */
  52909. this.onAnimationGroupPauseObservable = new BABYLON.Observable();
  52910. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52911. this._scene.animationGroups.push(this);
  52912. }
  52913. Object.defineProperty(AnimationGroup.prototype, "from", {
  52914. /**
  52915. * Gets the first frame
  52916. */
  52917. get: function () {
  52918. return this._from;
  52919. },
  52920. enumerable: true,
  52921. configurable: true
  52922. });
  52923. Object.defineProperty(AnimationGroup.prototype, "to", {
  52924. /**
  52925. * Gets the last frame
  52926. */
  52927. get: function () {
  52928. return this._to;
  52929. },
  52930. enumerable: true,
  52931. configurable: true
  52932. });
  52933. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  52934. /**
  52935. * Define if the animations are started
  52936. */
  52937. get: function () {
  52938. return this._isStarted;
  52939. },
  52940. enumerable: true,
  52941. configurable: true
  52942. });
  52943. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  52944. /**
  52945. * Gets or sets the speed ratio to use for all animations
  52946. */
  52947. get: function () {
  52948. return this._speedRatio;
  52949. },
  52950. /**
  52951. * Gets or sets the speed ratio to use for all animations
  52952. */
  52953. set: function (value) {
  52954. if (this._speedRatio === value) {
  52955. return;
  52956. }
  52957. this._speedRatio = value;
  52958. for (var index = 0; index < this._animatables.length; index++) {
  52959. var animatable = this._animatables[index];
  52960. animatable.speedRatio = this._speedRatio;
  52961. }
  52962. },
  52963. enumerable: true,
  52964. configurable: true
  52965. });
  52966. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  52967. /**
  52968. * Gets the targeted animations for this animation group
  52969. */
  52970. get: function () {
  52971. return this._targetedAnimations;
  52972. },
  52973. enumerable: true,
  52974. configurable: true
  52975. });
  52976. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  52977. /**
  52978. * returning the list of animatables controlled by this animation group.
  52979. */
  52980. get: function () {
  52981. return this._animatables;
  52982. },
  52983. enumerable: true,
  52984. configurable: true
  52985. });
  52986. /**
  52987. * Add an animation (with its target) in the group
  52988. * @param animation defines the animation we want to add
  52989. * @param target defines the target of the animation
  52990. * @returns the {BABYLON.TargetedAnimation} object
  52991. */
  52992. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  52993. var targetedAnimation = {
  52994. animation: animation,
  52995. target: target
  52996. };
  52997. var keys = animation.getKeys();
  52998. if (this._from > keys[0].frame) {
  52999. this._from = keys[0].frame;
  53000. }
  53001. if (this._to < keys[keys.length - 1].frame) {
  53002. this._to = keys[keys.length - 1].frame;
  53003. }
  53004. this._targetedAnimations.push(targetedAnimation);
  53005. return targetedAnimation;
  53006. };
  53007. /**
  53008. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  53009. * It can add constant keys at begin or end
  53010. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  53011. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  53012. * @returns the animation group
  53013. */
  53014. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  53015. if (beginFrame === void 0) { beginFrame = null; }
  53016. if (endFrame === void 0) { endFrame = null; }
  53017. if (beginFrame == null)
  53018. beginFrame = this._from;
  53019. if (endFrame == null)
  53020. endFrame = this._to;
  53021. for (var index = 0; index < this._targetedAnimations.length; index++) {
  53022. var targetedAnimation = this._targetedAnimations[index];
  53023. var keys = targetedAnimation.animation.getKeys();
  53024. var startKey = keys[0];
  53025. var endKey = keys[keys.length - 1];
  53026. if (startKey.frame > beginFrame) {
  53027. var newKey = {
  53028. frame: beginFrame,
  53029. value: startKey.value,
  53030. inTangent: startKey.inTangent,
  53031. outTangent: startKey.outTangent,
  53032. interpolation: startKey.interpolation
  53033. };
  53034. keys.splice(0, 0, newKey);
  53035. }
  53036. if (endKey.frame < endFrame) {
  53037. var newKey = {
  53038. frame: endFrame,
  53039. value: endKey.value,
  53040. inTangent: endKey.outTangent,
  53041. outTangent: endKey.outTangent,
  53042. interpolation: endKey.interpolation
  53043. };
  53044. keys.push(newKey);
  53045. }
  53046. }
  53047. this._from = beginFrame;
  53048. this._to = endFrame;
  53049. return this;
  53050. };
  53051. /**
  53052. * Start all animations on given targets
  53053. * @param loop defines if animations must loop
  53054. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  53055. * @param from defines the from key (optional)
  53056. * @param to defines the to key (optional)
  53057. * @returns the current animation group
  53058. */
  53059. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  53060. var _this = this;
  53061. if (loop === void 0) { loop = false; }
  53062. if (speedRatio === void 0) { speedRatio = 1; }
  53063. if (this._isStarted || this._targetedAnimations.length === 0) {
  53064. return this;
  53065. }
  53066. var _loop_1 = function (targetedAnimation) {
  53067. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  53068. animatable.onAnimationEnd = function () {
  53069. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  53070. _this._checkAnimationGroupEnded(animatable);
  53071. };
  53072. this_1._animatables.push(animatable);
  53073. };
  53074. var this_1 = this;
  53075. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  53076. var targetedAnimation = _a[_i];
  53077. _loop_1(targetedAnimation);
  53078. }
  53079. this._speedRatio = speedRatio;
  53080. this._isStarted = true;
  53081. return this;
  53082. };
  53083. /**
  53084. * Pause all animations
  53085. * @returns the animation group
  53086. */
  53087. AnimationGroup.prototype.pause = function () {
  53088. if (!this._isStarted) {
  53089. return this;
  53090. }
  53091. for (var index = 0; index < this._animatables.length; index++) {
  53092. var animatable = this._animatables[index];
  53093. animatable.pause();
  53094. }
  53095. this.onAnimationGroupPauseObservable.notifyObservers(this);
  53096. return this;
  53097. };
  53098. /**
  53099. * Play all animations to initial state
  53100. * This function will start() the animations if they were not started or will restart() them if they were paused
  53101. * @param loop defines if animations must loop
  53102. * @returns the animation group
  53103. */
  53104. AnimationGroup.prototype.play = function (loop) {
  53105. // only if all animatables are ready and exist
  53106. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  53107. if (loop !== undefined) {
  53108. for (var index = 0; index < this._animatables.length; index++) {
  53109. var animatable = this._animatables[index];
  53110. animatable.loopAnimation = loop;
  53111. }
  53112. }
  53113. this.restart();
  53114. }
  53115. else {
  53116. this.stop();
  53117. this.start(loop, this._speedRatio);
  53118. }
  53119. return this;
  53120. };
  53121. /**
  53122. * Reset all animations to initial state
  53123. * @returns the animation group
  53124. */
  53125. AnimationGroup.prototype.reset = function () {
  53126. if (!this._isStarted) {
  53127. return this;
  53128. }
  53129. for (var index = 0; index < this._animatables.length; index++) {
  53130. var animatable = this._animatables[index];
  53131. animatable.reset();
  53132. }
  53133. return this;
  53134. };
  53135. /**
  53136. * Restart animations from key 0
  53137. * @returns the animation group
  53138. */
  53139. AnimationGroup.prototype.restart = function () {
  53140. if (!this._isStarted) {
  53141. return this;
  53142. }
  53143. for (var index = 0; index < this._animatables.length; index++) {
  53144. var animatable = this._animatables[index];
  53145. animatable.restart();
  53146. }
  53147. return this;
  53148. };
  53149. /**
  53150. * Stop all animations
  53151. * @returns the animation group
  53152. */
  53153. AnimationGroup.prototype.stop = function () {
  53154. if (!this._isStarted) {
  53155. return this;
  53156. }
  53157. var list = this._animatables.slice();
  53158. for (var index = 0; index < list.length; index++) {
  53159. list[index].stop();
  53160. }
  53161. this._isStarted = false;
  53162. return this;
  53163. };
  53164. /**
  53165. * Set animation weight for all animatables
  53166. * @param weight defines the weight to use
  53167. * @return the animationGroup
  53168. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  53169. */
  53170. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  53171. for (var index = 0; index < this._animatables.length; index++) {
  53172. var animatable = this._animatables[index];
  53173. animatable.weight = weight;
  53174. }
  53175. return this;
  53176. };
  53177. /**
  53178. * Synchronize and normalize all animatables with a source animatable
  53179. * @param root defines the root animatable to synchronize with
  53180. * @return the animationGroup
  53181. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  53182. */
  53183. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  53184. for (var index = 0; index < this._animatables.length; index++) {
  53185. var animatable = this._animatables[index];
  53186. animatable.syncWith(root);
  53187. }
  53188. return this;
  53189. };
  53190. /**
  53191. * Goes to a specific frame in this animation group
  53192. * @param frame the frame number to go to
  53193. * @return the animationGroup
  53194. */
  53195. AnimationGroup.prototype.goToFrame = function (frame) {
  53196. if (!this._isStarted) {
  53197. return this;
  53198. }
  53199. for (var index = 0; index < this._animatables.length; index++) {
  53200. var animatable = this._animatables[index];
  53201. animatable.goToFrame(frame);
  53202. }
  53203. return this;
  53204. };
  53205. /**
  53206. * Dispose all associated resources
  53207. */
  53208. AnimationGroup.prototype.dispose = function () {
  53209. this._targetedAnimations = [];
  53210. this._animatables = [];
  53211. var index = this._scene.animationGroups.indexOf(this);
  53212. if (index > -1) {
  53213. this._scene.animationGroups.splice(index, 1);
  53214. }
  53215. };
  53216. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  53217. // animatable should be taken out of the array
  53218. var idx = this._animatables.indexOf(animatable);
  53219. if (idx > -1) {
  53220. this._animatables.splice(idx, 1);
  53221. }
  53222. // all animatables were removed? animation group ended!
  53223. if (this._animatables.length === 0) {
  53224. this._isStarted = false;
  53225. this.onAnimationGroupEndObservable.notifyObservers(this);
  53226. }
  53227. };
  53228. // Statics
  53229. /**
  53230. * Returns a new AnimationGroup object parsed from the source provided.
  53231. * @param parsedAnimationGroup defines the source
  53232. * @param scene defines the scene that will receive the animationGroup
  53233. * @returns a new AnimationGroup
  53234. */
  53235. AnimationGroup.Parse = function (parsedAnimationGroup, scene) {
  53236. var animationGroup = new BABYLON.AnimationGroup(parsedAnimationGroup.name, scene);
  53237. for (var i = 0; i < parsedAnimationGroup.targetedAnimations.length; i++) {
  53238. var targetedAnimation = parsedAnimationGroup.targetedAnimations[i];
  53239. var animation = BABYLON.Animation.Parse(targetedAnimation.animation);
  53240. var id = targetedAnimation.targetId;
  53241. var targetNode = scene.getNodeByID(id);
  53242. if (targetNode != null)
  53243. animationGroup.addTargetedAnimation(animation, targetNode);
  53244. }
  53245. if (parsedAnimationGroup.from !== null && parsedAnimationGroup.from !== null)
  53246. animationGroup.normalize(parsedAnimationGroup.from, parsedAnimationGroup.to);
  53247. return animationGroup;
  53248. };
  53249. /**
  53250. * Returns the string "AnimationGroup"
  53251. * @returns "AnimationGroup"
  53252. */
  53253. AnimationGroup.prototype.getClassName = function () {
  53254. return "AnimationGroup";
  53255. };
  53256. /**
  53257. * Creates a detailled string about the object
  53258. * @param fullDetails defines if the output string will support multiple levels of logging within scene loading
  53259. * @returns a string representing the object
  53260. */
  53261. AnimationGroup.prototype.toString = function (fullDetails) {
  53262. var ret = "Name: " + this.name;
  53263. ret += ", type: " + this.getClassName();
  53264. if (fullDetails) {
  53265. ret += ", from: " + this._from;
  53266. ret += ", to: " + this._to;
  53267. ret += ", isStarted: " + this._isStarted;
  53268. ret += ", speedRatio: " + this._speedRatio;
  53269. ret += ", targetedAnimations length: " + this._targetedAnimations.length;
  53270. ret += ", animatables length: " + this._animatables;
  53271. }
  53272. return ret;
  53273. };
  53274. return AnimationGroup;
  53275. }());
  53276. BABYLON.AnimationGroup = AnimationGroup;
  53277. })(BABYLON || (BABYLON = {}));
  53278. //# sourceMappingURL=babylon.animationGroup.js.map
  53279. var BABYLON;
  53280. (function (BABYLON) {
  53281. // Static values to help the garbage collector
  53282. // Quaternion
  53283. var _staticOffsetValueQuaternion = Object.freeze(new BABYLON.Quaternion(0, 0, 0, 0));
  53284. // Vector3
  53285. var _staticOffsetValueVector3 = Object.freeze(BABYLON.Vector3.Zero());
  53286. // Vector2
  53287. var _staticOffsetValueVector2 = Object.freeze(BABYLON.Vector2.Zero());
  53288. // Size
  53289. var _staticOffsetValueSize = Object.freeze(BABYLON.Size.Zero());
  53290. // Color3
  53291. var _staticOffsetValueColor3 = Object.freeze(BABYLON.Color3.Black());
  53292. /**
  53293. * Defines a runtime animation
  53294. */
  53295. var RuntimeAnimation = /** @class */ (function () {
  53296. /**
  53297. * Create a new RuntimeAnimation object
  53298. * @param target defines the target of the animation
  53299. * @param animation defines the source animation object
  53300. * @param scene defines the hosting scene
  53301. * @param host defines the initiating Animatable
  53302. */
  53303. function RuntimeAnimation(target, animation, scene, host) {
  53304. var _this = this;
  53305. this._events = new Array();
  53306. /**
  53307. * The current frame of the runtime animation
  53308. */
  53309. this._currentFrame = 0;
  53310. /**
  53311. * The original value of the runtime animation
  53312. */
  53313. this._originalValue = new Array();
  53314. /**
  53315. * The offsets cache of the runtime animation
  53316. */
  53317. this._offsetsCache = {};
  53318. /**
  53319. * The high limits cache of the runtime animation
  53320. */
  53321. this._highLimitsCache = {};
  53322. /**
  53323. * Specifies if the runtime animation has been stopped
  53324. */
  53325. this._stopped = false;
  53326. /**
  53327. * The blending factor of the runtime animation
  53328. */
  53329. this._blendingFactor = 0;
  53330. /**
  53331. * The target path of the runtime animation
  53332. */
  53333. this._targetPath = "";
  53334. /**
  53335. * The weight of the runtime animation
  53336. */
  53337. this._weight = 1.0;
  53338. /**
  53339. * The ratio offset of the runtime animation
  53340. */
  53341. this._ratioOffset = 0;
  53342. /**
  53343. * The previous delay of the runtime animation
  53344. */
  53345. this._previousDelay = 0;
  53346. /**
  53347. * The previous ratio of the runtime animation
  53348. */
  53349. this._previousRatio = 0;
  53350. this._animation = animation;
  53351. this._target = target;
  53352. this._scene = scene;
  53353. this._host = host;
  53354. animation._runtimeAnimations.push(this);
  53355. // Cloning events locally
  53356. var events = animation.getEvents();
  53357. if (events && events.length > 0) {
  53358. events.forEach(function (e) {
  53359. _this._events.push(e._clone());
  53360. });
  53361. }
  53362. }
  53363. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  53364. /**
  53365. * Gets the current frame of the runtime animation
  53366. */
  53367. get: function () {
  53368. return this._currentFrame;
  53369. },
  53370. enumerable: true,
  53371. configurable: true
  53372. });
  53373. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  53374. /**
  53375. * Gets the weight of the runtime animation
  53376. */
  53377. get: function () {
  53378. return this._weight;
  53379. },
  53380. enumerable: true,
  53381. configurable: true
  53382. });
  53383. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  53384. /**
  53385. * Gets the current value of the runtime animation
  53386. */
  53387. get: function () {
  53388. return this._currentValue;
  53389. },
  53390. enumerable: true,
  53391. configurable: true
  53392. });
  53393. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  53394. /**
  53395. * Gets the target path of the runtime animation
  53396. */
  53397. get: function () {
  53398. return this._targetPath;
  53399. },
  53400. enumerable: true,
  53401. configurable: true
  53402. });
  53403. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  53404. /**
  53405. * Gets the actual target of the runtime animation
  53406. */
  53407. get: function () {
  53408. return this._activeTarget;
  53409. },
  53410. enumerable: true,
  53411. configurable: true
  53412. });
  53413. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  53414. /**
  53415. * Gets the animation from the runtime animation
  53416. */
  53417. get: function () {
  53418. return this._animation;
  53419. },
  53420. enumerable: true,
  53421. configurable: true
  53422. });
  53423. /**
  53424. * Resets the runtime animation to the beginning
  53425. * @param restoreOriginal defines whether to restore the target property to the original value
  53426. */
  53427. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  53428. if (restoreOriginal === void 0) { restoreOriginal = false; }
  53429. if (restoreOriginal) {
  53430. if (this._target instanceof Array) {
  53431. var index = 0;
  53432. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  53433. var target = _a[_i];
  53434. if (this._originalValue[index] !== undefined) {
  53435. this._setValue(target, this._originalValue[index], -1);
  53436. }
  53437. index++;
  53438. }
  53439. }
  53440. else {
  53441. if (this._originalValue[0] !== undefined) {
  53442. this._setValue(this._target, this._originalValue[0], -1);
  53443. }
  53444. }
  53445. }
  53446. this._offsetsCache = {};
  53447. this._highLimitsCache = {};
  53448. this._currentFrame = 0;
  53449. this._blendingFactor = 0;
  53450. this._originalValue = new Array();
  53451. // Events
  53452. for (var index = 0; index < this._events.length; index++) {
  53453. this._events[index].isDone = false;
  53454. }
  53455. };
  53456. /**
  53457. * Specifies if the runtime animation is stopped
  53458. * @returns Boolean specifying if the runtime animation is stopped
  53459. */
  53460. RuntimeAnimation.prototype.isStopped = function () {
  53461. return this._stopped;
  53462. };
  53463. /**
  53464. * Disposes of the runtime animation
  53465. */
  53466. RuntimeAnimation.prototype.dispose = function () {
  53467. var index = this._animation.runtimeAnimations.indexOf(this);
  53468. if (index > -1) {
  53469. this._animation.runtimeAnimations.splice(index, 1);
  53470. }
  53471. };
  53472. /**
  53473. * Interpolates the animation from the current frame
  53474. * @param currentFrame The frame to interpolate the animation to
  53475. * @param repeatCount The number of times that the animation should loop
  53476. * @param loopMode The type of looping mode to use
  53477. * @param offsetValue Animation offset value
  53478. * @param highLimitValue The high limit value
  53479. * @returns The interpolated value
  53480. */
  53481. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  53482. this._currentFrame = currentFrame;
  53483. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  53484. this._workValue = BABYLON.Matrix.Zero();
  53485. }
  53486. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  53487. };
  53488. /**
  53489. * Apply the interpolated value to the target
  53490. * @param currentValue defines the value computed by the animation
  53491. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  53492. */
  53493. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  53494. if (weight === void 0) { weight = 1.0; }
  53495. if (this._target instanceof Array) {
  53496. var index = 0;
  53497. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  53498. var target = _a[_i];
  53499. this._setValue(target, currentValue, weight, index);
  53500. index++;
  53501. }
  53502. }
  53503. else {
  53504. this._setValue(this._target, currentValue, weight);
  53505. }
  53506. };
  53507. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  53508. if (targetIndex === void 0) { targetIndex = 0; }
  53509. // Set value
  53510. var path;
  53511. var destination;
  53512. var targetPropertyPath = this._animation.targetPropertyPath;
  53513. if (targetPropertyPath.length > 1) {
  53514. var property = target[targetPropertyPath[0]];
  53515. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  53516. property = property[targetPropertyPath[index]];
  53517. }
  53518. path = targetPropertyPath[targetPropertyPath.length - 1];
  53519. destination = property;
  53520. }
  53521. else {
  53522. path = targetPropertyPath[0];
  53523. destination = target;
  53524. }
  53525. this._targetPath = path;
  53526. this._activeTarget = destination;
  53527. this._weight = weight;
  53528. if (this._originalValue[targetIndex] === undefined) {
  53529. var originalValue = void 0;
  53530. if (destination.getRestPose && path === "_matrix") { // For bones
  53531. originalValue = destination.getRestPose();
  53532. }
  53533. else {
  53534. originalValue = destination[path];
  53535. }
  53536. if (originalValue && originalValue.clone) {
  53537. this._originalValue[targetIndex] = originalValue.clone();
  53538. }
  53539. else {
  53540. this._originalValue[targetIndex] = originalValue;
  53541. }
  53542. }
  53543. // Blending
  53544. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  53545. if (enableBlending && this._blendingFactor <= 1.0) {
  53546. if (!this._originalBlendValue) {
  53547. var originalValue = destination[path];
  53548. if (originalValue.clone) {
  53549. this._originalBlendValue = originalValue.clone();
  53550. }
  53551. else {
  53552. this._originalBlendValue = originalValue;
  53553. }
  53554. }
  53555. if (this._originalBlendValue.m) { // Matrix
  53556. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  53557. if (this._currentValue) {
  53558. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  53559. }
  53560. else {
  53561. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  53562. }
  53563. }
  53564. else {
  53565. if (this._currentValue) {
  53566. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  53567. }
  53568. else {
  53569. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  53570. }
  53571. }
  53572. }
  53573. else {
  53574. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  53575. }
  53576. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  53577. this._blendingFactor += blendingSpeed;
  53578. }
  53579. else {
  53580. this._currentValue = currentValue;
  53581. }
  53582. if (weight !== -1.0) {
  53583. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  53584. }
  53585. else {
  53586. destination[path] = this._currentValue;
  53587. }
  53588. if (target.markAsDirty) {
  53589. target.markAsDirty(this._animation.targetProperty);
  53590. }
  53591. };
  53592. /**
  53593. * Gets the loop pmode of the runtime animation
  53594. * @returns Loop Mode
  53595. */
  53596. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  53597. if (this._target && this._target.animationPropertiesOverride) {
  53598. return this._target.animationPropertiesOverride.loopMode;
  53599. }
  53600. return this._animation.loopMode;
  53601. };
  53602. /**
  53603. * Move the current animation to a given frame
  53604. * @param frame defines the frame to move to
  53605. */
  53606. RuntimeAnimation.prototype.goToFrame = function (frame) {
  53607. var keys = this._animation.getKeys();
  53608. if (frame < keys[0].frame) {
  53609. frame = keys[0].frame;
  53610. }
  53611. else if (frame > keys[keys.length - 1].frame) {
  53612. frame = keys[keys.length - 1].frame;
  53613. }
  53614. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  53615. this.setValue(currentValue, -1);
  53616. };
  53617. /**
  53618. * @hidden Internal use only
  53619. */
  53620. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  53621. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  53622. this._ratioOffset = this._previousRatio - newRatio;
  53623. };
  53624. /**
  53625. * Execute the current animation
  53626. * @param delay defines the delay to add to the current frame
  53627. * @param from defines the lower bound of the animation range
  53628. * @param to defines the upper bound of the animation range
  53629. * @param loop defines if the current animation must loop
  53630. * @param speedRatio defines the current speed ratio
  53631. * @param weight defines the weight of the animation (default is -1 so no weight)
  53632. * @returns a boolean indicating if the animation is running
  53633. */
  53634. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  53635. if (weight === void 0) { weight = -1.0; }
  53636. var targetPropertyPath = this._animation.targetPropertyPath;
  53637. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  53638. this._stopped = true;
  53639. return false;
  53640. }
  53641. var returnValue = true;
  53642. var keys = this._animation.getKeys();
  53643. // Adding a start key at frame 0 if missing
  53644. if (keys[0].frame !== 0) {
  53645. var newKey = { frame: 0, value: keys[0].value };
  53646. keys.splice(0, 0, newKey);
  53647. }
  53648. // Adding a duplicate key when there is only one key at frame zero
  53649. else if (keys.length === 1) {
  53650. var newKey = { frame: 0.001, value: keys[0].value };
  53651. keys.push(newKey);
  53652. }
  53653. // Check limits
  53654. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  53655. from = keys[0].frame;
  53656. }
  53657. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  53658. to = keys[keys.length - 1].frame;
  53659. }
  53660. //to and from cannot be the same key
  53661. if (from === to) {
  53662. if (from > keys[0].frame) {
  53663. from--;
  53664. }
  53665. else if (to < keys[keys.length - 1].frame) {
  53666. to++;
  53667. }
  53668. }
  53669. // Compute ratio
  53670. var range = to - from;
  53671. var offsetValue;
  53672. // ratio represents the frame delta between from and to
  53673. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  53674. var highLimitValue = 0;
  53675. this._previousDelay = delay;
  53676. this._previousRatio = ratio;
  53677. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  53678. returnValue = false;
  53679. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  53680. }
  53681. else {
  53682. // Get max value if required
  53683. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  53684. var keyOffset = to.toString() + from.toString();
  53685. if (!this._offsetsCache[keyOffset]) {
  53686. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  53687. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  53688. switch (this._animation.dataType) {
  53689. // Float
  53690. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  53691. this._offsetsCache[keyOffset] = toValue - fromValue;
  53692. break;
  53693. // Quaternion
  53694. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  53695. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  53696. break;
  53697. // Vector3
  53698. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  53699. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  53700. // Vector2
  53701. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  53702. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  53703. // Size
  53704. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  53705. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  53706. // Color3
  53707. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  53708. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  53709. default:
  53710. break;
  53711. }
  53712. this._highLimitsCache[keyOffset] = toValue;
  53713. }
  53714. highLimitValue = this._highLimitsCache[keyOffset];
  53715. offsetValue = this._offsetsCache[keyOffset];
  53716. }
  53717. }
  53718. if (offsetValue === undefined) {
  53719. switch (this._animation.dataType) {
  53720. // Float
  53721. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  53722. offsetValue = 0;
  53723. break;
  53724. // Quaternion
  53725. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  53726. offsetValue = _staticOffsetValueQuaternion;
  53727. break;
  53728. // Vector3
  53729. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  53730. offsetValue = _staticOffsetValueVector3;
  53731. break;
  53732. // Vector2
  53733. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  53734. offsetValue = _staticOffsetValueVector2;
  53735. break;
  53736. // Size
  53737. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  53738. offsetValue = _staticOffsetValueSize;
  53739. break;
  53740. // Color3
  53741. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  53742. offsetValue = _staticOffsetValueColor3;
  53743. }
  53744. }
  53745. // Compute value
  53746. var repeatCount = (ratio / range) >> 0;
  53747. var currentFrame = returnValue ? from + ratio % range : to;
  53748. // Need to normalize?
  53749. if (this._host && this._host.syncRoot) {
  53750. var syncRoot = this._host.syncRoot;
  53751. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  53752. currentFrame = from + (to - from) * hostNormalizedFrame;
  53753. }
  53754. // Reset events if looping
  53755. var events = this._events;
  53756. if (range > 0 && this.currentFrame > currentFrame ||
  53757. range < 0 && this.currentFrame < currentFrame) {
  53758. // Need to reset animation events
  53759. for (var index = 0; index < events.length; index++) {
  53760. if (!events[index].onlyOnce) {
  53761. // reset event, the animation is looping
  53762. events[index].isDone = false;
  53763. }
  53764. }
  53765. }
  53766. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  53767. // Set value
  53768. this.setValue(currentValue, weight);
  53769. // Check events
  53770. for (var index = 0; index < events.length; index++) {
  53771. // Make sure current frame has passed event frame and that event frame is within the current range
  53772. // Also, handle both forward and reverse animations
  53773. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  53774. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  53775. var event = events[index];
  53776. if (!event.isDone) {
  53777. // If event should be done only once, remove it.
  53778. if (event.onlyOnce) {
  53779. events.splice(index, 1);
  53780. index--;
  53781. }
  53782. event.isDone = true;
  53783. event.action(currentFrame);
  53784. } // Don't do anything if the event has already be done.
  53785. }
  53786. }
  53787. if (!returnValue) {
  53788. this._stopped = true;
  53789. }
  53790. return returnValue;
  53791. };
  53792. return RuntimeAnimation;
  53793. }());
  53794. BABYLON.RuntimeAnimation = RuntimeAnimation;
  53795. })(BABYLON || (BABYLON = {}));
  53796. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  53797. var BABYLON;
  53798. (function (BABYLON) {
  53799. /**
  53800. * Class used to store an actual running animation
  53801. */
  53802. var Animatable = /** @class */ (function () {
  53803. /**
  53804. * Creates a new Animatable
  53805. * @param scene defines the hosting scene
  53806. * @param target defines the target object
  53807. * @param fromFrame defines the starting frame number (default is 0)
  53808. * @param toFrame defines the ending frame number (default is 100)
  53809. * @param loopAnimation defines if the animation must loop (default is false)
  53810. * @param speedRatio defines the factor to apply to animation speed (default is 1)
  53811. * @param onAnimationEnd defines a callback to call when animation ends if it is not looping
  53812. * @param animations defines a group of animation to add to the new Animatable
  53813. */
  53814. function Animatable(scene,
  53815. /** defines the target object */
  53816. target,
  53817. /** defines the starting frame number (default is 0) */
  53818. fromFrame,
  53819. /** defines the ending frame number (default is 100) */
  53820. toFrame,
  53821. /** defines if the animation must loop (default is false) */
  53822. loopAnimation, speedRatio,
  53823. /** defines a callback to call when animation ends if it is not looping */
  53824. onAnimationEnd, animations) {
  53825. if (fromFrame === void 0) { fromFrame = 0; }
  53826. if (toFrame === void 0) { toFrame = 100; }
  53827. if (loopAnimation === void 0) { loopAnimation = false; }
  53828. if (speedRatio === void 0) { speedRatio = 1.0; }
  53829. this.target = target;
  53830. this.fromFrame = fromFrame;
  53831. this.toFrame = toFrame;
  53832. this.loopAnimation = loopAnimation;
  53833. this.onAnimationEnd = onAnimationEnd;
  53834. this._localDelayOffset = null;
  53835. this._pausedDelay = null;
  53836. this._runtimeAnimations = new Array();
  53837. this._paused = false;
  53838. this._speedRatio = 1;
  53839. this._weight = -1.0;
  53840. /**
  53841. * Gets or sets a boolean indicating if the animatable must be disposed and removed at the end of the animation.
  53842. * This will only apply for non looping animation (default is true)
  53843. */
  53844. this.disposeOnEnd = true;
  53845. /**
  53846. * Gets a boolean indicating if the animation has started
  53847. */
  53848. this.animationStarted = false;
  53849. /**
  53850. * Observer raised when the animation ends
  53851. */
  53852. this.onAnimationEndObservable = new BABYLON.Observable();
  53853. this._scene = scene;
  53854. if (animations) {
  53855. this.appendAnimations(target, animations);
  53856. }
  53857. this._speedRatio = speedRatio;
  53858. scene._activeAnimatables.push(this);
  53859. }
  53860. Object.defineProperty(Animatable.prototype, "syncRoot", {
  53861. /**
  53862. * Gets the root Animatable used to synchronize and normalize animations
  53863. */
  53864. get: function () {
  53865. return this._syncRoot;
  53866. },
  53867. enumerable: true,
  53868. configurable: true
  53869. });
  53870. Object.defineProperty(Animatable.prototype, "masterFrame", {
  53871. /**
  53872. * Gets the current frame of the first RuntimeAnimation
  53873. * Used to synchronize Animatables
  53874. */
  53875. get: function () {
  53876. if (this._runtimeAnimations.length === 0) {
  53877. return 0;
  53878. }
  53879. return this._runtimeAnimations[0].currentFrame;
  53880. },
  53881. enumerable: true,
  53882. configurable: true
  53883. });
  53884. Object.defineProperty(Animatable.prototype, "weight", {
  53885. /**
  53886. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  53887. */
  53888. get: function () {
  53889. return this._weight;
  53890. },
  53891. set: function (value) {
  53892. if (value === -1) { // -1 is ok and means no weight
  53893. this._weight = -1;
  53894. return;
  53895. }
  53896. // Else weight must be in [0, 1] range
  53897. this._weight = Math.min(Math.max(value, 0), 1.0);
  53898. },
  53899. enumerable: true,
  53900. configurable: true
  53901. });
  53902. Object.defineProperty(Animatable.prototype, "speedRatio", {
  53903. /**
  53904. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  53905. */
  53906. get: function () {
  53907. return this._speedRatio;
  53908. },
  53909. set: function (value) {
  53910. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  53911. var animation = this._runtimeAnimations[index];
  53912. animation._prepareForSpeedRatioChange(value);
  53913. }
  53914. this._speedRatio = value;
  53915. },
  53916. enumerable: true,
  53917. configurable: true
  53918. });
  53919. // Methods
  53920. /**
  53921. * Synchronize and normalize current Animatable with a source Animatable
  53922. * This is useful when using animation weights and when animations are not of the same length
  53923. * @param root defines the root Animatable to synchronize with
  53924. * @returns the current Animatable
  53925. */
  53926. Animatable.prototype.syncWith = function (root) {
  53927. this._syncRoot = root;
  53928. if (root) {
  53929. // Make sure this animatable will animate after the root
  53930. var index = this._scene._activeAnimatables.indexOf(this);
  53931. if (index > -1) {
  53932. this._scene._activeAnimatables.splice(index, 1);
  53933. this._scene._activeAnimatables.push(this);
  53934. }
  53935. }
  53936. return this;
  53937. };
  53938. /**
  53939. * Gets the list of runtime animations
  53940. * @returns an array of RuntimeAnimation
  53941. */
  53942. Animatable.prototype.getAnimations = function () {
  53943. return this._runtimeAnimations;
  53944. };
  53945. /**
  53946. * Adds more animations to the current animatable
  53947. * @param target defines the target of the animations
  53948. * @param animations defines the new animations to add
  53949. */
  53950. Animatable.prototype.appendAnimations = function (target, animations) {
  53951. for (var index = 0; index < animations.length; index++) {
  53952. var animation = animations[index];
  53953. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  53954. }
  53955. };
  53956. /**
  53957. * Gets the source animation for a specific property
  53958. * @param property defines the propertyu to look for
  53959. * @returns null or the source animation for the given property
  53960. */
  53961. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  53962. var runtimeAnimations = this._runtimeAnimations;
  53963. for (var index = 0; index < runtimeAnimations.length; index++) {
  53964. if (runtimeAnimations[index].animation.targetProperty === property) {
  53965. return runtimeAnimations[index].animation;
  53966. }
  53967. }
  53968. return null;
  53969. };
  53970. /**
  53971. * Gets the runtime animation for a specific property
  53972. * @param property defines the propertyu to look for
  53973. * @returns null or the runtime animation for the given property
  53974. */
  53975. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  53976. var runtimeAnimations = this._runtimeAnimations;
  53977. for (var index = 0; index < runtimeAnimations.length; index++) {
  53978. if (runtimeAnimations[index].animation.targetProperty === property) {
  53979. return runtimeAnimations[index];
  53980. }
  53981. }
  53982. return null;
  53983. };
  53984. /**
  53985. * Resets the animatable to its original state
  53986. */
  53987. Animatable.prototype.reset = function () {
  53988. var runtimeAnimations = this._runtimeAnimations;
  53989. for (var index = 0; index < runtimeAnimations.length; index++) {
  53990. runtimeAnimations[index].reset(true);
  53991. }
  53992. this._localDelayOffset = null;
  53993. this._pausedDelay = null;
  53994. };
  53995. /**
  53996. * Allows the animatable to blend with current running animations
  53997. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  53998. * @param blendingSpeed defines the blending speed to use
  53999. */
  54000. Animatable.prototype.enableBlending = function (blendingSpeed) {
  54001. var runtimeAnimations = this._runtimeAnimations;
  54002. for (var index = 0; index < runtimeAnimations.length; index++) {
  54003. runtimeAnimations[index].animation.enableBlending = true;
  54004. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  54005. }
  54006. };
  54007. /**
  54008. * Disable animation blending
  54009. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  54010. */
  54011. Animatable.prototype.disableBlending = function () {
  54012. var runtimeAnimations = this._runtimeAnimations;
  54013. for (var index = 0; index < runtimeAnimations.length; index++) {
  54014. runtimeAnimations[index].animation.enableBlending = false;
  54015. }
  54016. };
  54017. /**
  54018. * Jump directly to a given frame
  54019. * @param frame defines the frame to jump to
  54020. */
  54021. Animatable.prototype.goToFrame = function (frame) {
  54022. var runtimeAnimations = this._runtimeAnimations;
  54023. if (runtimeAnimations[0]) {
  54024. var fps = runtimeAnimations[0].animation.framePerSecond;
  54025. var currentFrame = runtimeAnimations[0].currentFrame;
  54026. var adjustTime = frame - currentFrame;
  54027. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  54028. if (this._localDelayOffset === null) {
  54029. this._localDelayOffset = 0;
  54030. }
  54031. this._localDelayOffset -= delay;
  54032. }
  54033. for (var index = 0; index < runtimeAnimations.length; index++) {
  54034. runtimeAnimations[index].goToFrame(frame);
  54035. }
  54036. };
  54037. /**
  54038. * Pause the animation
  54039. */
  54040. Animatable.prototype.pause = function () {
  54041. if (this._paused) {
  54042. return;
  54043. }
  54044. this._paused = true;
  54045. };
  54046. /**
  54047. * Restart the animation
  54048. */
  54049. Animatable.prototype.restart = function () {
  54050. this._paused = false;
  54051. };
  54052. Animatable.prototype._raiseOnAnimationEnd = function () {
  54053. if (this.onAnimationEnd) {
  54054. this.onAnimationEnd();
  54055. }
  54056. this.onAnimationEndObservable.notifyObservers(this);
  54057. };
  54058. /**
  54059. * Stop and delete the current animation
  54060. * @param animationName defines a string used to only stop some of the runtime animations instead of all
  54061. * @param targetMask - a function that determines if the animation should be stopped based on its target (all animations will be stopped if both this and animationName are empty)
  54062. */
  54063. Animatable.prototype.stop = function (animationName, targetMask) {
  54064. if (animationName || targetMask) {
  54065. var idx = this._scene._activeAnimatables.indexOf(this);
  54066. if (idx > -1) {
  54067. var runtimeAnimations = this._runtimeAnimations;
  54068. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  54069. var runtimeAnimation = runtimeAnimations[index];
  54070. if (animationName && runtimeAnimation.animation.name != animationName) {
  54071. continue;
  54072. }
  54073. if (targetMask && !targetMask(runtimeAnimation.target)) {
  54074. continue;
  54075. }
  54076. runtimeAnimation.dispose();
  54077. runtimeAnimations.splice(index, 1);
  54078. }
  54079. if (runtimeAnimations.length == 0) {
  54080. this._scene._activeAnimatables.splice(idx, 1);
  54081. this._raiseOnAnimationEnd();
  54082. }
  54083. }
  54084. }
  54085. else {
  54086. var index = this._scene._activeAnimatables.indexOf(this);
  54087. if (index > -1) {
  54088. this._scene._activeAnimatables.splice(index, 1);
  54089. var runtimeAnimations = this._runtimeAnimations;
  54090. for (var index = 0; index < runtimeAnimations.length; index++) {
  54091. runtimeAnimations[index].dispose();
  54092. }
  54093. this._raiseOnAnimationEnd();
  54094. }
  54095. }
  54096. };
  54097. /**
  54098. * Wait asynchronously for the animation to end
  54099. * @returns a promise which will be fullfilled when the animation ends
  54100. */
  54101. Animatable.prototype.waitAsync = function () {
  54102. var _this = this;
  54103. return new Promise(function (resolve, reject) {
  54104. _this.onAnimationEndObservable.add(function () {
  54105. resolve(_this);
  54106. }, undefined, undefined, _this, true);
  54107. });
  54108. };
  54109. /** @hidden */
  54110. Animatable.prototype._animate = function (delay) {
  54111. if (this._paused) {
  54112. this.animationStarted = false;
  54113. if (this._pausedDelay === null) {
  54114. this._pausedDelay = delay;
  54115. }
  54116. return true;
  54117. }
  54118. if (this._localDelayOffset === null) {
  54119. this._localDelayOffset = delay;
  54120. this._pausedDelay = null;
  54121. }
  54122. else if (this._pausedDelay !== null) {
  54123. this._localDelayOffset += delay - this._pausedDelay;
  54124. this._pausedDelay = null;
  54125. }
  54126. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  54127. return true;
  54128. }
  54129. // Animating
  54130. var running = false;
  54131. var runtimeAnimations = this._runtimeAnimations;
  54132. var index;
  54133. for (index = 0; index < runtimeAnimations.length; index++) {
  54134. var animation = runtimeAnimations[index];
  54135. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  54136. running = running || isRunning;
  54137. }
  54138. this.animationStarted = running;
  54139. if (!running) {
  54140. if (this.disposeOnEnd) {
  54141. // Remove from active animatables
  54142. index = this._scene._activeAnimatables.indexOf(this);
  54143. this._scene._activeAnimatables.splice(index, 1);
  54144. // Dispose all runtime animations
  54145. for (index = 0; index < runtimeAnimations.length; index++) {
  54146. runtimeAnimations[index].dispose();
  54147. }
  54148. }
  54149. this._raiseOnAnimationEnd();
  54150. if (this.disposeOnEnd) {
  54151. this.onAnimationEnd = null;
  54152. this.onAnimationEndObservable.clear();
  54153. }
  54154. }
  54155. return running;
  54156. };
  54157. return Animatable;
  54158. }());
  54159. BABYLON.Animatable = Animatable;
  54160. })(BABYLON || (BABYLON = {}));
  54161. //# sourceMappingURL=babylon.animatable.js.map
  54162. var BABYLON;
  54163. (function (BABYLON) {
  54164. /**
  54165. * Base class used for every default easing function.
  54166. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54167. */
  54168. var EasingFunction = /** @class */ (function () {
  54169. function EasingFunction() {
  54170. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  54171. }
  54172. /**
  54173. * Sets the easing mode of the current function.
  54174. * @param easingMode Defines the willing mode (EASINGMODE_EASEIN, EASINGMODE_EASEOUT or EASINGMODE_EASEINOUT)
  54175. */
  54176. EasingFunction.prototype.setEasingMode = function (easingMode) {
  54177. var n = Math.min(Math.max(easingMode, 0), 2);
  54178. this._easingMode = n;
  54179. };
  54180. /**
  54181. * Gets the current easing mode.
  54182. * @returns the easing mode
  54183. */
  54184. EasingFunction.prototype.getEasingMode = function () {
  54185. return this._easingMode;
  54186. };
  54187. /**
  54188. * @hidden
  54189. */
  54190. EasingFunction.prototype.easeInCore = function (gradient) {
  54191. throw new Error('You must implement this method');
  54192. };
  54193. /**
  54194. * Given an input gradient between 0 and 1, this returns the corrseponding value
  54195. * of the easing function.
  54196. * @param gradient Defines the value between 0 and 1 we want the easing value for
  54197. * @returns the corresponding value on the curve defined by the easing function
  54198. */
  54199. EasingFunction.prototype.ease = function (gradient) {
  54200. switch (this._easingMode) {
  54201. case EasingFunction.EASINGMODE_EASEIN:
  54202. return this.easeInCore(gradient);
  54203. case EasingFunction.EASINGMODE_EASEOUT:
  54204. return (1 - this.easeInCore(1 - gradient));
  54205. }
  54206. if (gradient >= 0.5) {
  54207. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  54208. }
  54209. return (this.easeInCore(gradient * 2) * 0.5);
  54210. };
  54211. /**
  54212. * Interpolation follows the mathematical formula associated with the easing function.
  54213. */
  54214. EasingFunction.EASINGMODE_EASEIN = 0;
  54215. /**
  54216. * Interpolation follows 100% interpolation minus the output of the formula associated with the easing function.
  54217. */
  54218. EasingFunction.EASINGMODE_EASEOUT = 1;
  54219. /**
  54220. * Interpolation uses EaseIn for the first half of the animation and EaseOut for the second half.
  54221. */
  54222. EasingFunction.EASINGMODE_EASEINOUT = 2;
  54223. return EasingFunction;
  54224. }());
  54225. BABYLON.EasingFunction = EasingFunction;
  54226. /**
  54227. * Easing function with a circle shape (see link below).
  54228. * @see https://easings.net/#easeInCirc
  54229. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54230. */
  54231. var CircleEase = /** @class */ (function (_super) {
  54232. __extends(CircleEase, _super);
  54233. function CircleEase() {
  54234. return _super !== null && _super.apply(this, arguments) || this;
  54235. }
  54236. /** @hidden */
  54237. CircleEase.prototype.easeInCore = function (gradient) {
  54238. gradient = Math.max(0, Math.min(1, gradient));
  54239. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  54240. };
  54241. return CircleEase;
  54242. }(EasingFunction));
  54243. BABYLON.CircleEase = CircleEase;
  54244. /**
  54245. * Easing function with a ease back shape (see link below).
  54246. * @see https://easings.net/#easeInBack
  54247. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54248. */
  54249. var BackEase = /** @class */ (function (_super) {
  54250. __extends(BackEase, _super);
  54251. /**
  54252. * Instantiates a back ease easing
  54253. * @see https://easings.net/#easeInBack
  54254. * @param amplitude Defines the amplitude of the function
  54255. */
  54256. function BackEase(
  54257. /** Defines the amplitude of the function */
  54258. amplitude) {
  54259. if (amplitude === void 0) { amplitude = 1; }
  54260. var _this = _super.call(this) || this;
  54261. _this.amplitude = amplitude;
  54262. return _this;
  54263. }
  54264. /** @hidden */
  54265. BackEase.prototype.easeInCore = function (gradient) {
  54266. var num = Math.max(0, this.amplitude);
  54267. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  54268. };
  54269. return BackEase;
  54270. }(EasingFunction));
  54271. BABYLON.BackEase = BackEase;
  54272. /**
  54273. * Easing function with a bouncing shape (see link below).
  54274. * @see https://easings.net/#easeInBounce
  54275. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54276. */
  54277. var BounceEase = /** @class */ (function (_super) {
  54278. __extends(BounceEase, _super);
  54279. /**
  54280. * Instantiates a bounce easing
  54281. * @see https://easings.net/#easeInBounce
  54282. * @param bounces Defines the number of bounces
  54283. * @param bounciness Defines the amplitude of the bounce
  54284. */
  54285. function BounceEase(
  54286. /** Defines the number of bounces */
  54287. bounces,
  54288. /** Defines the amplitude of the bounce */
  54289. bounciness) {
  54290. if (bounces === void 0) { bounces = 3; }
  54291. if (bounciness === void 0) { bounciness = 2; }
  54292. var _this = _super.call(this) || this;
  54293. _this.bounces = bounces;
  54294. _this.bounciness = bounciness;
  54295. return _this;
  54296. }
  54297. /** @hidden */
  54298. BounceEase.prototype.easeInCore = function (gradient) {
  54299. var y = Math.max(0.0, this.bounces);
  54300. var bounciness = this.bounciness;
  54301. if (bounciness <= 1.0) {
  54302. bounciness = 1.001;
  54303. }
  54304. var num9 = Math.pow(bounciness, y);
  54305. var num5 = 1.0 - bounciness;
  54306. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  54307. var num15 = gradient * num4;
  54308. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  54309. var num3 = Math.floor(num65);
  54310. var num13 = num3 + 1.0;
  54311. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  54312. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  54313. var num7 = (num8 + num12) * 0.5;
  54314. var num6 = gradient - num7;
  54315. var num2 = num7 - num8;
  54316. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  54317. };
  54318. return BounceEase;
  54319. }(EasingFunction));
  54320. BABYLON.BounceEase = BounceEase;
  54321. /**
  54322. * Easing function with a power of 3 shape (see link below).
  54323. * @see https://easings.net/#easeInCubic
  54324. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54325. */
  54326. var CubicEase = /** @class */ (function (_super) {
  54327. __extends(CubicEase, _super);
  54328. function CubicEase() {
  54329. return _super !== null && _super.apply(this, arguments) || this;
  54330. }
  54331. /** @hidden */
  54332. CubicEase.prototype.easeInCore = function (gradient) {
  54333. return (gradient * gradient * gradient);
  54334. };
  54335. return CubicEase;
  54336. }(EasingFunction));
  54337. BABYLON.CubicEase = CubicEase;
  54338. /**
  54339. * Easing function with an elastic shape (see link below).
  54340. * @see https://easings.net/#easeInElastic
  54341. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54342. */
  54343. var ElasticEase = /** @class */ (function (_super) {
  54344. __extends(ElasticEase, _super);
  54345. /**
  54346. * Instantiates an elastic easing function
  54347. * @see https://easings.net/#easeInElastic
  54348. * @param oscillations Defines the number of oscillations
  54349. * @param springiness Defines the amplitude of the oscillations
  54350. */
  54351. function ElasticEase(
  54352. /** Defines the number of oscillations*/
  54353. oscillations,
  54354. /** Defines the amplitude of the oscillations*/
  54355. springiness) {
  54356. if (oscillations === void 0) { oscillations = 3; }
  54357. if (springiness === void 0) { springiness = 3; }
  54358. var _this = _super.call(this) || this;
  54359. _this.oscillations = oscillations;
  54360. _this.springiness = springiness;
  54361. return _this;
  54362. }
  54363. /** @hidden */
  54364. ElasticEase.prototype.easeInCore = function (gradient) {
  54365. var num2;
  54366. var num3 = Math.max(0.0, this.oscillations);
  54367. var num = Math.max(0.0, this.springiness);
  54368. if (num == 0) {
  54369. num2 = gradient;
  54370. }
  54371. else {
  54372. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  54373. }
  54374. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  54375. };
  54376. return ElasticEase;
  54377. }(EasingFunction));
  54378. BABYLON.ElasticEase = ElasticEase;
  54379. /**
  54380. * Easing function with an exponential shape (see link below).
  54381. * @see https://easings.net/#easeInExpo
  54382. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54383. */
  54384. var ExponentialEase = /** @class */ (function (_super) {
  54385. __extends(ExponentialEase, _super);
  54386. /**
  54387. * Instantiates an exponential easing function
  54388. * @see https://easings.net/#easeInExpo
  54389. * @param exponent Defines the exponent of the function
  54390. */
  54391. function ExponentialEase(
  54392. /** Defines the exponent of the function */
  54393. exponent) {
  54394. if (exponent === void 0) { exponent = 2; }
  54395. var _this = _super.call(this) || this;
  54396. _this.exponent = exponent;
  54397. return _this;
  54398. }
  54399. /** @hidden */
  54400. ExponentialEase.prototype.easeInCore = function (gradient) {
  54401. if (this.exponent <= 0) {
  54402. return gradient;
  54403. }
  54404. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  54405. };
  54406. return ExponentialEase;
  54407. }(EasingFunction));
  54408. BABYLON.ExponentialEase = ExponentialEase;
  54409. /**
  54410. * Easing function with a power shape (see link below).
  54411. * @see https://easings.net/#easeInQuad
  54412. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54413. */
  54414. var PowerEase = /** @class */ (function (_super) {
  54415. __extends(PowerEase, _super);
  54416. /**
  54417. * Instantiates an power base easing function
  54418. * @see https://easings.net/#easeInQuad
  54419. * @param power Defines the power of the function
  54420. */
  54421. function PowerEase(
  54422. /** Defines the power of the function */
  54423. power) {
  54424. if (power === void 0) { power = 2; }
  54425. var _this = _super.call(this) || this;
  54426. _this.power = power;
  54427. return _this;
  54428. }
  54429. /** @hidden */
  54430. PowerEase.prototype.easeInCore = function (gradient) {
  54431. var y = Math.max(0.0, this.power);
  54432. return Math.pow(gradient, y);
  54433. };
  54434. return PowerEase;
  54435. }(EasingFunction));
  54436. BABYLON.PowerEase = PowerEase;
  54437. /**
  54438. * Easing function with a power of 2 shape (see link below).
  54439. * @see https://easings.net/#easeInQuad
  54440. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54441. */
  54442. var QuadraticEase = /** @class */ (function (_super) {
  54443. __extends(QuadraticEase, _super);
  54444. function QuadraticEase() {
  54445. return _super !== null && _super.apply(this, arguments) || this;
  54446. }
  54447. /** @hidden */
  54448. QuadraticEase.prototype.easeInCore = function (gradient) {
  54449. return (gradient * gradient);
  54450. };
  54451. return QuadraticEase;
  54452. }(EasingFunction));
  54453. BABYLON.QuadraticEase = QuadraticEase;
  54454. /**
  54455. * Easing function with a power of 4 shape (see link below).
  54456. * @see https://easings.net/#easeInQuart
  54457. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54458. */
  54459. var QuarticEase = /** @class */ (function (_super) {
  54460. __extends(QuarticEase, _super);
  54461. function QuarticEase() {
  54462. return _super !== null && _super.apply(this, arguments) || this;
  54463. }
  54464. /** @hidden */
  54465. QuarticEase.prototype.easeInCore = function (gradient) {
  54466. return (gradient * gradient * gradient * gradient);
  54467. };
  54468. return QuarticEase;
  54469. }(EasingFunction));
  54470. BABYLON.QuarticEase = QuarticEase;
  54471. /**
  54472. * Easing function with a power of 5 shape (see link below).
  54473. * @see https://easings.net/#easeInQuint
  54474. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54475. */
  54476. var QuinticEase = /** @class */ (function (_super) {
  54477. __extends(QuinticEase, _super);
  54478. function QuinticEase() {
  54479. return _super !== null && _super.apply(this, arguments) || this;
  54480. }
  54481. /** @hidden */
  54482. QuinticEase.prototype.easeInCore = function (gradient) {
  54483. return (gradient * gradient * gradient * gradient * gradient);
  54484. };
  54485. return QuinticEase;
  54486. }(EasingFunction));
  54487. BABYLON.QuinticEase = QuinticEase;
  54488. /**
  54489. * Easing function with a sin shape (see link below).
  54490. * @see https://easings.net/#easeInSine
  54491. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54492. */
  54493. var SineEase = /** @class */ (function (_super) {
  54494. __extends(SineEase, _super);
  54495. function SineEase() {
  54496. return _super !== null && _super.apply(this, arguments) || this;
  54497. }
  54498. /** @hidden */
  54499. SineEase.prototype.easeInCore = function (gradient) {
  54500. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  54501. };
  54502. return SineEase;
  54503. }(EasingFunction));
  54504. BABYLON.SineEase = SineEase;
  54505. /**
  54506. * Easing function with a bezier shape (see link below).
  54507. * @see http://cubic-bezier.com/#.17,.67,.83,.67
  54508. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54509. */
  54510. var BezierCurveEase = /** @class */ (function (_super) {
  54511. __extends(BezierCurveEase, _super);
  54512. /**
  54513. * Instantiates a bezier function
  54514. * @see http://cubic-bezier.com/#.17,.67,.83,.67
  54515. * @param x1 Defines the x component of the start tangent in the bezier curve
  54516. * @param y1 Defines the y component of the start tangent in the bezier curve
  54517. * @param x2 Defines the x component of the end tangent in the bezier curve
  54518. * @param y2 Defines the y component of the end tangent in the bezier curve
  54519. */
  54520. function BezierCurveEase(
  54521. /** Defines the x component of the start tangent in the bezier curve */
  54522. x1,
  54523. /** Defines the y component of the start tangent in the bezier curve */
  54524. y1,
  54525. /** Defines the x component of the end tangent in the bezier curve */
  54526. x2,
  54527. /** Defines the y component of the end tangent in the bezier curve */
  54528. y2) {
  54529. if (x1 === void 0) { x1 = 0; }
  54530. if (y1 === void 0) { y1 = 0; }
  54531. if (x2 === void 0) { x2 = 1; }
  54532. if (y2 === void 0) { y2 = 1; }
  54533. var _this = _super.call(this) || this;
  54534. _this.x1 = x1;
  54535. _this.y1 = y1;
  54536. _this.x2 = x2;
  54537. _this.y2 = y2;
  54538. return _this;
  54539. }
  54540. /** @hidden */
  54541. BezierCurveEase.prototype.easeInCore = function (gradient) {
  54542. return BABYLON.BezierCurve.Interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  54543. };
  54544. return BezierCurveEase;
  54545. }(EasingFunction));
  54546. BABYLON.BezierCurveEase = BezierCurveEase;
  54547. })(BABYLON || (BABYLON = {}));
  54548. //# sourceMappingURL=babylon.easing.js.map
  54549. var BABYLON;
  54550. (function (BABYLON) {
  54551. /**
  54552. * A Condition applied to an Action
  54553. */
  54554. var Condition = /** @class */ (function () {
  54555. /**
  54556. * Creates a new Condition
  54557. * @param actionManager the manager of the action the condition is applied to
  54558. */
  54559. function Condition(actionManager) {
  54560. this._actionManager = actionManager;
  54561. }
  54562. /**
  54563. * Check if the current condition is valid
  54564. * @returns a boolean
  54565. */
  54566. Condition.prototype.isValid = function () {
  54567. return true;
  54568. };
  54569. /**
  54570. * Internal only
  54571. * @hidden
  54572. */
  54573. Condition.prototype._getProperty = function (propertyPath) {
  54574. return this._actionManager._getProperty(propertyPath);
  54575. };
  54576. /**
  54577. * Internal only
  54578. * @hidden
  54579. */
  54580. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  54581. return this._actionManager._getEffectiveTarget(target, propertyPath);
  54582. };
  54583. /**
  54584. * Serialize placeholder for child classes
  54585. * @returns the serialized object
  54586. */
  54587. Condition.prototype.serialize = function () {
  54588. };
  54589. /**
  54590. * Internal only
  54591. * @hidden
  54592. */
  54593. Condition.prototype._serialize = function (serializedCondition) {
  54594. return {
  54595. type: 2,
  54596. children: [],
  54597. name: serializedCondition.name,
  54598. properties: serializedCondition.properties
  54599. };
  54600. };
  54601. return Condition;
  54602. }());
  54603. BABYLON.Condition = Condition;
  54604. /**
  54605. * Defines specific conditional operators as extensions of Condition
  54606. */
  54607. var ValueCondition = /** @class */ (function (_super) {
  54608. __extends(ValueCondition, _super);
  54609. /**
  54610. * Creates a new ValueCondition
  54611. * @param actionManager manager for the action the condition applies to
  54612. * @param target for the action
  54613. * @param propertyPath path to specify the property of the target the conditional operator uses
  54614. * @param value the value compared by the conditional operator against the current value of the property
  54615. * @param operator the conditional operator, default ValueCondition.IsEqual
  54616. */
  54617. function ValueCondition(actionManager, target,
  54618. /** path to specify the property of the target the conditional operator uses */
  54619. propertyPath,
  54620. /** the value compared by the conditional operator against the current value of the property */
  54621. value,
  54622. /** the conditional operator, default ValueCondition.IsEqual */
  54623. operator) {
  54624. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  54625. var _this = _super.call(this, actionManager) || this;
  54626. _this.propertyPath = propertyPath;
  54627. _this.value = value;
  54628. _this.operator = operator;
  54629. _this._target = target;
  54630. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  54631. _this._property = _this._getProperty(_this.propertyPath);
  54632. return _this;
  54633. }
  54634. Object.defineProperty(ValueCondition, "IsEqual", {
  54635. /**
  54636. * returns the number for IsEqual
  54637. */
  54638. get: function () {
  54639. return ValueCondition._IsEqual;
  54640. },
  54641. enumerable: true,
  54642. configurable: true
  54643. });
  54644. Object.defineProperty(ValueCondition, "IsDifferent", {
  54645. /**
  54646. * Returns the number for IsDifferent
  54647. */
  54648. get: function () {
  54649. return ValueCondition._IsDifferent;
  54650. },
  54651. enumerable: true,
  54652. configurable: true
  54653. });
  54654. Object.defineProperty(ValueCondition, "IsGreater", {
  54655. /**
  54656. * Returns the number for IsGreater
  54657. */
  54658. get: function () {
  54659. return ValueCondition._IsGreater;
  54660. },
  54661. enumerable: true,
  54662. configurable: true
  54663. });
  54664. Object.defineProperty(ValueCondition, "IsLesser", {
  54665. /**
  54666. * Returns the number for IsLesser
  54667. */
  54668. get: function () {
  54669. return ValueCondition._IsLesser;
  54670. },
  54671. enumerable: true,
  54672. configurable: true
  54673. });
  54674. /**
  54675. * Compares the given value with the property value for the specified conditional operator
  54676. * @returns the result of the comparison
  54677. */
  54678. ValueCondition.prototype.isValid = function () {
  54679. switch (this.operator) {
  54680. case ValueCondition.IsGreater:
  54681. return this._effectiveTarget[this._property] > this.value;
  54682. case ValueCondition.IsLesser:
  54683. return this._effectiveTarget[this._property] < this.value;
  54684. case ValueCondition.IsEqual:
  54685. case ValueCondition.IsDifferent:
  54686. var check;
  54687. if (this.value.equals) {
  54688. check = this.value.equals(this._effectiveTarget[this._property]);
  54689. }
  54690. else {
  54691. check = this.value === this._effectiveTarget[this._property];
  54692. }
  54693. return this.operator === ValueCondition.IsEqual ? check : !check;
  54694. }
  54695. return false;
  54696. };
  54697. /**
  54698. * Serialize the ValueCondition into a JSON compatible object
  54699. * @returns serialization object
  54700. */
  54701. ValueCondition.prototype.serialize = function () {
  54702. return this._serialize({
  54703. name: "ValueCondition",
  54704. properties: [
  54705. BABYLON.Action._GetTargetProperty(this._target),
  54706. { name: "propertyPath", value: this.propertyPath },
  54707. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  54708. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  54709. ]
  54710. });
  54711. };
  54712. /**
  54713. * Gets the name of the conditional operator for the ValueCondition
  54714. * @param operator the conditional operator
  54715. * @returns the name
  54716. */
  54717. ValueCondition.GetOperatorName = function (operator) {
  54718. switch (operator) {
  54719. case ValueCondition._IsEqual: return "IsEqual";
  54720. case ValueCondition._IsDifferent: return "IsDifferent";
  54721. case ValueCondition._IsGreater: return "IsGreater";
  54722. case ValueCondition._IsLesser: return "IsLesser";
  54723. default: return "";
  54724. }
  54725. };
  54726. /**
  54727. * Internal only
  54728. * @hidden
  54729. */
  54730. ValueCondition._IsEqual = 0;
  54731. /**
  54732. * Internal only
  54733. * @hidden
  54734. */
  54735. ValueCondition._IsDifferent = 1;
  54736. /**
  54737. * Internal only
  54738. * @hidden
  54739. */
  54740. ValueCondition._IsGreater = 2;
  54741. /**
  54742. * Internal only
  54743. * @hidden
  54744. */
  54745. ValueCondition._IsLesser = 3;
  54746. return ValueCondition;
  54747. }(Condition));
  54748. BABYLON.ValueCondition = ValueCondition;
  54749. /**
  54750. * Defines a predicate condition as an extension of Condition
  54751. */
  54752. var PredicateCondition = /** @class */ (function (_super) {
  54753. __extends(PredicateCondition, _super);
  54754. /**
  54755. * Creates a new PredicateCondition
  54756. * @param actionManager manager for the action the condition applies to
  54757. * @param predicate defines the predicate function used to validate the condition
  54758. */
  54759. function PredicateCondition(actionManager,
  54760. /** defines the predicate function used to validate the condition */
  54761. predicate) {
  54762. var _this = _super.call(this, actionManager) || this;
  54763. _this.predicate = predicate;
  54764. return _this;
  54765. }
  54766. /**
  54767. * @returns the validity of the predicate condition
  54768. */
  54769. PredicateCondition.prototype.isValid = function () {
  54770. return this.predicate();
  54771. };
  54772. return PredicateCondition;
  54773. }(Condition));
  54774. BABYLON.PredicateCondition = PredicateCondition;
  54775. /**
  54776. * Defines a state condition as an extension of Condition
  54777. */
  54778. var StateCondition = /** @class */ (function (_super) {
  54779. __extends(StateCondition, _super);
  54780. /**
  54781. * Creates a new StateCondition
  54782. * @param actionManager manager for the action the condition applies to
  54783. * @param target of the condition
  54784. * @param value to compare with target state
  54785. */
  54786. function StateCondition(actionManager, target,
  54787. /** Value to compare with target state */
  54788. value) {
  54789. var _this = _super.call(this, actionManager) || this;
  54790. _this.value = value;
  54791. _this._target = target;
  54792. return _this;
  54793. }
  54794. /**
  54795. * Gets a boolean indicating if the current condition is met
  54796. * @returns the validity of the state
  54797. */
  54798. StateCondition.prototype.isValid = function () {
  54799. return this._target.state === this.value;
  54800. };
  54801. /**
  54802. * Serialize the StateCondition into a JSON compatible object
  54803. * @returns serialization object
  54804. */
  54805. StateCondition.prototype.serialize = function () {
  54806. return this._serialize({
  54807. name: "StateCondition",
  54808. properties: [
  54809. BABYLON.Action._GetTargetProperty(this._target),
  54810. { name: "value", value: this.value }
  54811. ]
  54812. });
  54813. };
  54814. return StateCondition;
  54815. }(Condition));
  54816. BABYLON.StateCondition = StateCondition;
  54817. })(BABYLON || (BABYLON = {}));
  54818. //# sourceMappingURL=babylon.condition.js.map
  54819. var BABYLON;
  54820. (function (BABYLON) {
  54821. /**
  54822. * The action to be carried out following a trigger
  54823. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  54824. */
  54825. var Action = /** @class */ (function () {
  54826. /**
  54827. * Creates a new Action
  54828. * @param triggerOptions the trigger, with or without parameters, for the action
  54829. * @param condition an optional determinant of action
  54830. */
  54831. function Action(
  54832. /** the trigger, with or without parameters, for the action */
  54833. triggerOptions, condition) {
  54834. this.triggerOptions = triggerOptions;
  54835. /**
  54836. * An event triggered prior to action being executed.
  54837. */
  54838. this.onBeforeExecuteObservable = new BABYLON.Observable();
  54839. if (triggerOptions.parameter) {
  54840. this.trigger = triggerOptions.trigger;
  54841. this._triggerParameter = triggerOptions.parameter;
  54842. }
  54843. else if (triggerOptions.trigger) {
  54844. this.trigger = triggerOptions.trigger;
  54845. }
  54846. else {
  54847. this.trigger = triggerOptions;
  54848. }
  54849. this._nextActiveAction = this;
  54850. this._condition = condition;
  54851. }
  54852. /**
  54853. * Internal only
  54854. * @hidden
  54855. */
  54856. Action.prototype._prepare = function () {
  54857. };
  54858. /**
  54859. * Gets the trigger parameters
  54860. * @returns the trigger parameters
  54861. */
  54862. Action.prototype.getTriggerParameter = function () {
  54863. return this._triggerParameter;
  54864. };
  54865. /**
  54866. * Internal only - executes current action event
  54867. * @hidden
  54868. */
  54869. Action.prototype._executeCurrent = function (evt) {
  54870. if (this._nextActiveAction._condition) {
  54871. var condition = this._nextActiveAction._condition;
  54872. var currentRenderId = this._actionManager.getScene().getRenderId();
  54873. // We cache the current evaluation for the current frame
  54874. if (condition._evaluationId === currentRenderId) {
  54875. if (!condition._currentResult) {
  54876. return;
  54877. }
  54878. }
  54879. else {
  54880. condition._evaluationId = currentRenderId;
  54881. if (!condition.isValid()) {
  54882. condition._currentResult = false;
  54883. return;
  54884. }
  54885. condition._currentResult = true;
  54886. }
  54887. }
  54888. this.onBeforeExecuteObservable.notifyObservers(this);
  54889. this._nextActiveAction.execute(evt);
  54890. this.skipToNextActiveAction();
  54891. };
  54892. /**
  54893. * Execute placeholder for child classes
  54894. * @param evt optional action event
  54895. */
  54896. Action.prototype.execute = function (evt) {
  54897. };
  54898. /**
  54899. * Skips to next active action
  54900. */
  54901. Action.prototype.skipToNextActiveAction = function () {
  54902. if (this._nextActiveAction._child) {
  54903. if (!this._nextActiveAction._child._actionManager) {
  54904. this._nextActiveAction._child._actionManager = this._actionManager;
  54905. }
  54906. this._nextActiveAction = this._nextActiveAction._child;
  54907. }
  54908. else {
  54909. this._nextActiveAction = this;
  54910. }
  54911. };
  54912. /**
  54913. * Adds action to chain of actions, may be a DoNothingAction
  54914. * @param action defines the next action to execute
  54915. * @returns The action passed in
  54916. * @see https://www.babylonjs-playground.com/#1T30HR#0
  54917. */
  54918. Action.prototype.then = function (action) {
  54919. this._child = action;
  54920. action._actionManager = this._actionManager;
  54921. action._prepare();
  54922. return action;
  54923. };
  54924. /**
  54925. * Internal only
  54926. * @hidden
  54927. */
  54928. Action.prototype._getProperty = function (propertyPath) {
  54929. return this._actionManager._getProperty(propertyPath);
  54930. };
  54931. /**
  54932. * Internal only
  54933. * @hidden
  54934. */
  54935. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  54936. return this._actionManager._getEffectiveTarget(target, propertyPath);
  54937. };
  54938. /**
  54939. * Serialize placeholder for child classes
  54940. * @param parent of child
  54941. * @returns the serialized object
  54942. */
  54943. Action.prototype.serialize = function (parent) {
  54944. };
  54945. /**
  54946. * Internal only called by serialize
  54947. * @hidden
  54948. */
  54949. Action.prototype._serialize = function (serializedAction, parent) {
  54950. var serializationObject = {
  54951. type: 1,
  54952. children: [],
  54953. name: serializedAction.name,
  54954. properties: serializedAction.properties || []
  54955. };
  54956. // Serialize child
  54957. if (this._child) {
  54958. this._child.serialize(serializationObject);
  54959. }
  54960. // Check if "this" has a condition
  54961. if (this._condition) {
  54962. var serializedCondition = this._condition.serialize();
  54963. serializedCondition.children.push(serializationObject);
  54964. if (parent) {
  54965. parent.children.push(serializedCondition);
  54966. }
  54967. return serializedCondition;
  54968. }
  54969. if (parent) {
  54970. parent.children.push(serializationObject);
  54971. }
  54972. return serializationObject;
  54973. };
  54974. /**
  54975. * Internal only
  54976. * @hidden
  54977. */
  54978. Action._SerializeValueAsString = function (value) {
  54979. if (typeof value === "number") {
  54980. return value.toString();
  54981. }
  54982. if (typeof value === "boolean") {
  54983. return value ? "true" : "false";
  54984. }
  54985. if (value instanceof BABYLON.Vector2) {
  54986. return value.x + ", " + value.y;
  54987. }
  54988. if (value instanceof BABYLON.Vector3) {
  54989. return value.x + ", " + value.y + ", " + value.z;
  54990. }
  54991. if (value instanceof BABYLON.Color3) {
  54992. return value.r + ", " + value.g + ", " + value.b;
  54993. }
  54994. if (value instanceof BABYLON.Color4) {
  54995. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  54996. }
  54997. return value; // string
  54998. };
  54999. /**
  55000. * Internal only
  55001. * @hidden
  55002. */
  55003. Action._GetTargetProperty = function (target) {
  55004. return {
  55005. name: "target",
  55006. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  55007. : target instanceof BABYLON.Light ? "LightProperties"
  55008. : target instanceof BABYLON.Camera ? "CameraProperties"
  55009. : "SceneProperties",
  55010. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  55011. };
  55012. };
  55013. return Action;
  55014. }());
  55015. BABYLON.Action = Action;
  55016. })(BABYLON || (BABYLON = {}));
  55017. //# sourceMappingURL=babylon.action.js.map
  55018. var BABYLON;
  55019. (function (BABYLON) {
  55020. /**
  55021. * ActionEvent is the event being sent when an action is triggered.
  55022. */
  55023. var ActionEvent = /** @class */ (function () {
  55024. /**
  55025. * Creates a new ActionEvent
  55026. * @param source The mesh or sprite that triggered the action
  55027. * @param pointerX The X mouse cursor position at the time of the event
  55028. * @param pointerY The Y mouse cursor position at the time of the event
  55029. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  55030. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  55031. * @param additionalData additional data for the event
  55032. */
  55033. function ActionEvent(
  55034. /** The mesh or sprite that triggered the action */
  55035. source,
  55036. /** The X mouse cursor position at the time of the event */
  55037. pointerX,
  55038. /** The Y mouse cursor position at the time of the event */
  55039. pointerY,
  55040. /** The mesh that is currently pointed at (can be null) */
  55041. meshUnderPointer,
  55042. /** the original (browser) event that triggered the ActionEvent */
  55043. sourceEvent,
  55044. /** additional data for the event */
  55045. additionalData) {
  55046. this.source = source;
  55047. this.pointerX = pointerX;
  55048. this.pointerY = pointerY;
  55049. this.meshUnderPointer = meshUnderPointer;
  55050. this.sourceEvent = sourceEvent;
  55051. this.additionalData = additionalData;
  55052. }
  55053. /**
  55054. * Helper function to auto-create an ActionEvent from a source mesh.
  55055. * @param source The source mesh that triggered the event
  55056. * @param evt The original (browser) event
  55057. * @param additionalData additional data for the event
  55058. * @returns the new ActionEvent
  55059. */
  55060. ActionEvent.CreateNew = function (source, evt, additionalData) {
  55061. var scene = source.getScene();
  55062. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  55063. };
  55064. /**
  55065. * Helper function to auto-create an ActionEvent from a source sprite
  55066. * @param source The source sprite that triggered the event
  55067. * @param scene Scene associated with the sprite
  55068. * @param evt The original (browser) event
  55069. * @param additionalData additional data for the event
  55070. * @returns the new ActionEvent
  55071. */
  55072. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  55073. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  55074. };
  55075. /**
  55076. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  55077. * @param scene the scene where the event occurred
  55078. * @param evt The original (browser) event
  55079. * @returns the new ActionEvent
  55080. */
  55081. ActionEvent.CreateNewFromScene = function (scene, evt) {
  55082. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  55083. };
  55084. /**
  55085. * Helper function to auto-create an ActionEvent from a primitive
  55086. * @param prim defines the target primitive
  55087. * @param pointerPos defines the pointer position
  55088. * @param evt The original (browser) event
  55089. * @param additionalData additional data for the event
  55090. * @returns the new ActionEvent
  55091. */
  55092. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  55093. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  55094. };
  55095. return ActionEvent;
  55096. }());
  55097. BABYLON.ActionEvent = ActionEvent;
  55098. /**
  55099. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  55100. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  55101. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55102. */
  55103. var ActionManager = /** @class */ (function () {
  55104. /**
  55105. * Creates a new action manager
  55106. * @param scene defines the hosting scene
  55107. */
  55108. function ActionManager(scene) {
  55109. // Members
  55110. /** Gets the list of actions */
  55111. this.actions = new Array();
  55112. /** Gets the cursor to use when hovering items */
  55113. this.hoverCursor = '';
  55114. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  55115. scene.actionManagers.push(this);
  55116. }
  55117. // Methods
  55118. /**
  55119. * Releases all associated resources
  55120. */
  55121. ActionManager.prototype.dispose = function () {
  55122. var index = this._scene.actionManagers.indexOf(this);
  55123. for (var i = 0; i < this.actions.length; i++) {
  55124. var action = this.actions[i];
  55125. ActionManager.Triggers[action.trigger]--;
  55126. if (ActionManager.Triggers[action.trigger] === 0) {
  55127. delete ActionManager.Triggers[action.trigger];
  55128. }
  55129. }
  55130. if (index > -1) {
  55131. this._scene.actionManagers.splice(index, 1);
  55132. }
  55133. };
  55134. /**
  55135. * Gets hosting scene
  55136. * @returns the hosting scene
  55137. */
  55138. ActionManager.prototype.getScene = function () {
  55139. return this._scene;
  55140. };
  55141. /**
  55142. * Does this action manager handles actions of any of the given triggers
  55143. * @param triggers defines the triggers to be tested
  55144. * @return a boolean indicating whether one (or more) of the triggers is handled
  55145. */
  55146. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  55147. for (var index = 0; index < this.actions.length; index++) {
  55148. var action = this.actions[index];
  55149. if (triggers.indexOf(action.trigger) > -1) {
  55150. return true;
  55151. }
  55152. }
  55153. return false;
  55154. };
  55155. /**
  55156. * Does this action manager handles actions of any of the given triggers. This function takes two arguments for
  55157. * speed.
  55158. * @param triggerA defines the trigger to be tested
  55159. * @param triggerB defines the trigger to be tested
  55160. * @return a boolean indicating whether one (or more) of the triggers is handled
  55161. */
  55162. ActionManager.prototype.hasSpecificTriggers2 = function (triggerA, triggerB) {
  55163. for (var index = 0; index < this.actions.length; index++) {
  55164. var action = this.actions[index];
  55165. if (triggerA == action.trigger || triggerB == action.trigger) {
  55166. return true;
  55167. }
  55168. }
  55169. return false;
  55170. };
  55171. /**
  55172. * Does this action manager handles actions of a given trigger
  55173. * @param trigger defines the trigger to be tested
  55174. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  55175. * @return whether the trigger is handled
  55176. */
  55177. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  55178. for (var index = 0; index < this.actions.length; index++) {
  55179. var action = this.actions[index];
  55180. if (action.trigger === trigger) {
  55181. if (parameterPredicate) {
  55182. if (parameterPredicate(action.getTriggerParameter())) {
  55183. return true;
  55184. }
  55185. }
  55186. else {
  55187. return true;
  55188. }
  55189. }
  55190. }
  55191. return false;
  55192. };
  55193. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  55194. /**
  55195. * Does this action manager has pointer triggers
  55196. */
  55197. get: function () {
  55198. for (var index = 0; index < this.actions.length; index++) {
  55199. var action = this.actions[index];
  55200. if (action.trigger >= ActionManager.OnPickTrigger && action.trigger <= ActionManager.OnPointerOutTrigger) {
  55201. return true;
  55202. }
  55203. }
  55204. return false;
  55205. },
  55206. enumerable: true,
  55207. configurable: true
  55208. });
  55209. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  55210. /**
  55211. * Does this action manager has pick triggers
  55212. */
  55213. get: function () {
  55214. for (var index = 0; index < this.actions.length; index++) {
  55215. var action = this.actions[index];
  55216. if (action.trigger >= ActionManager.OnPickTrigger && action.trigger <= ActionManager.OnPickUpTrigger) {
  55217. return true;
  55218. }
  55219. }
  55220. return false;
  55221. },
  55222. enumerable: true,
  55223. configurable: true
  55224. });
  55225. Object.defineProperty(ActionManager, "HasTriggers", {
  55226. /**
  55227. * Does exist one action manager with at least one trigger
  55228. **/
  55229. get: function () {
  55230. for (var t in ActionManager.Triggers) {
  55231. if (ActionManager.Triggers.hasOwnProperty(t)) {
  55232. return true;
  55233. }
  55234. }
  55235. return false;
  55236. },
  55237. enumerable: true,
  55238. configurable: true
  55239. });
  55240. Object.defineProperty(ActionManager, "HasPickTriggers", {
  55241. /**
  55242. * Does exist one action manager with at least one pick trigger
  55243. **/
  55244. get: function () {
  55245. for (var t in ActionManager.Triggers) {
  55246. if (ActionManager.Triggers.hasOwnProperty(t)) {
  55247. var t_int = parseInt(t);
  55248. if (t_int >= ActionManager.OnPickTrigger && t_int <= ActionManager.OnPickUpTrigger) {
  55249. return true;
  55250. }
  55251. }
  55252. }
  55253. return false;
  55254. },
  55255. enumerable: true,
  55256. configurable: true
  55257. });
  55258. /**
  55259. * Does exist one action manager that handles actions of a given trigger
  55260. * @param trigger defines the trigger to be tested
  55261. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  55262. **/
  55263. ActionManager.HasSpecificTrigger = function (trigger) {
  55264. for (var t in ActionManager.Triggers) {
  55265. if (ActionManager.Triggers.hasOwnProperty(t)) {
  55266. var t_int = parseInt(t);
  55267. if (t_int === trigger) {
  55268. return true;
  55269. }
  55270. }
  55271. }
  55272. return false;
  55273. };
  55274. /**
  55275. * Registers an action to this action manager
  55276. * @param action defines the action to be registered
  55277. * @return the action amended (prepared) after registration
  55278. */
  55279. ActionManager.prototype.registerAction = function (action) {
  55280. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  55281. if (this.getScene().actionManager !== this) {
  55282. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  55283. return null;
  55284. }
  55285. }
  55286. this.actions.push(action);
  55287. if (ActionManager.Triggers[action.trigger]) {
  55288. ActionManager.Triggers[action.trigger]++;
  55289. }
  55290. else {
  55291. ActionManager.Triggers[action.trigger] = 1;
  55292. }
  55293. action._actionManager = this;
  55294. action._prepare();
  55295. return action;
  55296. };
  55297. /**
  55298. * Unregisters an action to this action manager
  55299. * @param action defines the action to be unregistered
  55300. * @return a boolean indicating whether the action has been unregistered
  55301. */
  55302. ActionManager.prototype.unregisterAction = function (action) {
  55303. var index = this.actions.indexOf(action);
  55304. if (index !== -1) {
  55305. this.actions.splice(index, 1);
  55306. ActionManager.Triggers[action.trigger] -= 1;
  55307. if (ActionManager.Triggers[action.trigger] === 0) {
  55308. delete ActionManager.Triggers[action.trigger];
  55309. }
  55310. delete action._actionManager;
  55311. return true;
  55312. }
  55313. return false;
  55314. };
  55315. /**
  55316. * Process a specific trigger
  55317. * @param trigger defines the trigger to process
  55318. * @param evt defines the event details to be processed
  55319. */
  55320. ActionManager.prototype.processTrigger = function (trigger, evt) {
  55321. for (var index = 0; index < this.actions.length; index++) {
  55322. var action = this.actions[index];
  55323. if (action.trigger === trigger) {
  55324. if (evt) {
  55325. if (trigger === ActionManager.OnKeyUpTrigger
  55326. || trigger === ActionManager.OnKeyDownTrigger) {
  55327. var parameter = action.getTriggerParameter();
  55328. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  55329. if (!parameter.toLowerCase) {
  55330. continue;
  55331. }
  55332. var lowerCase = parameter.toLowerCase();
  55333. if (lowerCase !== evt.sourceEvent.key) {
  55334. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  55335. var actualkey = String.fromCharCode(unicode).toLowerCase();
  55336. if (actualkey !== lowerCase) {
  55337. continue;
  55338. }
  55339. }
  55340. }
  55341. }
  55342. }
  55343. action._executeCurrent(evt);
  55344. }
  55345. }
  55346. };
  55347. /** @hidden */
  55348. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  55349. var properties = propertyPath.split(".");
  55350. for (var index = 0; index < properties.length - 1; index++) {
  55351. target = target[properties[index]];
  55352. }
  55353. return target;
  55354. };
  55355. /** @hidden */
  55356. ActionManager.prototype._getProperty = function (propertyPath) {
  55357. var properties = propertyPath.split(".");
  55358. return properties[properties.length - 1];
  55359. };
  55360. /**
  55361. * Serialize this manager to a JSON object
  55362. * @param name defines the property name to store this manager
  55363. * @returns a JSON representation of this manager
  55364. */
  55365. ActionManager.prototype.serialize = function (name) {
  55366. var root = {
  55367. children: new Array(),
  55368. name: name,
  55369. type: 3,
  55370. properties: new Array() // Empty for root but required
  55371. };
  55372. for (var i = 0; i < this.actions.length; i++) {
  55373. var triggerObject = {
  55374. type: 0,
  55375. children: new Array(),
  55376. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  55377. properties: new Array()
  55378. };
  55379. var triggerOptions = this.actions[i].triggerOptions;
  55380. if (triggerOptions && typeof triggerOptions !== "number") {
  55381. if (triggerOptions.parameter instanceof BABYLON.Node) {
  55382. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  55383. }
  55384. else {
  55385. var parameter = {};
  55386. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  55387. if (triggerOptions.parameter.mesh) {
  55388. parameter._meshId = triggerOptions.parameter.mesh.id;
  55389. }
  55390. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  55391. }
  55392. }
  55393. // Serialize child action, recursively
  55394. this.actions[i].serialize(triggerObject);
  55395. // Add serialized trigger
  55396. root.children.push(triggerObject);
  55397. }
  55398. return root;
  55399. };
  55400. /**
  55401. * Creates a new ActionManager from a JSON data
  55402. * @param parsedActions defines the JSON data to read from
  55403. * @param object defines the hosting mesh
  55404. * @param scene defines the hosting scene
  55405. */
  55406. ActionManager.Parse = function (parsedActions, object, scene) {
  55407. var actionManager = new ActionManager(scene);
  55408. if (object === null)
  55409. scene.actionManager = actionManager;
  55410. else
  55411. object.actionManager = actionManager;
  55412. // instanciate a new object
  55413. var instanciate = function (name, params) {
  55414. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  55415. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  55416. newInstance.constructor.apply(newInstance, params);
  55417. return newInstance;
  55418. };
  55419. var parseParameter = function (name, value, target, propertyPath) {
  55420. if (propertyPath === null) {
  55421. // String, boolean or float
  55422. var floatValue = parseFloat(value);
  55423. if (value === "true" || value === "false")
  55424. return value === "true";
  55425. else
  55426. return isNaN(floatValue) ? value : floatValue;
  55427. }
  55428. var effectiveTarget = propertyPath.split(".");
  55429. var values = value.split(",");
  55430. // Get effective Target
  55431. for (var i = 0; i < effectiveTarget.length; i++) {
  55432. target = target[effectiveTarget[i]];
  55433. }
  55434. // Return appropriate value with its type
  55435. if (typeof (target) === "boolean")
  55436. return values[0] === "true";
  55437. if (typeof (target) === "string")
  55438. return values[0];
  55439. // Parameters with multiple values such as Vector3 etc.
  55440. var split = new Array();
  55441. for (var i = 0; i < values.length; i++)
  55442. split.push(parseFloat(values[i]));
  55443. if (target instanceof BABYLON.Vector3)
  55444. return BABYLON.Vector3.FromArray(split);
  55445. if (target instanceof BABYLON.Vector4)
  55446. return BABYLON.Vector4.FromArray(split);
  55447. if (target instanceof BABYLON.Color3)
  55448. return BABYLON.Color3.FromArray(split);
  55449. if (target instanceof BABYLON.Color4)
  55450. return BABYLON.Color4.FromArray(split);
  55451. return parseFloat(values[0]);
  55452. };
  55453. // traverse graph per trigger
  55454. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  55455. if (combineArray === void 0) { combineArray = null; }
  55456. if (parsedAction.detached)
  55457. return;
  55458. var parameters = new Array();
  55459. var target = null;
  55460. var propertyPath = null;
  55461. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  55462. // Parameters
  55463. if (parsedAction.type === 2)
  55464. parameters.push(actionManager);
  55465. else
  55466. parameters.push(trigger);
  55467. if (combine) {
  55468. var actions = new Array();
  55469. for (var j = 0; j < parsedAction.combine.length; j++) {
  55470. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  55471. }
  55472. parameters.push(actions);
  55473. }
  55474. else {
  55475. for (var i = 0; i < parsedAction.properties.length; i++) {
  55476. var value = parsedAction.properties[i].value;
  55477. var name = parsedAction.properties[i].name;
  55478. var targetType = parsedAction.properties[i].targetType;
  55479. if (name === "target")
  55480. if (targetType !== null && targetType === "SceneProperties")
  55481. value = target = scene;
  55482. else
  55483. value = target = scene.getNodeByName(value);
  55484. else if (name === "parent")
  55485. value = scene.getNodeByName(value);
  55486. else if (name === "sound") {
  55487. // Can not externalize to component, so only checks for the presence off the API.
  55488. if (scene.getSoundByName) {
  55489. value = scene.getSoundByName(value);
  55490. }
  55491. }
  55492. else if (name !== "propertyPath") {
  55493. if (parsedAction.type === 2 && name === "operator")
  55494. value = BABYLON.ValueCondition[value];
  55495. else
  55496. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  55497. }
  55498. else {
  55499. propertyPath = value;
  55500. }
  55501. parameters.push(value);
  55502. }
  55503. }
  55504. if (combineArray === null) {
  55505. parameters.push(condition);
  55506. }
  55507. else {
  55508. parameters.push(null);
  55509. }
  55510. // If interpolate value action
  55511. if (parsedAction.name === "InterpolateValueAction") {
  55512. var param = parameters[parameters.length - 2];
  55513. parameters[parameters.length - 1] = param;
  55514. parameters[parameters.length - 2] = condition;
  55515. }
  55516. // Action or condition(s) and not CombineAction
  55517. var newAction = instanciate(parsedAction.name, parameters);
  55518. if (newAction instanceof BABYLON.Condition && condition !== null) {
  55519. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  55520. if (action)
  55521. action.then(nothing);
  55522. else
  55523. actionManager.registerAction(nothing);
  55524. action = nothing;
  55525. }
  55526. if (combineArray === null) {
  55527. if (newAction instanceof BABYLON.Condition) {
  55528. condition = newAction;
  55529. newAction = action;
  55530. }
  55531. else {
  55532. condition = null;
  55533. if (action)
  55534. action.then(newAction);
  55535. else
  55536. actionManager.registerAction(newAction);
  55537. }
  55538. }
  55539. else {
  55540. combineArray.push(newAction);
  55541. }
  55542. for (var i = 0; i < parsedAction.children.length; i++)
  55543. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  55544. };
  55545. // triggers
  55546. for (var i = 0; i < parsedActions.children.length; i++) {
  55547. var triggerParams;
  55548. var trigger = parsedActions.children[i];
  55549. if (trigger.properties.length > 0) {
  55550. var param = trigger.properties[0].value;
  55551. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  55552. if (value._meshId) {
  55553. value.mesh = scene.getMeshByID(value._meshId);
  55554. }
  55555. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  55556. }
  55557. else
  55558. triggerParams = ActionManager[trigger.name];
  55559. for (var j = 0; j < trigger.children.length; j++) {
  55560. if (!trigger.detached)
  55561. traverse(trigger.children[j], triggerParams, null, null);
  55562. }
  55563. }
  55564. };
  55565. /**
  55566. * Get a trigger name by index
  55567. * @param trigger defines the trigger index
  55568. * @returns a trigger name
  55569. */
  55570. ActionManager.GetTriggerName = function (trigger) {
  55571. switch (trigger) {
  55572. case 0: return "NothingTrigger";
  55573. case 1: return "OnPickTrigger";
  55574. case 2: return "OnLeftPickTrigger";
  55575. case 3: return "OnRightPickTrigger";
  55576. case 4: return "OnCenterPickTrigger";
  55577. case 5: return "OnPickDownTrigger";
  55578. case 6: return "OnPickUpTrigger";
  55579. case 7: return "OnLongPressTrigger";
  55580. case 8: return "OnPointerOverTrigger";
  55581. case 9: return "OnPointerOutTrigger";
  55582. case 10: return "OnEveryFrameTrigger";
  55583. case 11: return "OnIntersectionEnterTrigger";
  55584. case 12: return "OnIntersectionExitTrigger";
  55585. case 13: return "OnKeyDownTrigger";
  55586. case 14: return "OnKeyUpTrigger";
  55587. case 15: return "OnPickOutTrigger";
  55588. default: return "";
  55589. }
  55590. };
  55591. /**
  55592. * Nothing
  55593. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55594. */
  55595. ActionManager.NothingTrigger = 0;
  55596. /**
  55597. * On pick
  55598. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55599. */
  55600. ActionManager.OnPickTrigger = 1;
  55601. /**
  55602. * On left pick
  55603. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55604. */
  55605. ActionManager.OnLeftPickTrigger = 2;
  55606. /**
  55607. * On right pick
  55608. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55609. */
  55610. ActionManager.OnRightPickTrigger = 3;
  55611. /**
  55612. * On center pick
  55613. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55614. */
  55615. ActionManager.OnCenterPickTrigger = 4;
  55616. /**
  55617. * On pick down
  55618. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55619. */
  55620. ActionManager.OnPickDownTrigger = 5;
  55621. /**
  55622. * On double pick
  55623. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55624. */
  55625. ActionManager.OnDoublePickTrigger = 6;
  55626. /**
  55627. * On pick up
  55628. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55629. */
  55630. ActionManager.OnPickUpTrigger = 7;
  55631. /**
  55632. * On pick out.
  55633. * This trigger will only be raised if you also declared a OnPickDown
  55634. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55635. */
  55636. ActionManager.OnPickOutTrigger = 16;
  55637. /**
  55638. * On long press
  55639. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55640. */
  55641. ActionManager.OnLongPressTrigger = 8;
  55642. /**
  55643. * On pointer over
  55644. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55645. */
  55646. ActionManager.OnPointerOverTrigger = 9;
  55647. /**
  55648. * On pointer out
  55649. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55650. */
  55651. ActionManager.OnPointerOutTrigger = 10;
  55652. /**
  55653. * On every frame
  55654. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55655. */
  55656. ActionManager.OnEveryFrameTrigger = 11;
  55657. /**
  55658. * On intersection enter
  55659. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55660. */
  55661. ActionManager.OnIntersectionEnterTrigger = 12;
  55662. /**
  55663. * On intersection exit
  55664. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55665. */
  55666. ActionManager.OnIntersectionExitTrigger = 13;
  55667. /**
  55668. * On key down
  55669. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55670. */
  55671. ActionManager.OnKeyDownTrigger = 14;
  55672. /**
  55673. * On key up
  55674. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55675. */
  55676. ActionManager.OnKeyUpTrigger = 15;
  55677. /** Gets the list of active triggers */
  55678. ActionManager.Triggers = {};
  55679. return ActionManager;
  55680. }());
  55681. BABYLON.ActionManager = ActionManager;
  55682. })(BABYLON || (BABYLON = {}));
  55683. //# sourceMappingURL=babylon.actionManager.js.map
  55684. var BABYLON;
  55685. (function (BABYLON) {
  55686. /**
  55687. * This defines an action responsible to change the value of a property
  55688. * by interpolating between its current value and the newly set one once triggered.
  55689. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55690. */
  55691. var InterpolateValueAction = /** @class */ (function (_super) {
  55692. __extends(InterpolateValueAction, _super);
  55693. /**
  55694. * Instantiate the action
  55695. * @param triggerOptions defines the trigger options
  55696. * @param target defines the object containing the value to interpolate
  55697. * @param propertyPath defines the path to the property in the target object
  55698. * @param value defines the target value at the end of the interpolation
  55699. * @param duration deines the time it will take for the property to interpolate to the value.
  55700. * @param condition defines the trigger related conditions
  55701. * @param stopOtherAnimations defines if the other scene animations should be stopped when the action has been triggered
  55702. * @param onInterpolationDone defines a callback raised once the interpolation animation has been done
  55703. */
  55704. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  55705. if (duration === void 0) { duration = 1000; }
  55706. var _this = _super.call(this, triggerOptions, condition) || this;
  55707. /**
  55708. * Defines the time it will take for the property to interpolate to the value.
  55709. */
  55710. _this.duration = 1000;
  55711. /**
  55712. * Observable triggered once the interpolation animation has been done.
  55713. */
  55714. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  55715. _this.propertyPath = propertyPath;
  55716. _this.value = value;
  55717. _this.duration = duration;
  55718. _this.stopOtherAnimations = stopOtherAnimations;
  55719. _this.onInterpolationDone = onInterpolationDone;
  55720. _this._target = _this._effectiveTarget = target;
  55721. return _this;
  55722. }
  55723. /** @hidden */
  55724. InterpolateValueAction.prototype._prepare = function () {
  55725. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  55726. this._property = this._getProperty(this.propertyPath);
  55727. };
  55728. /**
  55729. * Execute the action starts the value interpolation.
  55730. */
  55731. InterpolateValueAction.prototype.execute = function () {
  55732. var _this = this;
  55733. var scene = this._actionManager.getScene();
  55734. var keys = [
  55735. {
  55736. frame: 0,
  55737. value: this._effectiveTarget[this._property]
  55738. }, {
  55739. frame: 100,
  55740. value: this.value
  55741. }
  55742. ];
  55743. var dataType;
  55744. if (typeof this.value === "number") {
  55745. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  55746. }
  55747. else if (this.value instanceof BABYLON.Color3) {
  55748. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  55749. }
  55750. else if (this.value instanceof BABYLON.Vector3) {
  55751. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  55752. }
  55753. else if (this.value instanceof BABYLON.Matrix) {
  55754. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  55755. }
  55756. else if (this.value instanceof BABYLON.Quaternion) {
  55757. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  55758. }
  55759. else {
  55760. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  55761. return;
  55762. }
  55763. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  55764. animation.setKeys(keys);
  55765. if (this.stopOtherAnimations) {
  55766. scene.stopAnimation(this._effectiveTarget);
  55767. }
  55768. var wrapper = function () {
  55769. _this.onInterpolationDoneObservable.notifyObservers(_this);
  55770. if (_this.onInterpolationDone) {
  55771. _this.onInterpolationDone();
  55772. }
  55773. };
  55774. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  55775. };
  55776. /**
  55777. * Serializes the actions and its related information.
  55778. * @param parent defines the object to serialize in
  55779. * @returns the serialized object
  55780. */
  55781. InterpolateValueAction.prototype.serialize = function (parent) {
  55782. return _super.prototype._serialize.call(this, {
  55783. name: "InterpolateValueAction",
  55784. properties: [
  55785. BABYLON.Action._GetTargetProperty(this._target),
  55786. { name: "propertyPath", value: this.propertyPath },
  55787. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  55788. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  55789. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  55790. ]
  55791. }, parent);
  55792. };
  55793. return InterpolateValueAction;
  55794. }(BABYLON.Action));
  55795. BABYLON.InterpolateValueAction = InterpolateValueAction;
  55796. })(BABYLON || (BABYLON = {}));
  55797. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  55798. var BABYLON;
  55799. (function (BABYLON) {
  55800. /**
  55801. * This defines an action responsible to toggle a boolean once triggered.
  55802. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55803. */
  55804. var SwitchBooleanAction = /** @class */ (function (_super) {
  55805. __extends(SwitchBooleanAction, _super);
  55806. /**
  55807. * Instantiate the action
  55808. * @param triggerOptions defines the trigger options
  55809. * @param target defines the object containing the boolean
  55810. * @param propertyPath defines the path to the boolean property in the target object
  55811. * @param condition defines the trigger related conditions
  55812. */
  55813. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  55814. var _this = _super.call(this, triggerOptions, condition) || this;
  55815. _this.propertyPath = propertyPath;
  55816. _this._target = _this._effectiveTarget = target;
  55817. return _this;
  55818. }
  55819. /** @hidden */
  55820. SwitchBooleanAction.prototype._prepare = function () {
  55821. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  55822. this._property = this._getProperty(this.propertyPath);
  55823. };
  55824. /**
  55825. * Execute the action toggle the boolean value.
  55826. */
  55827. SwitchBooleanAction.prototype.execute = function () {
  55828. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  55829. };
  55830. /**
  55831. * Serializes the actions and its related information.
  55832. * @param parent defines the object to serialize in
  55833. * @returns the serialized object
  55834. */
  55835. SwitchBooleanAction.prototype.serialize = function (parent) {
  55836. return _super.prototype._serialize.call(this, {
  55837. name: "SwitchBooleanAction",
  55838. properties: [
  55839. BABYLON.Action._GetTargetProperty(this._target),
  55840. { name: "propertyPath", value: this.propertyPath }
  55841. ]
  55842. }, parent);
  55843. };
  55844. return SwitchBooleanAction;
  55845. }(BABYLON.Action));
  55846. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  55847. /**
  55848. * This defines an action responsible to set a the state field of the target
  55849. * to a desired value once triggered.
  55850. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55851. */
  55852. var SetStateAction = /** @class */ (function (_super) {
  55853. __extends(SetStateAction, _super);
  55854. /**
  55855. * Instantiate the action
  55856. * @param triggerOptions defines the trigger options
  55857. * @param target defines the object containing the state property
  55858. * @param value defines the value to store in the state field
  55859. * @param condition defines the trigger related conditions
  55860. */
  55861. function SetStateAction(triggerOptions, target, value, condition) {
  55862. var _this = _super.call(this, triggerOptions, condition) || this;
  55863. _this.value = value;
  55864. _this._target = target;
  55865. return _this;
  55866. }
  55867. /**
  55868. * Execute the action and store the value on the target state property.
  55869. */
  55870. SetStateAction.prototype.execute = function () {
  55871. this._target.state = this.value;
  55872. };
  55873. /**
  55874. * Serializes the actions and its related information.
  55875. * @param parent defines the object to serialize in
  55876. * @returns the serialized object
  55877. */
  55878. SetStateAction.prototype.serialize = function (parent) {
  55879. return _super.prototype._serialize.call(this, {
  55880. name: "SetStateAction",
  55881. properties: [
  55882. BABYLON.Action._GetTargetProperty(this._target),
  55883. { name: "value", value: this.value }
  55884. ]
  55885. }, parent);
  55886. };
  55887. return SetStateAction;
  55888. }(BABYLON.Action));
  55889. BABYLON.SetStateAction = SetStateAction;
  55890. /**
  55891. * This defines an action responsible to set a property of the target
  55892. * to a desired value once triggered.
  55893. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55894. */
  55895. var SetValueAction = /** @class */ (function (_super) {
  55896. __extends(SetValueAction, _super);
  55897. /**
  55898. * Instantiate the action
  55899. * @param triggerOptions defines the trigger options
  55900. * @param target defines the object containing the property
  55901. * @param propertyPath defines the path of the property to set in the target
  55902. * @param value defines the value to set in the property
  55903. * @param condition defines the trigger related conditions
  55904. */
  55905. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  55906. var _this = _super.call(this, triggerOptions, condition) || this;
  55907. _this.propertyPath = propertyPath;
  55908. _this.value = value;
  55909. _this._target = _this._effectiveTarget = target;
  55910. return _this;
  55911. }
  55912. /** @hidden */
  55913. SetValueAction.prototype._prepare = function () {
  55914. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  55915. this._property = this._getProperty(this.propertyPath);
  55916. };
  55917. /**
  55918. * Execute the action and set the targetted property to the desired value.
  55919. */
  55920. SetValueAction.prototype.execute = function () {
  55921. this._effectiveTarget[this._property] = this.value;
  55922. if (this._target.markAsDirty) {
  55923. this._target.markAsDirty(this._property);
  55924. }
  55925. };
  55926. /**
  55927. * Serializes the actions and its related information.
  55928. * @param parent defines the object to serialize in
  55929. * @returns the serialized object
  55930. */
  55931. SetValueAction.prototype.serialize = function (parent) {
  55932. return _super.prototype._serialize.call(this, {
  55933. name: "SetValueAction",
  55934. properties: [
  55935. BABYLON.Action._GetTargetProperty(this._target),
  55936. { name: "propertyPath", value: this.propertyPath },
  55937. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  55938. ]
  55939. }, parent);
  55940. };
  55941. return SetValueAction;
  55942. }(BABYLON.Action));
  55943. BABYLON.SetValueAction = SetValueAction;
  55944. /**
  55945. * This defines an action responsible to increment the target value
  55946. * to a desired value once triggered.
  55947. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55948. */
  55949. var IncrementValueAction = /** @class */ (function (_super) {
  55950. __extends(IncrementValueAction, _super);
  55951. /**
  55952. * Instantiate the action
  55953. * @param triggerOptions defines the trigger options
  55954. * @param target defines the object containing the property
  55955. * @param propertyPath defines the path of the property to increment in the target
  55956. * @param value defines the value value we should increment the property by
  55957. * @param condition defines the trigger related conditions
  55958. */
  55959. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  55960. var _this = _super.call(this, triggerOptions, condition) || this;
  55961. _this.propertyPath = propertyPath;
  55962. _this.value = value;
  55963. _this._target = _this._effectiveTarget = target;
  55964. return _this;
  55965. }
  55966. /** @hidden */
  55967. IncrementValueAction.prototype._prepare = function () {
  55968. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  55969. this._property = this._getProperty(this.propertyPath);
  55970. if (typeof this._effectiveTarget[this._property] !== "number") {
  55971. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  55972. }
  55973. };
  55974. /**
  55975. * Execute the action and increment the target of the value amount.
  55976. */
  55977. IncrementValueAction.prototype.execute = function () {
  55978. this._effectiveTarget[this._property] += this.value;
  55979. if (this._target.markAsDirty) {
  55980. this._target.markAsDirty(this._property);
  55981. }
  55982. };
  55983. /**
  55984. * Serializes the actions and its related information.
  55985. * @param parent defines the object to serialize in
  55986. * @returns the serialized object
  55987. */
  55988. IncrementValueAction.prototype.serialize = function (parent) {
  55989. return _super.prototype._serialize.call(this, {
  55990. name: "IncrementValueAction",
  55991. properties: [
  55992. BABYLON.Action._GetTargetProperty(this._target),
  55993. { name: "propertyPath", value: this.propertyPath },
  55994. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  55995. ]
  55996. }, parent);
  55997. };
  55998. return IncrementValueAction;
  55999. }(BABYLON.Action));
  56000. BABYLON.IncrementValueAction = IncrementValueAction;
  56001. /**
  56002. * This defines an action responsible to start an animation once triggered.
  56003. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  56004. */
  56005. var PlayAnimationAction = /** @class */ (function (_super) {
  56006. __extends(PlayAnimationAction, _super);
  56007. /**
  56008. * Instantiate the action
  56009. * @param triggerOptions defines the trigger options
  56010. * @param target defines the target animation or animation name
  56011. * @param from defines from where the animation should start (animation frame)
  56012. * @param end defines where the animation should stop (animation frame)
  56013. * @param loop defines if the animation should loop or stop after the first play
  56014. * @param condition defines the trigger related conditions
  56015. */
  56016. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  56017. var _this = _super.call(this, triggerOptions, condition) || this;
  56018. _this.from = from;
  56019. _this.to = to;
  56020. _this.loop = loop;
  56021. _this._target = target;
  56022. return _this;
  56023. }
  56024. /** @hidden */
  56025. PlayAnimationAction.prototype._prepare = function () {
  56026. };
  56027. /**
  56028. * Execute the action and play the animation.
  56029. */
  56030. PlayAnimationAction.prototype.execute = function () {
  56031. var scene = this._actionManager.getScene();
  56032. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  56033. };
  56034. /**
  56035. * Serializes the actions and its related information.
  56036. * @param parent defines the object to serialize in
  56037. * @returns the serialized object
  56038. */
  56039. PlayAnimationAction.prototype.serialize = function (parent) {
  56040. return _super.prototype._serialize.call(this, {
  56041. name: "PlayAnimationAction",
  56042. properties: [
  56043. BABYLON.Action._GetTargetProperty(this._target),
  56044. { name: "from", value: String(this.from) },
  56045. { name: "to", value: String(this.to) },
  56046. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  56047. ]
  56048. }, parent);
  56049. };
  56050. return PlayAnimationAction;
  56051. }(BABYLON.Action));
  56052. BABYLON.PlayAnimationAction = PlayAnimationAction;
  56053. /**
  56054. * This defines an action responsible to stop an animation once triggered.
  56055. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  56056. */
  56057. var StopAnimationAction = /** @class */ (function (_super) {
  56058. __extends(StopAnimationAction, _super);
  56059. /**
  56060. * Instantiate the action
  56061. * @param triggerOptions defines the trigger options
  56062. * @param target defines the target animation or animation name
  56063. * @param condition defines the trigger related conditions
  56064. */
  56065. function StopAnimationAction(triggerOptions, target, condition) {
  56066. var _this = _super.call(this, triggerOptions, condition) || this;
  56067. _this._target = target;
  56068. return _this;
  56069. }
  56070. /** @hidden */
  56071. StopAnimationAction.prototype._prepare = function () {
  56072. };
  56073. /**
  56074. * Execute the action and stop the animation.
  56075. */
  56076. StopAnimationAction.prototype.execute = function () {
  56077. var scene = this._actionManager.getScene();
  56078. scene.stopAnimation(this._target);
  56079. };
  56080. /**
  56081. * Serializes the actions and its related information.
  56082. * @param parent defines the object to serialize in
  56083. * @returns the serialized object
  56084. */
  56085. StopAnimationAction.prototype.serialize = function (parent) {
  56086. return _super.prototype._serialize.call(this, {
  56087. name: "StopAnimationAction",
  56088. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  56089. }, parent);
  56090. };
  56091. return StopAnimationAction;
  56092. }(BABYLON.Action));
  56093. BABYLON.StopAnimationAction = StopAnimationAction;
  56094. /**
  56095. * This defines an action responsible that does nothing once triggered.
  56096. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  56097. */
  56098. var DoNothingAction = /** @class */ (function (_super) {
  56099. __extends(DoNothingAction, _super);
  56100. /**
  56101. * Instantiate the action
  56102. * @param triggerOptions defines the trigger options
  56103. * @param condition defines the trigger related conditions
  56104. */
  56105. function DoNothingAction(triggerOptions, condition) {
  56106. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  56107. return _super.call(this, triggerOptions, condition) || this;
  56108. }
  56109. /**
  56110. * Execute the action and do nothing.
  56111. */
  56112. DoNothingAction.prototype.execute = function () {
  56113. };
  56114. /**
  56115. * Serializes the actions and its related information.
  56116. * @param parent defines the object to serialize in
  56117. * @returns the serialized object
  56118. */
  56119. DoNothingAction.prototype.serialize = function (parent) {
  56120. return _super.prototype._serialize.call(this, {
  56121. name: "DoNothingAction",
  56122. properties: []
  56123. }, parent);
  56124. };
  56125. return DoNothingAction;
  56126. }(BABYLON.Action));
  56127. BABYLON.DoNothingAction = DoNothingAction;
  56128. /**
  56129. * This defines an action responsible to trigger several actions once triggered.
  56130. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  56131. */
  56132. var CombineAction = /** @class */ (function (_super) {
  56133. __extends(CombineAction, _super);
  56134. /**
  56135. * Instantiate the action
  56136. * @param triggerOptions defines the trigger options
  56137. * @param children defines the list of aggregated animations to run
  56138. * @param condition defines the trigger related conditions
  56139. */
  56140. function CombineAction(triggerOptions, children, condition) {
  56141. var _this = _super.call(this, triggerOptions, condition) || this;
  56142. _this.children = children;
  56143. return _this;
  56144. }
  56145. /** @hidden */
  56146. CombineAction.prototype._prepare = function () {
  56147. for (var index = 0; index < this.children.length; index++) {
  56148. this.children[index]._actionManager = this._actionManager;
  56149. this.children[index]._prepare();
  56150. }
  56151. };
  56152. /**
  56153. * Execute the action and executes all the aggregated actions.
  56154. */
  56155. CombineAction.prototype.execute = function (evt) {
  56156. for (var index = 0; index < this.children.length; index++) {
  56157. this.children[index].execute(evt);
  56158. }
  56159. };
  56160. /**
  56161. * Serializes the actions and its related information.
  56162. * @param parent defines the object to serialize in
  56163. * @returns the serialized object
  56164. */
  56165. CombineAction.prototype.serialize = function (parent) {
  56166. var serializationObject = _super.prototype._serialize.call(this, {
  56167. name: "CombineAction",
  56168. properties: [],
  56169. combine: []
  56170. }, parent);
  56171. for (var i = 0; i < this.children.length; i++) {
  56172. serializationObject.combine.push(this.children[i].serialize(null));
  56173. }
  56174. return serializationObject;
  56175. };
  56176. return CombineAction;
  56177. }(BABYLON.Action));
  56178. BABYLON.CombineAction = CombineAction;
  56179. /**
  56180. * This defines an action responsible to run code (external event) once triggered.
  56181. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  56182. */
  56183. var ExecuteCodeAction = /** @class */ (function (_super) {
  56184. __extends(ExecuteCodeAction, _super);
  56185. /**
  56186. * Instantiate the action
  56187. * @param triggerOptions defines the trigger options
  56188. * @param func defines the callback function to run
  56189. * @param condition defines the trigger related conditions
  56190. */
  56191. function ExecuteCodeAction(triggerOptions, func, condition) {
  56192. var _this = _super.call(this, triggerOptions, condition) || this;
  56193. _this.func = func;
  56194. return _this;
  56195. }
  56196. /**
  56197. * Execute the action and run the attached code.
  56198. */
  56199. ExecuteCodeAction.prototype.execute = function (evt) {
  56200. this.func(evt);
  56201. };
  56202. return ExecuteCodeAction;
  56203. }(BABYLON.Action));
  56204. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  56205. /**
  56206. * This defines an action responsible to set the parent property of the target once triggered.
  56207. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  56208. */
  56209. var SetParentAction = /** @class */ (function (_super) {
  56210. __extends(SetParentAction, _super);
  56211. /**
  56212. * Instantiate the action
  56213. * @param triggerOptions defines the trigger options
  56214. * @param target defines the target containing the parent property
  56215. * @param parent defines from where the animation should start (animation frame)
  56216. * @param condition defines the trigger related conditions
  56217. */
  56218. function SetParentAction(triggerOptions, target, parent, condition) {
  56219. var _this = _super.call(this, triggerOptions, condition) || this;
  56220. _this._target = target;
  56221. _this._parent = parent;
  56222. return _this;
  56223. }
  56224. /** @hidden */
  56225. SetParentAction.prototype._prepare = function () {
  56226. };
  56227. /**
  56228. * Execute the action and set the parent property.
  56229. */
  56230. SetParentAction.prototype.execute = function () {
  56231. if (this._target.parent === this._parent) {
  56232. return;
  56233. }
  56234. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  56235. invertParentWorldMatrix.invert();
  56236. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  56237. this._target.parent = this._parent;
  56238. };
  56239. /**
  56240. * Serializes the actions and its related information.
  56241. * @param parent defines the object to serialize in
  56242. * @returns the serialized object
  56243. */
  56244. SetParentAction.prototype.serialize = function (parent) {
  56245. return _super.prototype._serialize.call(this, {
  56246. name: "SetParentAction",
  56247. properties: [
  56248. BABYLON.Action._GetTargetProperty(this._target),
  56249. BABYLON.Action._GetTargetProperty(this._parent),
  56250. ]
  56251. }, parent);
  56252. };
  56253. return SetParentAction;
  56254. }(BABYLON.Action));
  56255. BABYLON.SetParentAction = SetParentAction;
  56256. })(BABYLON || (BABYLON = {}));
  56257. //# sourceMappingURL=babylon.directActions.js.map
  56258. var BABYLON;
  56259. (function (BABYLON) {
  56260. /**
  56261. * Class used to manage multiple sprites on the same spritesheet
  56262. * @see http://doc.babylonjs.com/babylon101/sprites
  56263. */
  56264. var SpriteManager = /** @class */ (function () {
  56265. /**
  56266. * Creates a new sprite manager
  56267. * @param name defines the manager's name
  56268. * @param imgUrl defines the sprite sheet url
  56269. * @param capacity defines the maximum allowed number of sprites
  56270. * @param cellSize defines the size of a sprite cell
  56271. * @param scene defines the hosting scene
  56272. * @param epsilon defines the epsilon value to align texture (0.01 by default)
  56273. * @param samplingMode defines the smapling mode to use with spritesheet
  56274. */
  56275. function SpriteManager(
  56276. /** defines the manager's name */
  56277. name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  56278. if (epsilon === void 0) { epsilon = 0.01; }
  56279. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  56280. this.name = name;
  56281. /** Gets the list of sprites */
  56282. this.sprites = new Array();
  56283. /** Gets or sets the rendering group id (0 by default) */
  56284. this.renderingGroupId = 0;
  56285. /** Gets or sets camera layer mask */
  56286. this.layerMask = 0x0FFFFFFF;
  56287. /** Gets or sets a boolean indicating if the manager must consider scene fog when rendering */
  56288. this.fogEnabled = true;
  56289. /** Gets or sets a boolean indicating if the sprites are pickable */
  56290. this.isPickable = false;
  56291. /**
  56292. * An event triggered when the manager is disposed.
  56293. */
  56294. this.onDisposeObservable = new BABYLON.Observable();
  56295. this._vertexBuffers = {};
  56296. if (!scene._getComponent(BABYLON.SceneComponentConstants.NAME_SPRITE)) {
  56297. scene._addComponent(new BABYLON.SpriteSceneComponent(scene));
  56298. }
  56299. this._capacity = capacity;
  56300. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  56301. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56302. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56303. if (cellSize.width && cellSize.height) {
  56304. this.cellWidth = cellSize.width;
  56305. this.cellHeight = cellSize.height;
  56306. }
  56307. else if (cellSize !== undefined) {
  56308. this.cellWidth = cellSize;
  56309. this.cellHeight = cellSize;
  56310. }
  56311. else {
  56312. return;
  56313. }
  56314. this._epsilon = epsilon;
  56315. this._scene = scene;
  56316. this._scene.spriteManagers.push(this);
  56317. var indices = [];
  56318. var index = 0;
  56319. for (var count = 0; count < capacity; count++) {
  56320. indices.push(index);
  56321. indices.push(index + 1);
  56322. indices.push(index + 2);
  56323. indices.push(index);
  56324. indices.push(index + 2);
  56325. indices.push(index + 3);
  56326. index += 4;
  56327. }
  56328. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  56329. // VBO
  56330. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  56331. this._vertexData = new Float32Array(capacity * 16 * 4);
  56332. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  56333. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  56334. var options = this._buffer.createVertexBuffer("options", 4, 4);
  56335. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  56336. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  56337. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  56338. this._vertexBuffers["options"] = options;
  56339. this._vertexBuffers["cellInfo"] = cellInfo;
  56340. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  56341. // Effects
  56342. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  56343. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  56344. }
  56345. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  56346. /**
  56347. * Callback called when the manager is disposed
  56348. */
  56349. set: function (callback) {
  56350. if (this._onDisposeObserver) {
  56351. this.onDisposeObservable.remove(this._onDisposeObserver);
  56352. }
  56353. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  56354. },
  56355. enumerable: true,
  56356. configurable: true
  56357. });
  56358. Object.defineProperty(SpriteManager.prototype, "texture", {
  56359. /**
  56360. * Gets or sets the spritesheet texture
  56361. */
  56362. get: function () {
  56363. return this._spriteTexture;
  56364. },
  56365. set: function (value) {
  56366. this._spriteTexture = value;
  56367. },
  56368. enumerable: true,
  56369. configurable: true
  56370. });
  56371. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  56372. var arrayOffset = index * 16;
  56373. if (offsetX === 0)
  56374. offsetX = this._epsilon;
  56375. else if (offsetX === 1)
  56376. offsetX = 1 - this._epsilon;
  56377. if (offsetY === 0)
  56378. offsetY = this._epsilon;
  56379. else if (offsetY === 1)
  56380. offsetY = 1 - this._epsilon;
  56381. this._vertexData[arrayOffset] = sprite.position.x;
  56382. this._vertexData[arrayOffset + 1] = sprite.position.y;
  56383. this._vertexData[arrayOffset + 2] = sprite.position.z;
  56384. this._vertexData[arrayOffset + 3] = sprite.angle;
  56385. this._vertexData[arrayOffset + 4] = sprite.width;
  56386. this._vertexData[arrayOffset + 5] = sprite.height;
  56387. this._vertexData[arrayOffset + 6] = offsetX;
  56388. this._vertexData[arrayOffset + 7] = offsetY;
  56389. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  56390. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  56391. var offset = (sprite.cellIndex / rowSize) >> 0;
  56392. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  56393. this._vertexData[arrayOffset + 11] = offset;
  56394. // Color
  56395. this._vertexData[arrayOffset + 12] = sprite.color.r;
  56396. this._vertexData[arrayOffset + 13] = sprite.color.g;
  56397. this._vertexData[arrayOffset + 14] = sprite.color.b;
  56398. this._vertexData[arrayOffset + 15] = sprite.color.a;
  56399. };
  56400. /**
  56401. * Intersects the sprites with a ray
  56402. * @param ray defines the ray to intersect with
  56403. * @param camera defines the current active camera
  56404. * @param predicate defines a predicate used to select candidate sprites
  56405. * @param fastCheck defines if a fast check only must be done (the first potential sprite is will be used and not the closer)
  56406. * @returns null if no hit or a PickingInfo
  56407. */
  56408. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  56409. var count = Math.min(this._capacity, this.sprites.length);
  56410. var min = BABYLON.Vector3.Zero();
  56411. var max = BABYLON.Vector3.Zero();
  56412. var distance = Number.MAX_VALUE;
  56413. var currentSprite = null;
  56414. var cameraSpacePosition = BABYLON.Vector3.Zero();
  56415. var cameraView = camera.getViewMatrix();
  56416. for (var index = 0; index < count; index++) {
  56417. var sprite = this.sprites[index];
  56418. if (!sprite) {
  56419. continue;
  56420. }
  56421. if (predicate) {
  56422. if (!predicate(sprite)) {
  56423. continue;
  56424. }
  56425. }
  56426. else if (!sprite.isPickable) {
  56427. continue;
  56428. }
  56429. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  56430. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  56431. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  56432. if (ray.intersectsBoxMinMax(min, max)) {
  56433. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  56434. if (distance > currentDistance) {
  56435. distance = currentDistance;
  56436. currentSprite = sprite;
  56437. if (fastCheck) {
  56438. break;
  56439. }
  56440. }
  56441. }
  56442. }
  56443. if (currentSprite) {
  56444. var result = new BABYLON.PickingInfo();
  56445. result.hit = true;
  56446. result.pickedSprite = currentSprite;
  56447. result.distance = distance;
  56448. return result;
  56449. }
  56450. return null;
  56451. };
  56452. /**
  56453. * Render all child sprites
  56454. */
  56455. SpriteManager.prototype.render = function () {
  56456. // Check
  56457. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  56458. return;
  56459. var engine = this._scene.getEngine();
  56460. var baseSize = this._spriteTexture.getBaseSize();
  56461. // Sprites
  56462. var deltaTime = engine.getDeltaTime();
  56463. var max = Math.min(this._capacity, this.sprites.length);
  56464. var rowSize = baseSize.width / this.cellWidth;
  56465. var offset = 0;
  56466. for (var index = 0; index < max; index++) {
  56467. var sprite = this.sprites[index];
  56468. if (!sprite || !sprite.isVisible) {
  56469. continue;
  56470. }
  56471. sprite._animate(deltaTime);
  56472. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  56473. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  56474. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  56475. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  56476. }
  56477. this._buffer.update(this._vertexData);
  56478. // Render
  56479. var effect = this._effectBase;
  56480. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  56481. effect = this._effectFog;
  56482. }
  56483. engine.enableEffect(effect);
  56484. var viewMatrix = this._scene.getViewMatrix();
  56485. effect.setTexture("diffuseSampler", this._spriteTexture);
  56486. effect.setMatrix("view", viewMatrix);
  56487. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  56488. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  56489. // Fog
  56490. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  56491. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  56492. effect.setColor3("vFogColor", this._scene.fogColor);
  56493. }
  56494. // VBOs
  56495. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  56496. // Draw order
  56497. engine.setDepthFunctionToLessOrEqual();
  56498. effect.setBool("alphaTest", true);
  56499. engine.setColorWrite(false);
  56500. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  56501. engine.setColorWrite(true);
  56502. effect.setBool("alphaTest", false);
  56503. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  56504. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  56505. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  56506. };
  56507. /**
  56508. * Release associated resources
  56509. */
  56510. SpriteManager.prototype.dispose = function () {
  56511. if (this._buffer) {
  56512. this._buffer.dispose();
  56513. this._buffer = null;
  56514. }
  56515. if (this._indexBuffer) {
  56516. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  56517. this._indexBuffer = null;
  56518. }
  56519. if (this._spriteTexture) {
  56520. this._spriteTexture.dispose();
  56521. this._spriteTexture = null;
  56522. }
  56523. // Remove from scene
  56524. var index = this._scene.spriteManagers.indexOf(this);
  56525. this._scene.spriteManagers.splice(index, 1);
  56526. // Callback
  56527. this.onDisposeObservable.notifyObservers(this);
  56528. this.onDisposeObservable.clear();
  56529. };
  56530. return SpriteManager;
  56531. }());
  56532. BABYLON.SpriteManager = SpriteManager;
  56533. })(BABYLON || (BABYLON = {}));
  56534. //# sourceMappingURL=babylon.spriteManager.js.map
  56535. var BABYLON;
  56536. (function (BABYLON) {
  56537. /**
  56538. * Class used to represent a sprite
  56539. * @see http://doc.babylonjs.com/babylon101/sprites
  56540. */
  56541. var Sprite = /** @class */ (function () {
  56542. /**
  56543. * Creates a new Sprite
  56544. * @param name defines the name
  56545. * @param manager defines the manager
  56546. */
  56547. function Sprite(
  56548. /** defines the name */
  56549. name, manager) {
  56550. this.name = name;
  56551. /** Gets or sets the main color */
  56552. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56553. /** Gets or sets the width */
  56554. this.width = 1.0;
  56555. /** Gets or sets the height */
  56556. this.height = 1.0;
  56557. /** Gets or sets rotation angle */
  56558. this.angle = 0;
  56559. /** Gets or sets the cell index in the sprite sheet */
  56560. this.cellIndex = 0;
  56561. /** Gets or sets a boolean indicating if UV coordinates should be inverted in U axis */
  56562. this.invertU = 0;
  56563. /** Gets or sets a boolean indicating if UV coordinates should be inverted in B axis */
  56564. this.invertV = 0;
  56565. /** Gets the list of attached animations */
  56566. this.animations = new Array();
  56567. /** Gets or sets a boolean indicating if the sprite can be picked */
  56568. this.isPickable = false;
  56569. this._animationStarted = false;
  56570. this._loopAnimation = false;
  56571. this._fromIndex = 0;
  56572. this._toIndex = 0;
  56573. this._delay = 0;
  56574. this._direction = 1;
  56575. this._time = 0;
  56576. /**
  56577. * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true
  56578. */
  56579. this.isVisible = true;
  56580. this._manager = manager;
  56581. this._manager.sprites.push(this);
  56582. this.position = BABYLON.Vector3.Zero();
  56583. }
  56584. Object.defineProperty(Sprite.prototype, "size", {
  56585. /**
  56586. * Gets or sets the sprite size
  56587. */
  56588. get: function () {
  56589. return this.width;
  56590. },
  56591. set: function (value) {
  56592. this.width = value;
  56593. this.height = value;
  56594. },
  56595. enumerable: true,
  56596. configurable: true
  56597. });
  56598. /**
  56599. * Starts an animation
  56600. * @param from defines the initial key
  56601. * @param to defines the end key
  56602. * @param loop defines if the animation must loop
  56603. * @param delay defines the start delay (in ms)
  56604. * @param onAnimationEnd defines a callback to call when animation ends
  56605. */
  56606. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  56607. this._fromIndex = from;
  56608. this._toIndex = to;
  56609. this._loopAnimation = loop;
  56610. this._delay = delay;
  56611. this._animationStarted = true;
  56612. this._direction = from < to ? 1 : -1;
  56613. this.cellIndex = from;
  56614. this._time = 0;
  56615. this._onAnimationEnd = onAnimationEnd;
  56616. };
  56617. /** Stops current animation (if any) */
  56618. Sprite.prototype.stopAnimation = function () {
  56619. this._animationStarted = false;
  56620. };
  56621. /** @hidden */
  56622. Sprite.prototype._animate = function (deltaTime) {
  56623. if (!this._animationStarted)
  56624. return;
  56625. this._time += deltaTime;
  56626. if (this._time > this._delay) {
  56627. this._time = this._time % this._delay;
  56628. this.cellIndex += this._direction;
  56629. if (this.cellIndex > this._toIndex) {
  56630. if (this._loopAnimation) {
  56631. this.cellIndex = this._fromIndex;
  56632. }
  56633. else {
  56634. this.cellIndex = this._toIndex;
  56635. this._animationStarted = false;
  56636. if (this._onAnimationEnd) {
  56637. this._onAnimationEnd();
  56638. }
  56639. if (this.disposeWhenFinishedAnimating) {
  56640. this.dispose();
  56641. }
  56642. }
  56643. }
  56644. }
  56645. };
  56646. /** Release associated resources */
  56647. Sprite.prototype.dispose = function () {
  56648. for (var i = 0; i < this._manager.sprites.length; i++) {
  56649. if (this._manager.sprites[i] == this) {
  56650. this._manager.sprites.splice(i, 1);
  56651. }
  56652. }
  56653. };
  56654. return Sprite;
  56655. }());
  56656. BABYLON.Sprite = Sprite;
  56657. })(BABYLON || (BABYLON = {}));
  56658. //# sourceMappingURL=babylon.sprite.js.map
  56659. var BABYLON;
  56660. (function (BABYLON) {
  56661. BABYLON.Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  56662. if (!BABYLON.PickingInfo) {
  56663. return null;
  56664. }
  56665. var pickingInfo = null;
  56666. if (!camera) {
  56667. if (!this.activeCamera) {
  56668. return null;
  56669. }
  56670. camera = this.activeCamera;
  56671. }
  56672. if (this.spriteManagers.length > 0) {
  56673. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  56674. var spriteManager = this.spriteManagers[spriteIndex];
  56675. if (!spriteManager.isPickable) {
  56676. continue;
  56677. }
  56678. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  56679. if (!result || !result.hit)
  56680. continue;
  56681. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  56682. continue;
  56683. pickingInfo = result;
  56684. if (fastCheck) {
  56685. break;
  56686. }
  56687. }
  56688. }
  56689. return pickingInfo || new BABYLON.PickingInfo();
  56690. };
  56691. BABYLON.Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  56692. this.createPickingRayInCameraSpaceToRef(x, y, this._tempSpritePickingRay, camera);
  56693. return this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera);
  56694. };
  56695. BABYLON.Scene.prototype.pickSpriteWithRay = function (ray, predicate, fastCheck, camera) {
  56696. if (!this._tempSpritePickingRay) {
  56697. return null;
  56698. }
  56699. if (!camera) {
  56700. if (!this.activeCamera) {
  56701. return null;
  56702. }
  56703. camera = this.activeCamera;
  56704. }
  56705. BABYLON.Ray.TransformToRef(ray, camera.getViewMatrix(), this._tempSpritePickingRay);
  56706. return this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera);
  56707. };
  56708. BABYLON.Scene.prototype.setPointerOverSprite = function (sprite) {
  56709. if (this._pointerOverSprite === sprite) {
  56710. return;
  56711. }
  56712. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  56713. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  56714. }
  56715. this._pointerOverSprite = sprite;
  56716. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  56717. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  56718. }
  56719. };
  56720. BABYLON.Scene.prototype.getPointerOverSprite = function () {
  56721. return this._pointerOverSprite;
  56722. };
  56723. /**
  56724. * Defines the sprite scene component responsible to manage sprites
  56725. * in a given scene.
  56726. */
  56727. var SpriteSceneComponent = /** @class */ (function () {
  56728. /**
  56729. * Creates a new instance of the component for the given scene
  56730. * @param scene Defines the scene to register the component in
  56731. */
  56732. function SpriteSceneComponent(scene) {
  56733. /**
  56734. * The component name helpfull to identify the component in the list of scene components.
  56735. */
  56736. this.name = BABYLON.SceneComponentConstants.NAME_SPRITE;
  56737. this.scene = scene;
  56738. this.scene.spriteManagers = new Array();
  56739. this.scene._tempSpritePickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  56740. this.scene.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  56741. this.scene.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  56742. this._spritePredicate = function (sprite) {
  56743. if (!sprite.actionManager) {
  56744. return false;
  56745. }
  56746. return sprite.isPickable && sprite.actionManager.hasPointerTriggers;
  56747. };
  56748. }
  56749. /**
  56750. * Registers the component in a given scene
  56751. */
  56752. SpriteSceneComponent.prototype.register = function () {
  56753. this.scene._pointerMoveStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERMOVE_SPRITE, this, this._pointerMove);
  56754. this.scene._pointerDownStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERDOWN_SPRITE, this, this._pointerDown);
  56755. this.scene._pointerUpStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERUP_SPRITE, this, this._pointerUp);
  56756. };
  56757. /**
  56758. * Rebuilds the elements related to this component in case of
  56759. * context lost for instance.
  56760. */
  56761. SpriteSceneComponent.prototype.rebuild = function () {
  56762. /** Nothing to do for sprites */
  56763. };
  56764. /**
  56765. * Disposes the component and the associated ressources.
  56766. */
  56767. SpriteSceneComponent.prototype.dispose = function () {
  56768. this.scene.onBeforeSpritesRenderingObservable.clear();
  56769. this.scene.onAfterSpritesRenderingObservable.clear();
  56770. var spriteManagers = this.scene.spriteManagers;
  56771. while (spriteManagers.length) {
  56772. spriteManagers[0].dispose();
  56773. }
  56774. };
  56775. SpriteSceneComponent.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, fastCheck, camera) {
  56776. var result = this.scene.pickSprite(x, y, this._spritePredicate, fastCheck, camera);
  56777. if (result) {
  56778. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  56779. }
  56780. return result;
  56781. };
  56782. SpriteSceneComponent.prototype._pointerMove = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, isMeshPicked, canvas) {
  56783. var scene = this.scene;
  56784. if (isMeshPicked) {
  56785. scene.setPointerOverSprite(null);
  56786. }
  56787. else {
  56788. pickResult = this._pickSpriteButKeepRay(pickResult, unTranslatedPointerX, unTranslatedPointerY, false, scene.cameraToUseForPointers || undefined);
  56789. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  56790. scene.setPointerOverSprite(pickResult.pickedSprite);
  56791. if (scene._pointerOverSprite && scene._pointerOverSprite.actionManager && scene._pointerOverSprite.actionManager.hoverCursor) {
  56792. canvas.style.cursor = scene._pointerOverSprite.actionManager.hoverCursor;
  56793. }
  56794. else {
  56795. canvas.style.cursor = scene.hoverCursor;
  56796. }
  56797. }
  56798. else {
  56799. scene.setPointerOverSprite(null);
  56800. }
  56801. }
  56802. return pickResult;
  56803. };
  56804. SpriteSceneComponent.prototype._pointerDown = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {
  56805. var scene = this.scene;
  56806. scene._pickedDownSprite = null;
  56807. if (scene.spriteManagers.length > 0) {
  56808. pickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);
  56809. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  56810. if (pickResult.pickedSprite.actionManager) {
  56811. scene._pickedDownSprite = pickResult.pickedSprite;
  56812. switch (evt.button) {
  56813. case 0:
  56814. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  56815. break;
  56816. case 1:
  56817. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  56818. break;
  56819. case 2:
  56820. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  56821. break;
  56822. }
  56823. if (pickResult.pickedSprite.actionManager) {
  56824. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  56825. }
  56826. }
  56827. }
  56828. }
  56829. return pickResult;
  56830. };
  56831. SpriteSceneComponent.prototype._pointerUp = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {
  56832. var scene = this.scene;
  56833. if (scene.spriteManagers.length > 0) {
  56834. var spritePickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);
  56835. if (spritePickResult) {
  56836. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  56837. if (spritePickResult.pickedSprite.actionManager) {
  56838. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
  56839. if (spritePickResult.pickedSprite.actionManager) {
  56840. if (!this.scene._isPointerSwiping()) {
  56841. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
  56842. }
  56843. }
  56844. }
  56845. }
  56846. if (scene._pickedDownSprite && scene._pickedDownSprite.actionManager && scene._pickedDownSprite !== spritePickResult.pickedSprite) {
  56847. scene._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(scene._pickedDownSprite, scene, evt));
  56848. }
  56849. }
  56850. }
  56851. return pickResult;
  56852. };
  56853. return SpriteSceneComponent;
  56854. }());
  56855. BABYLON.SpriteSceneComponent = SpriteSceneComponent;
  56856. })(BABYLON || (BABYLON = {}));
  56857. //# sourceMappingURL=babylon.spriteSceneComponent.js.map
  56858. var BABYLON;
  56859. (function (BABYLON) {
  56860. /**
  56861. * @hidden
  56862. */
  56863. var IntersectionInfo = /** @class */ (function () {
  56864. function IntersectionInfo(bu, bv, distance) {
  56865. this.bu = bu;
  56866. this.bv = bv;
  56867. this.distance = distance;
  56868. this.faceId = 0;
  56869. this.subMeshId = 0;
  56870. }
  56871. return IntersectionInfo;
  56872. }());
  56873. BABYLON.IntersectionInfo = IntersectionInfo;
  56874. /**
  56875. * Information about the result of picking within a scene
  56876. * @see https://doc.babylonjs.com/babylon101/picking_collisions
  56877. */
  56878. var PickingInfo = /** @class */ (function () {
  56879. function PickingInfo() {
  56880. /**
  56881. * If the pick collided with an object
  56882. */
  56883. this.hit = false;
  56884. /**
  56885. * Distance away where the pick collided
  56886. */
  56887. this.distance = 0;
  56888. /**
  56889. * The location of pick collision
  56890. */
  56891. this.pickedPoint = null;
  56892. /**
  56893. * The mesh corresponding the the pick collision
  56894. */
  56895. this.pickedMesh = null;
  56896. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  56897. this.bu = 0;
  56898. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  56899. this.bv = 0;
  56900. /** The id of the face on the mesh that was picked */
  56901. this.faceId = -1;
  56902. /** Id of the the submesh that was picked */
  56903. this.subMeshId = 0;
  56904. /** If a sprite was picked, this will be the sprite the pick collided with */
  56905. this.pickedSprite = null;
  56906. /**
  56907. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  56908. */
  56909. this.originMesh = null;
  56910. /**
  56911. * The ray that was used to perform the picking.
  56912. */
  56913. this.ray = null;
  56914. }
  56915. /**
  56916. * Gets the normal correspodning to the face the pick collided with
  56917. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  56918. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  56919. * @returns The normal correspodning to the face the pick collided with
  56920. */
  56921. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  56922. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  56923. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  56924. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  56925. return null;
  56926. }
  56927. var indices = this.pickedMesh.getIndices();
  56928. if (!indices) {
  56929. return null;
  56930. }
  56931. var result;
  56932. if (useVerticesNormals) {
  56933. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  56934. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  56935. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  56936. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  56937. normal0 = normal0.scale(this.bu);
  56938. normal1 = normal1.scale(this.bv);
  56939. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  56940. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  56941. }
  56942. else {
  56943. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  56944. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  56945. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  56946. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  56947. var p1p2 = vertex1.subtract(vertex2);
  56948. var p3p2 = vertex3.subtract(vertex2);
  56949. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  56950. }
  56951. if (useWorldCoordinates) {
  56952. var wm = this.pickedMesh.getWorldMatrix();
  56953. if (this.pickedMesh.nonUniformScaling) {
  56954. BABYLON.Tmp.Matrix[0].copyFrom(wm);
  56955. wm = BABYLON.Tmp.Matrix[0];
  56956. wm.setTranslationFromFloats(0, 0, 0);
  56957. wm.invert();
  56958. wm.transposeToRef(BABYLON.Tmp.Matrix[1]);
  56959. wm = BABYLON.Tmp.Matrix[1];
  56960. }
  56961. result = BABYLON.Vector3.TransformNormal(result, wm);
  56962. }
  56963. result.normalize();
  56964. return result;
  56965. };
  56966. /**
  56967. * Gets the texture coordinates of where the pick occured
  56968. * @returns the vector containing the coordnates of the texture
  56969. */
  56970. PickingInfo.prototype.getTextureCoordinates = function () {
  56971. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  56972. return null;
  56973. }
  56974. var indices = this.pickedMesh.getIndices();
  56975. if (!indices) {
  56976. return null;
  56977. }
  56978. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  56979. if (!uvs) {
  56980. return null;
  56981. }
  56982. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  56983. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  56984. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  56985. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  56986. uv1 = uv1.scale(this.bu);
  56987. uv2 = uv2.scale(this.bv);
  56988. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  56989. };
  56990. return PickingInfo;
  56991. }());
  56992. BABYLON.PickingInfo = PickingInfo;
  56993. })(BABYLON || (BABYLON = {}));
  56994. //# sourceMappingURL=babylon.pickingInfo.js.map
  56995. var BABYLON;
  56996. (function (BABYLON) {
  56997. /**
  56998. * Class representing a ray with position and direction
  56999. */
  57000. var Ray = /** @class */ (function () {
  57001. /**
  57002. * Creates a new ray
  57003. * @param origin origin point
  57004. * @param direction direction
  57005. * @param length length of the ray
  57006. */
  57007. function Ray(
  57008. /** origin point */
  57009. origin,
  57010. /** direction */
  57011. direction,
  57012. /** length of the ray */
  57013. length) {
  57014. if (length === void 0) { length = Number.MAX_VALUE; }
  57015. this.origin = origin;
  57016. this.direction = direction;
  57017. this.length = length;
  57018. }
  57019. // Methods
  57020. /**
  57021. * Checks if the ray intersects a box
  57022. * @param minimum bound of the box
  57023. * @param maximum bound of the box
  57024. * @returns if the box was hit
  57025. */
  57026. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  57027. var d = 0.0;
  57028. var maxValue = Number.MAX_VALUE;
  57029. var inv;
  57030. var min;
  57031. var max;
  57032. var temp;
  57033. if (Math.abs(this.direction.x) < 0.0000001) {
  57034. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  57035. return false;
  57036. }
  57037. }
  57038. else {
  57039. inv = 1.0 / this.direction.x;
  57040. min = (minimum.x - this.origin.x) * inv;
  57041. max = (maximum.x - this.origin.x) * inv;
  57042. if (max === -Infinity) {
  57043. max = Infinity;
  57044. }
  57045. if (min > max) {
  57046. temp = min;
  57047. min = max;
  57048. max = temp;
  57049. }
  57050. d = Math.max(min, d);
  57051. maxValue = Math.min(max, maxValue);
  57052. if (d > maxValue) {
  57053. return false;
  57054. }
  57055. }
  57056. if (Math.abs(this.direction.y) < 0.0000001) {
  57057. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  57058. return false;
  57059. }
  57060. }
  57061. else {
  57062. inv = 1.0 / this.direction.y;
  57063. min = (minimum.y - this.origin.y) * inv;
  57064. max = (maximum.y - this.origin.y) * inv;
  57065. if (max === -Infinity) {
  57066. max = Infinity;
  57067. }
  57068. if (min > max) {
  57069. temp = min;
  57070. min = max;
  57071. max = temp;
  57072. }
  57073. d = Math.max(min, d);
  57074. maxValue = Math.min(max, maxValue);
  57075. if (d > maxValue) {
  57076. return false;
  57077. }
  57078. }
  57079. if (Math.abs(this.direction.z) < 0.0000001) {
  57080. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  57081. return false;
  57082. }
  57083. }
  57084. else {
  57085. inv = 1.0 / this.direction.z;
  57086. min = (minimum.z - this.origin.z) * inv;
  57087. max = (maximum.z - this.origin.z) * inv;
  57088. if (max === -Infinity) {
  57089. max = Infinity;
  57090. }
  57091. if (min > max) {
  57092. temp = min;
  57093. min = max;
  57094. max = temp;
  57095. }
  57096. d = Math.max(min, d);
  57097. maxValue = Math.min(max, maxValue);
  57098. if (d > maxValue) {
  57099. return false;
  57100. }
  57101. }
  57102. return true;
  57103. };
  57104. /**
  57105. * Checks if the ray intersects a box
  57106. * @param box the bounding box to check
  57107. * @returns if the box was hit
  57108. */
  57109. Ray.prototype.intersectsBox = function (box) {
  57110. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  57111. };
  57112. /**
  57113. * If the ray hits a sphere
  57114. * @param sphere the bounding sphere to check
  57115. * @returns true if it hits the sphere
  57116. */
  57117. Ray.prototype.intersectsSphere = function (sphere) {
  57118. var x = sphere.center.x - this.origin.x;
  57119. var y = sphere.center.y - this.origin.y;
  57120. var z = sphere.center.z - this.origin.z;
  57121. var pyth = (x * x) + (y * y) + (z * z);
  57122. var rr = sphere.radius * sphere.radius;
  57123. if (pyth <= rr) {
  57124. return true;
  57125. }
  57126. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  57127. if (dot < 0.0) {
  57128. return false;
  57129. }
  57130. var temp = pyth - (dot * dot);
  57131. return temp <= rr;
  57132. };
  57133. /**
  57134. * If the ray hits a triange
  57135. * @param vertex0 triangle vertex
  57136. * @param vertex1 triangle vertex
  57137. * @param vertex2 triangle vertex
  57138. * @returns intersection information if hit
  57139. */
  57140. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  57141. if (!this._edge1) {
  57142. this._edge1 = BABYLON.Vector3.Zero();
  57143. this._edge2 = BABYLON.Vector3.Zero();
  57144. this._pvec = BABYLON.Vector3.Zero();
  57145. this._tvec = BABYLON.Vector3.Zero();
  57146. this._qvec = BABYLON.Vector3.Zero();
  57147. }
  57148. vertex1.subtractToRef(vertex0, this._edge1);
  57149. vertex2.subtractToRef(vertex0, this._edge2);
  57150. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  57151. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  57152. if (det === 0) {
  57153. return null;
  57154. }
  57155. var invdet = 1 / det;
  57156. this.origin.subtractToRef(vertex0, this._tvec);
  57157. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  57158. if (bu < 0 || bu > 1.0) {
  57159. return null;
  57160. }
  57161. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  57162. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  57163. if (bv < 0 || bu + bv > 1.0) {
  57164. return null;
  57165. }
  57166. //check if the distance is longer than the predefined length.
  57167. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  57168. if (distance > this.length) {
  57169. return null;
  57170. }
  57171. return new BABYLON.IntersectionInfo(bu, bv, distance);
  57172. };
  57173. /**
  57174. * Checks if ray intersects a plane
  57175. * @param plane the plane to check
  57176. * @returns the distance away it was hit
  57177. */
  57178. Ray.prototype.intersectsPlane = function (plane) {
  57179. var distance;
  57180. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  57181. if (Math.abs(result1) < 9.99999997475243E-07) {
  57182. return null;
  57183. }
  57184. else {
  57185. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  57186. distance = (-plane.d - result2) / result1;
  57187. if (distance < 0.0) {
  57188. if (distance < -9.99999997475243E-07) {
  57189. return null;
  57190. }
  57191. else {
  57192. return 0;
  57193. }
  57194. }
  57195. return distance;
  57196. }
  57197. };
  57198. /**
  57199. * Checks if ray intersects a mesh
  57200. * @param mesh the mesh to check
  57201. * @param fastCheck if only the bounding box should checked
  57202. * @returns picking info of the intersecton
  57203. */
  57204. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  57205. var tm = BABYLON.Tmp.Matrix[0];
  57206. mesh.getWorldMatrix().invertToRef(tm);
  57207. if (this._tmpRay) {
  57208. Ray.TransformToRef(this, tm, this._tmpRay);
  57209. }
  57210. else {
  57211. this._tmpRay = Ray.Transform(this, tm);
  57212. }
  57213. return mesh.intersects(this._tmpRay, fastCheck);
  57214. };
  57215. /**
  57216. * Checks if ray intersects a mesh
  57217. * @param meshes the meshes to check
  57218. * @param fastCheck if only the bounding box should checked
  57219. * @param results array to store result in
  57220. * @returns Array of picking infos
  57221. */
  57222. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  57223. if (results) {
  57224. results.length = 0;
  57225. }
  57226. else {
  57227. results = [];
  57228. }
  57229. for (var i = 0; i < meshes.length; i++) {
  57230. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  57231. if (pickInfo.hit) {
  57232. results.push(pickInfo);
  57233. }
  57234. }
  57235. results.sort(this._comparePickingInfo);
  57236. return results;
  57237. };
  57238. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  57239. if (pickingInfoA.distance < pickingInfoB.distance) {
  57240. return -1;
  57241. }
  57242. else if (pickingInfoA.distance > pickingInfoB.distance) {
  57243. return 1;
  57244. }
  57245. else {
  57246. return 0;
  57247. }
  57248. };
  57249. /**
  57250. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  57251. * @param sega the first point of the segment to test the intersection against
  57252. * @param segb the second point of the segment to test the intersection against
  57253. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  57254. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  57255. */
  57256. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  57257. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  57258. var u = segb.subtract(sega);
  57259. var v = rsegb.subtract(this.origin);
  57260. var w = sega.subtract(this.origin);
  57261. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  57262. var b = BABYLON.Vector3.Dot(u, v);
  57263. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  57264. var d = BABYLON.Vector3.Dot(u, w);
  57265. var e = BABYLON.Vector3.Dot(v, w);
  57266. var D = a * c - b * b; // always >= 0
  57267. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  57268. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  57269. // compute the line parameters of the two closest points
  57270. if (D < Ray.smallnum) { // the lines are almost parallel
  57271. sN = 0.0; // force using point P0 on segment S1
  57272. sD = 1.0; // to prevent possible division by 0.0 later
  57273. tN = e;
  57274. tD = c;
  57275. }
  57276. else { // get the closest points on the infinite lines
  57277. sN = (b * e - c * d);
  57278. tN = (a * e - b * d);
  57279. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  57280. sN = 0.0;
  57281. tN = e;
  57282. tD = c;
  57283. }
  57284. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  57285. sN = sD;
  57286. tN = e + b;
  57287. tD = c;
  57288. }
  57289. }
  57290. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  57291. tN = 0.0;
  57292. // recompute sc for this edge
  57293. if (-d < 0.0) {
  57294. sN = 0.0;
  57295. }
  57296. else if (-d > a)
  57297. sN = sD;
  57298. else {
  57299. sN = -d;
  57300. sD = a;
  57301. }
  57302. }
  57303. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  57304. tN = tD;
  57305. // recompute sc for this edge
  57306. if ((-d + b) < 0.0) {
  57307. sN = 0;
  57308. }
  57309. else if ((-d + b) > a) {
  57310. sN = sD;
  57311. }
  57312. else {
  57313. sN = (-d + b);
  57314. sD = a;
  57315. }
  57316. }
  57317. // finally do the division to get sc and tc
  57318. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  57319. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  57320. // get the difference of the two closest points
  57321. var qtc = v.multiplyByFloats(tc, tc, tc);
  57322. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  57323. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  57324. if (isIntersected) {
  57325. return qtc.length();
  57326. }
  57327. return -1;
  57328. };
  57329. /**
  57330. * Update the ray from viewport position
  57331. * @param x position
  57332. * @param y y position
  57333. * @param viewportWidth viewport width
  57334. * @param viewportHeight viewport height
  57335. * @param world world matrix
  57336. * @param view view matrix
  57337. * @param projection projection matrix
  57338. * @returns this ray updated
  57339. */
  57340. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  57341. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  57342. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  57343. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  57344. this.direction.normalize();
  57345. return this;
  57346. };
  57347. // Statics
  57348. /**
  57349. * Creates a ray with origin and direction of 0,0,0
  57350. * @returns the new ray
  57351. */
  57352. Ray.Zero = function () {
  57353. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  57354. };
  57355. /**
  57356. * Creates a new ray from screen space and viewport
  57357. * @param x position
  57358. * @param y y position
  57359. * @param viewportWidth viewport width
  57360. * @param viewportHeight viewport height
  57361. * @param world world matrix
  57362. * @param view view matrix
  57363. * @param projection projection matrix
  57364. * @returns new ray
  57365. */
  57366. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  57367. var result = Ray.Zero();
  57368. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  57369. };
  57370. /**
  57371. * 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
  57372. * transformed to the given world matrix.
  57373. * @param origin The origin point
  57374. * @param end The end point
  57375. * @param world a matrix to transform the ray to. Default is the identity matrix.
  57376. * @returns the new ray
  57377. */
  57378. Ray.CreateNewFromTo = function (origin, end, world) {
  57379. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  57380. var direction = end.subtract(origin);
  57381. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  57382. direction.normalize();
  57383. return Ray.Transform(new Ray(origin, direction, length), world);
  57384. };
  57385. /**
  57386. * Transforms a ray by a matrix
  57387. * @param ray ray to transform
  57388. * @param matrix matrix to apply
  57389. * @returns the resulting new ray
  57390. */
  57391. Ray.Transform = function (ray, matrix) {
  57392. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  57393. Ray.TransformToRef(ray, matrix, result);
  57394. return result;
  57395. };
  57396. /**
  57397. * Transforms a ray by a matrix
  57398. * @param ray ray to transform
  57399. * @param matrix matrix to apply
  57400. * @param result ray to store result in
  57401. */
  57402. Ray.TransformToRef = function (ray, matrix, result) {
  57403. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  57404. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  57405. result.length = ray.length;
  57406. var dir = result.direction;
  57407. var len = dir.length();
  57408. if (!(len === 0 || len === 1)) {
  57409. var num = 1.0 / len;
  57410. dir.x *= num;
  57411. dir.y *= num;
  57412. dir.z *= num;
  57413. result.length *= len;
  57414. }
  57415. };
  57416. Ray.smallnum = 0.00000001;
  57417. Ray.rayl = 10e8;
  57418. return Ray;
  57419. }());
  57420. BABYLON.Ray = Ray;
  57421. })(BABYLON || (BABYLON = {}));
  57422. //# sourceMappingURL=babylon.ray.js.map
  57423. var BABYLON;
  57424. (function (BABYLON) {
  57425. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  57426. if (boxMin.x > sphereCenter.x + sphereRadius)
  57427. return false;
  57428. if (sphereCenter.x - sphereRadius > boxMax.x)
  57429. return false;
  57430. if (boxMin.y > sphereCenter.y + sphereRadius)
  57431. return false;
  57432. if (sphereCenter.y - sphereRadius > boxMax.y)
  57433. return false;
  57434. if (boxMin.z > sphereCenter.z + sphereRadius)
  57435. return false;
  57436. if (sphereCenter.z - sphereRadius > boxMax.z)
  57437. return false;
  57438. return true;
  57439. };
  57440. var getLowestRoot = (function () {
  57441. var result = { root: 0, found: false };
  57442. return function (a, b, c, maxR) {
  57443. result.root = 0;
  57444. result.found = false;
  57445. var determinant = b * b - 4.0 * a * c;
  57446. if (determinant < 0)
  57447. return result;
  57448. var sqrtD = Math.sqrt(determinant);
  57449. var r1 = (-b - sqrtD) / (2.0 * a);
  57450. var r2 = (-b + sqrtD) / (2.0 * a);
  57451. if (r1 > r2) {
  57452. var temp = r2;
  57453. r2 = r1;
  57454. r1 = temp;
  57455. }
  57456. if (r1 > 0 && r1 < maxR) {
  57457. result.root = r1;
  57458. result.found = true;
  57459. return result;
  57460. }
  57461. if (r2 > 0 && r2 < maxR) {
  57462. result.root = r2;
  57463. result.found = true;
  57464. return result;
  57465. }
  57466. return result;
  57467. };
  57468. })();
  57469. /** @hidden */
  57470. var Collider = /** @class */ (function () {
  57471. function Collider() {
  57472. this._collisionPoint = BABYLON.Vector3.Zero();
  57473. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  57474. this._tempVector = BABYLON.Vector3.Zero();
  57475. this._tempVector2 = BABYLON.Vector3.Zero();
  57476. this._tempVector3 = BABYLON.Vector3.Zero();
  57477. this._tempVector4 = BABYLON.Vector3.Zero();
  57478. this._edge = BABYLON.Vector3.Zero();
  57479. this._baseToVertex = BABYLON.Vector3.Zero();
  57480. this._destinationPoint = BABYLON.Vector3.Zero();
  57481. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  57482. this._displacementVector = BABYLON.Vector3.Zero();
  57483. /** @hidden */
  57484. this._radius = BABYLON.Vector3.One();
  57485. /** @hidden */
  57486. this._retry = 0;
  57487. /** @hidden */
  57488. this._basePointWorld = BABYLON.Vector3.Zero();
  57489. this._velocityWorld = BABYLON.Vector3.Zero();
  57490. this._normalizedVelocity = BABYLON.Vector3.Zero();
  57491. this._collisionMask = -1;
  57492. }
  57493. Object.defineProperty(Collider.prototype, "collisionMask", {
  57494. get: function () {
  57495. return this._collisionMask;
  57496. },
  57497. set: function (mask) {
  57498. this._collisionMask = !isNaN(mask) ? mask : -1;
  57499. },
  57500. enumerable: true,
  57501. configurable: true
  57502. });
  57503. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  57504. /**
  57505. * Gets the plane normal used to compute the sliding response (in local space)
  57506. */
  57507. get: function () {
  57508. return this._slidePlaneNormal;
  57509. },
  57510. enumerable: true,
  57511. configurable: true
  57512. });
  57513. // Methods
  57514. /** @hidden */
  57515. Collider.prototype._initialize = function (source, dir, e) {
  57516. this._velocity = dir;
  57517. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  57518. this._basePoint = source;
  57519. source.multiplyToRef(this._radius, this._basePointWorld);
  57520. dir.multiplyToRef(this._radius, this._velocityWorld);
  57521. this._velocityWorldLength = this._velocityWorld.length();
  57522. this._epsilon = e;
  57523. this.collisionFound = false;
  57524. };
  57525. /** @hidden */
  57526. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  57527. pa.subtractToRef(point, this._tempVector);
  57528. pb.subtractToRef(point, this._tempVector2);
  57529. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  57530. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  57531. if (d < 0)
  57532. return false;
  57533. pc.subtractToRef(point, this._tempVector3);
  57534. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  57535. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  57536. if (d < 0)
  57537. return false;
  57538. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  57539. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  57540. return d >= 0;
  57541. };
  57542. /** @hidden */
  57543. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  57544. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  57545. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  57546. if (distance > this._velocityWorldLength + max + sphereRadius) {
  57547. return false;
  57548. }
  57549. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  57550. return false;
  57551. return true;
  57552. };
  57553. /** @hidden */
  57554. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  57555. var t0;
  57556. var embeddedInPlane = false;
  57557. //defensive programming, actually not needed.
  57558. if (!trianglePlaneArray) {
  57559. trianglePlaneArray = [];
  57560. }
  57561. if (!trianglePlaneArray[faceIndex]) {
  57562. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  57563. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  57564. }
  57565. var trianglePlane = trianglePlaneArray[faceIndex];
  57566. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  57567. return;
  57568. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  57569. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  57570. if (normalDotVelocity == 0) {
  57571. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  57572. return;
  57573. embeddedInPlane = true;
  57574. t0 = 0;
  57575. }
  57576. else {
  57577. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  57578. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  57579. if (t0 > t1) {
  57580. var temp = t1;
  57581. t1 = t0;
  57582. t0 = temp;
  57583. }
  57584. if (t0 > 1.0 || t1 < 0.0)
  57585. return;
  57586. if (t0 < 0)
  57587. t0 = 0;
  57588. if (t0 > 1.0)
  57589. t0 = 1.0;
  57590. }
  57591. this._collisionPoint.copyFromFloats(0, 0, 0);
  57592. var found = false;
  57593. var t = 1.0;
  57594. if (!embeddedInPlane) {
  57595. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  57596. this._velocity.scaleToRef(t0, this._tempVector);
  57597. this._planeIntersectionPoint.addInPlace(this._tempVector);
  57598. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  57599. found = true;
  57600. t = t0;
  57601. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  57602. }
  57603. }
  57604. if (!found) {
  57605. var velocitySquaredLength = this._velocity.lengthSquared();
  57606. var a = velocitySquaredLength;
  57607. this._basePoint.subtractToRef(p1, this._tempVector);
  57608. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  57609. var c = this._tempVector.lengthSquared() - 1.0;
  57610. var lowestRoot = getLowestRoot(a, b, c, t);
  57611. if (lowestRoot.found) {
  57612. t = lowestRoot.root;
  57613. found = true;
  57614. this._collisionPoint.copyFrom(p1);
  57615. }
  57616. this._basePoint.subtractToRef(p2, this._tempVector);
  57617. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  57618. c = this._tempVector.lengthSquared() - 1.0;
  57619. lowestRoot = getLowestRoot(a, b, c, t);
  57620. if (lowestRoot.found) {
  57621. t = lowestRoot.root;
  57622. found = true;
  57623. this._collisionPoint.copyFrom(p2);
  57624. }
  57625. this._basePoint.subtractToRef(p3, this._tempVector);
  57626. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  57627. c = this._tempVector.lengthSquared() - 1.0;
  57628. lowestRoot = getLowestRoot(a, b, c, t);
  57629. if (lowestRoot.found) {
  57630. t = lowestRoot.root;
  57631. found = true;
  57632. this._collisionPoint.copyFrom(p3);
  57633. }
  57634. p2.subtractToRef(p1, this._edge);
  57635. p1.subtractToRef(this._basePoint, this._baseToVertex);
  57636. var edgeSquaredLength = this._edge.lengthSquared();
  57637. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  57638. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  57639. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  57640. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  57641. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  57642. lowestRoot = getLowestRoot(a, b, c, t);
  57643. if (lowestRoot.found) {
  57644. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  57645. if (f >= 0.0 && f <= 1.0) {
  57646. t = lowestRoot.root;
  57647. found = true;
  57648. this._edge.scaleInPlace(f);
  57649. p1.addToRef(this._edge, this._collisionPoint);
  57650. }
  57651. }
  57652. p3.subtractToRef(p2, this._edge);
  57653. p2.subtractToRef(this._basePoint, this._baseToVertex);
  57654. edgeSquaredLength = this._edge.lengthSquared();
  57655. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  57656. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  57657. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  57658. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  57659. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  57660. lowestRoot = getLowestRoot(a, b, c, t);
  57661. if (lowestRoot.found) {
  57662. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  57663. if (f >= 0.0 && f <= 1.0) {
  57664. t = lowestRoot.root;
  57665. found = true;
  57666. this._edge.scaleInPlace(f);
  57667. p2.addToRef(this._edge, this._collisionPoint);
  57668. }
  57669. }
  57670. p1.subtractToRef(p3, this._edge);
  57671. p3.subtractToRef(this._basePoint, this._baseToVertex);
  57672. edgeSquaredLength = this._edge.lengthSquared();
  57673. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  57674. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  57675. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  57676. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  57677. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  57678. lowestRoot = getLowestRoot(a, b, c, t);
  57679. if (lowestRoot.found) {
  57680. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  57681. if (f >= 0.0 && f <= 1.0) {
  57682. t = lowestRoot.root;
  57683. found = true;
  57684. this._edge.scaleInPlace(f);
  57685. p3.addToRef(this._edge, this._collisionPoint);
  57686. }
  57687. }
  57688. }
  57689. if (found) {
  57690. var distToCollision = t * this._velocity.length();
  57691. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  57692. if (!this.intersectionPoint) {
  57693. this.intersectionPoint = this._collisionPoint.clone();
  57694. }
  57695. else {
  57696. this.intersectionPoint.copyFrom(this._collisionPoint);
  57697. }
  57698. this._nearestDistance = distToCollision;
  57699. this.collisionFound = true;
  57700. }
  57701. }
  57702. };
  57703. /** @hidden */
  57704. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  57705. for (var i = indexStart; i < indexEnd; i += 3) {
  57706. var p1 = pts[indices[i] - decal];
  57707. var p2 = pts[indices[i + 1] - decal];
  57708. var p3 = pts[indices[i + 2] - decal];
  57709. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  57710. }
  57711. };
  57712. /** @hidden */
  57713. Collider.prototype._getResponse = function (pos, vel) {
  57714. pos.addToRef(vel, this._destinationPoint);
  57715. vel.scaleInPlace((this._nearestDistance / vel.length()));
  57716. this._basePoint.addToRef(vel, pos);
  57717. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  57718. this._slidePlaneNormal.normalize();
  57719. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  57720. pos.addInPlace(this._displacementVector);
  57721. this.intersectionPoint.addInPlace(this._displacementVector);
  57722. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  57723. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  57724. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  57725. };
  57726. return Collider;
  57727. }());
  57728. BABYLON.Collider = Collider;
  57729. })(BABYLON || (BABYLON = {}));
  57730. //# sourceMappingURL=babylon.collider.js.map
  57731. var BABYLON;
  57732. (function (BABYLON) {
  57733. //WebWorker code will be inserted to this variable.
  57734. /** @hidden */
  57735. BABYLON.CollisionWorker = "";
  57736. /** Defines supported task for worker process */
  57737. var WorkerTaskType;
  57738. (function (WorkerTaskType) {
  57739. /** Initialization */
  57740. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  57741. /** Update of geometry */
  57742. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  57743. /** Evaluate collision */
  57744. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  57745. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  57746. /** Defines kind of replies returned by worker */
  57747. var WorkerReplyType;
  57748. (function (WorkerReplyType) {
  57749. /** Success */
  57750. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  57751. /** Unkown error */
  57752. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  57753. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  57754. /** @hidden */
  57755. var CollisionCoordinatorWorker = /** @class */ (function () {
  57756. function CollisionCoordinatorWorker() {
  57757. var _this = this;
  57758. this._scaledPosition = BABYLON.Vector3.Zero();
  57759. this._scaledVelocity = BABYLON.Vector3.Zero();
  57760. this.onMeshUpdated = function (transformNode) {
  57761. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  57762. };
  57763. this.onGeometryUpdated = function (geometry) {
  57764. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  57765. };
  57766. this._afterRender = function () {
  57767. if (!_this._init)
  57768. return;
  57769. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  57770. return;
  57771. }
  57772. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  57773. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  57774. if (_this._runningUpdated > 4) {
  57775. return;
  57776. }
  57777. ++_this._runningUpdated;
  57778. var payload = {
  57779. updatedMeshes: _this._addUpdateMeshesList,
  57780. updatedGeometries: _this._addUpdateGeometriesList,
  57781. removedGeometries: _this._toRemoveGeometryArray,
  57782. removedMeshes: _this._toRemoveMeshesArray
  57783. };
  57784. var message = {
  57785. payload: payload,
  57786. taskType: WorkerTaskType.UPDATE
  57787. };
  57788. var serializable = [];
  57789. for (var id in payload.updatedGeometries) {
  57790. if (payload.updatedGeometries.hasOwnProperty(id)) {
  57791. //prepare transferables
  57792. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  57793. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  57794. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  57795. }
  57796. }
  57797. _this._worker.postMessage(message, serializable);
  57798. _this._addUpdateMeshesList = {};
  57799. _this._addUpdateGeometriesList = {};
  57800. _this._toRemoveGeometryArray = [];
  57801. _this._toRemoveMeshesArray = [];
  57802. };
  57803. this._onMessageFromWorker = function (e) {
  57804. var returnData = e.data;
  57805. if (returnData.error != WorkerReplyType.SUCCESS) {
  57806. //TODO what errors can be returned from the worker?
  57807. BABYLON.Tools.Warn("error returned from worker!");
  57808. return;
  57809. }
  57810. switch (returnData.taskType) {
  57811. case WorkerTaskType.INIT:
  57812. _this._init = true;
  57813. //Update the worked with ALL of the scene's current state
  57814. _this._scene.meshes.forEach(function (mesh) {
  57815. _this.onMeshAdded(mesh);
  57816. });
  57817. _this._scene.getGeometries().forEach(function (geometry) {
  57818. _this.onGeometryAdded(geometry);
  57819. });
  57820. break;
  57821. case WorkerTaskType.UPDATE:
  57822. _this._runningUpdated--;
  57823. break;
  57824. case WorkerTaskType.COLLIDE:
  57825. var returnPayload = returnData.payload;
  57826. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  57827. return;
  57828. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  57829. if (callback) {
  57830. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  57831. if (mesh) {
  57832. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  57833. }
  57834. }
  57835. //cleanup
  57836. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  57837. break;
  57838. }
  57839. };
  57840. this._collisionsCallbackArray = [];
  57841. this._init = false;
  57842. this._runningUpdated = 0;
  57843. this._addUpdateMeshesList = {};
  57844. this._addUpdateGeometriesList = {};
  57845. this._toRemoveGeometryArray = [];
  57846. this._toRemoveMeshesArray = [];
  57847. }
  57848. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  57849. if (!this._init)
  57850. return;
  57851. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  57852. return;
  57853. position.divideToRef(collider._radius, this._scaledPosition);
  57854. displacement.divideToRef(collider._radius, this._scaledVelocity);
  57855. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  57856. var payload = {
  57857. collider: {
  57858. position: this._scaledPosition.asArray(),
  57859. velocity: this._scaledVelocity.asArray(),
  57860. radius: collider._radius.asArray()
  57861. },
  57862. collisionId: collisionIndex,
  57863. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  57864. maximumRetry: maximumRetry
  57865. };
  57866. var message = {
  57867. payload: payload,
  57868. taskType: WorkerTaskType.COLLIDE
  57869. };
  57870. this._worker.postMessage(message);
  57871. };
  57872. CollisionCoordinatorWorker.prototype.init = function (scene) {
  57873. this._scene = scene;
  57874. this._scene.registerAfterRender(this._afterRender);
  57875. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  57876. this._worker = new Worker(workerUrl);
  57877. this._worker.onmessage = this._onMessageFromWorker;
  57878. var message = {
  57879. payload: {},
  57880. taskType: WorkerTaskType.INIT
  57881. };
  57882. this._worker.postMessage(message);
  57883. };
  57884. CollisionCoordinatorWorker.prototype.destroy = function () {
  57885. this._scene.unregisterAfterRender(this._afterRender);
  57886. this._worker.terminate();
  57887. };
  57888. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  57889. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  57890. this.onMeshUpdated(mesh);
  57891. };
  57892. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  57893. this._toRemoveMeshesArray.push(mesh.uniqueId);
  57894. };
  57895. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  57896. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  57897. geometry.onGeometryUpdated = this.onGeometryUpdated;
  57898. this.onGeometryUpdated(geometry);
  57899. };
  57900. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  57901. this._toRemoveGeometryArray.push(geometry.id);
  57902. };
  57903. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  57904. var submeshes = [];
  57905. if (mesh.subMeshes) {
  57906. submeshes = mesh.subMeshes.map(function (sm, idx) {
  57907. var boundingInfo = sm.getBoundingInfo();
  57908. return {
  57909. position: idx,
  57910. verticesStart: sm.verticesStart,
  57911. verticesCount: sm.verticesCount,
  57912. indexStart: sm.indexStart,
  57913. indexCount: sm.indexCount,
  57914. hasMaterial: !!sm.getMaterial(),
  57915. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  57916. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  57917. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  57918. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  57919. };
  57920. });
  57921. }
  57922. var geometryId = null;
  57923. if (mesh instanceof BABYLON.Mesh) {
  57924. var geometry = mesh.geometry;
  57925. geometryId = geometry ? geometry.id : null;
  57926. }
  57927. else if (mesh instanceof BABYLON.InstancedMesh) {
  57928. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  57929. geometryId = geometry ? geometry.id : null;
  57930. }
  57931. var boundingInfo = mesh.getBoundingInfo();
  57932. return {
  57933. uniqueId: mesh.uniqueId,
  57934. id: mesh.id,
  57935. name: mesh.name,
  57936. geometryId: geometryId,
  57937. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  57938. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  57939. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  57940. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  57941. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  57942. subMeshes: submeshes,
  57943. checkCollisions: mesh.checkCollisions
  57944. };
  57945. };
  57946. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  57947. return {
  57948. id: geometry.id,
  57949. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  57950. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  57951. indices: new Uint32Array(geometry.getIndices() || []),
  57952. };
  57953. };
  57954. return CollisionCoordinatorWorker;
  57955. }());
  57956. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  57957. /** @hidden */
  57958. var CollisionCoordinatorLegacy = /** @class */ (function () {
  57959. function CollisionCoordinatorLegacy() {
  57960. this._scaledPosition = BABYLON.Vector3.Zero();
  57961. this._scaledVelocity = BABYLON.Vector3.Zero();
  57962. this._finalPosition = BABYLON.Vector3.Zero();
  57963. }
  57964. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  57965. position.divideToRef(collider._radius, this._scaledPosition);
  57966. displacement.divideToRef(collider._radius, this._scaledVelocity);
  57967. collider.collidedMesh = null;
  57968. collider._retry = 0;
  57969. collider._initialVelocity = this._scaledVelocity;
  57970. collider._initialPosition = this._scaledPosition;
  57971. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  57972. this._finalPosition.multiplyInPlace(collider._radius);
  57973. //run the callback
  57974. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  57975. };
  57976. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  57977. this._scene = scene;
  57978. };
  57979. CollisionCoordinatorLegacy.prototype.destroy = function () {
  57980. //Legacy need no destruction method.
  57981. };
  57982. //No update in legacy mode
  57983. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  57984. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  57985. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  57986. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  57987. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  57988. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  57989. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  57990. if (excludedMesh === void 0) { excludedMesh = null; }
  57991. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  57992. if (collider._retry >= maximumRetry) {
  57993. finalPosition.copyFrom(position);
  57994. return;
  57995. }
  57996. // Check if this is a mesh else camera or -1
  57997. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  57998. collider._initialize(position, velocity, closeDistance);
  57999. // Check all meshes
  58000. for (var index = 0; index < this._scene.meshes.length; index++) {
  58001. var mesh = this._scene.meshes[index];
  58002. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  58003. mesh._checkCollision(collider);
  58004. }
  58005. }
  58006. if (!collider.collisionFound) {
  58007. position.addToRef(velocity, finalPosition);
  58008. return;
  58009. }
  58010. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  58011. collider._getResponse(position, velocity);
  58012. }
  58013. if (velocity.length() <= closeDistance) {
  58014. finalPosition.copyFrom(position);
  58015. return;
  58016. }
  58017. collider._retry++;
  58018. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  58019. };
  58020. return CollisionCoordinatorLegacy;
  58021. }());
  58022. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  58023. })(BABYLON || (BABYLON = {}));
  58024. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  58025. var BABYLON;
  58026. (function (BABYLON) {
  58027. /**
  58028. * A particle represents one of the element emitted by a particle system.
  58029. * This is mainly define by its coordinates, direction, velocity and age.
  58030. */
  58031. var Particle = /** @class */ (function () {
  58032. /**
  58033. * Creates a new instance Particle
  58034. * @param particleSystem the particle system the particle belongs to
  58035. */
  58036. function Particle(
  58037. /**
  58038. * The particle system the particle belongs to.
  58039. */
  58040. particleSystem) {
  58041. this.particleSystem = particleSystem;
  58042. /**
  58043. * The world position of the particle in the scene.
  58044. */
  58045. this.position = BABYLON.Vector3.Zero();
  58046. /**
  58047. * The world direction of the particle in the scene.
  58048. */
  58049. this.direction = BABYLON.Vector3.Zero();
  58050. /**
  58051. * The color of the particle.
  58052. */
  58053. this.color = new BABYLON.Color4(0, 0, 0, 0);
  58054. /**
  58055. * The color change of the particle per step.
  58056. */
  58057. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  58058. /**
  58059. * Defines how long will the life of the particle be.
  58060. */
  58061. this.lifeTime = 1.0;
  58062. /**
  58063. * The current age of the particle.
  58064. */
  58065. this.age = 0;
  58066. /**
  58067. * The current size of the particle.
  58068. */
  58069. this.size = 0;
  58070. /**
  58071. * The current scale of the particle.
  58072. */
  58073. this.scale = new BABYLON.Vector2(1, 1);
  58074. /**
  58075. * The current angle of the particle.
  58076. */
  58077. this.angle = 0;
  58078. /**
  58079. * Defines how fast is the angle changing.
  58080. */
  58081. this.angularSpeed = 0;
  58082. /**
  58083. * Defines the cell index used by the particle to be rendered from a sprite.
  58084. */
  58085. this.cellIndex = 0;
  58086. /** @hidden */
  58087. this._attachedSubEmitters = null;
  58088. /** @hidden */
  58089. this._currentColor1 = new BABYLON.Color4(0, 0, 0, 0);
  58090. /** @hidden */
  58091. this._currentColor2 = new BABYLON.Color4(0, 0, 0, 0);
  58092. /** @hidden */
  58093. this._currentSize1 = 0;
  58094. /** @hidden */
  58095. this._currentSize2 = 0;
  58096. /** @hidden */
  58097. this._currentAngularSpeed1 = 0;
  58098. /** @hidden */
  58099. this._currentAngularSpeed2 = 0;
  58100. /** @hidden */
  58101. this._currentVelocity1 = 0;
  58102. /** @hidden */
  58103. this._currentVelocity2 = 0;
  58104. /** @hidden */
  58105. this._currentLimitVelocity1 = 0;
  58106. /** @hidden */
  58107. this._currentLimitVelocity2 = 0;
  58108. /** @hidden */
  58109. this._currentDrag1 = 0;
  58110. /** @hidden */
  58111. this._currentDrag2 = 0;
  58112. this.id = Particle._Count++;
  58113. if (!this.particleSystem.isAnimationSheetEnabled) {
  58114. return;
  58115. }
  58116. this.updateCellInfoFromSystem();
  58117. }
  58118. Particle.prototype.updateCellInfoFromSystem = function () {
  58119. this.cellIndex = this.particleSystem.startSpriteCellID;
  58120. };
  58121. /**
  58122. * Defines how the sprite cell index is updated for the particle
  58123. */
  58124. Particle.prototype.updateCellIndex = function () {
  58125. var offsetAge = this.age;
  58126. var changeSpeed = this.particleSystem.spriteCellChangeSpeed;
  58127. if (this.particleSystem.spriteRandomStartCell) {
  58128. if (this._randomCellOffset === undefined) {
  58129. this._randomCellOffset = Math.random() * this.lifeTime;
  58130. }
  58131. if (changeSpeed === 0) { // Special case when speed = 0 meaning we want to stay on initial cell
  58132. changeSpeed = 1;
  58133. offsetAge = this._randomCellOffset;
  58134. }
  58135. else {
  58136. offsetAge += this._randomCellOffset;
  58137. }
  58138. }
  58139. var dist = (this._initialEndSpriteCellID - this._initialStartSpriteCellID);
  58140. var ratio = BABYLON.Scalar.Clamp(((offsetAge * changeSpeed) % this.lifeTime) / this.lifeTime);
  58141. this.cellIndex = this._initialStartSpriteCellID + (ratio * dist) | 0;
  58142. };
  58143. /** @hidden */
  58144. Particle.prototype._inheritParticleInfoToSubEmitter = function (subEmitter) {
  58145. if (subEmitter.particleSystem.emitter.position) {
  58146. var emitterMesh = subEmitter.particleSystem.emitter;
  58147. emitterMesh.position.copyFrom(this.position);
  58148. if (subEmitter.inheritDirection) {
  58149. emitterMesh.position.subtractToRef(this.direction, BABYLON.Tmp.Vector3[0]);
  58150. // Look at using Y as forward
  58151. emitterMesh.lookAt(BABYLON.Tmp.Vector3[0], 0, Math.PI / 2);
  58152. }
  58153. }
  58154. else {
  58155. var emitterPosition = subEmitter.particleSystem.emitter;
  58156. emitterPosition.copyFrom(this.position);
  58157. }
  58158. // Set inheritedVelocityOffset to be used when new particles are created
  58159. this.direction.scaleToRef(subEmitter.inheritedVelocityAmount / 2, BABYLON.Tmp.Vector3[0]);
  58160. subEmitter.particleSystem._inheritedVelocityOffset.copyFrom(BABYLON.Tmp.Vector3[0]);
  58161. };
  58162. /** @hidden */
  58163. Particle.prototype._inheritParticleInfoToSubEmitters = function () {
  58164. var _this = this;
  58165. if (this._attachedSubEmitters && this._attachedSubEmitters.length > 0) {
  58166. this._attachedSubEmitters.forEach(function (subEmitter) {
  58167. _this._inheritParticleInfoToSubEmitter(subEmitter);
  58168. });
  58169. }
  58170. };
  58171. /** @hidden */
  58172. Particle.prototype._reset = function () {
  58173. this.age = 0;
  58174. this._currentColorGradient = null;
  58175. this._currentSizeGradient = null;
  58176. this._currentAngularSpeedGradient = null;
  58177. this._currentVelocityGradient = null;
  58178. this._currentLimitVelocityGradient = null;
  58179. this._currentDragGradient = null;
  58180. this.cellIndex = this.particleSystem.startSpriteCellID;
  58181. this._randomCellOffset = undefined;
  58182. };
  58183. /**
  58184. * Copy the properties of particle to another one.
  58185. * @param other the particle to copy the information to.
  58186. */
  58187. Particle.prototype.copyTo = function (other) {
  58188. other.position.copyFrom(this.position);
  58189. if (this._initialDirection) {
  58190. if (other._initialDirection) {
  58191. other._initialDirection.copyFrom(this._initialDirection);
  58192. }
  58193. else {
  58194. other._initialDirection = this._initialDirection.clone();
  58195. }
  58196. }
  58197. else {
  58198. other._initialDirection = null;
  58199. }
  58200. other.direction.copyFrom(this.direction);
  58201. other.color.copyFrom(this.color);
  58202. other.colorStep.copyFrom(this.colorStep);
  58203. other.lifeTime = this.lifeTime;
  58204. other.age = this.age;
  58205. other._randomCellOffset = this._randomCellOffset;
  58206. other.size = this.size;
  58207. other.scale.copyFrom(this.scale);
  58208. other.angle = this.angle;
  58209. other.angularSpeed = this.angularSpeed;
  58210. other.particleSystem = this.particleSystem;
  58211. other.cellIndex = this.cellIndex;
  58212. other.id = this.id;
  58213. other._attachedSubEmitters = this._attachedSubEmitters;
  58214. if (this._currentColorGradient) {
  58215. other._currentColorGradient = this._currentColorGradient;
  58216. other._currentColor1.copyFrom(this._currentColor1);
  58217. other._currentColor2.copyFrom(this._currentColor2);
  58218. }
  58219. if (this._currentSizeGradient) {
  58220. other._currentSizeGradient = this._currentSizeGradient;
  58221. other._currentSize1 = this._currentSize1;
  58222. other._currentSize2 = this._currentSize2;
  58223. }
  58224. if (this._currentAngularSpeedGradient) {
  58225. other._currentAngularSpeedGradient = this._currentAngularSpeedGradient;
  58226. other._currentAngularSpeed1 = this._currentAngularSpeed1;
  58227. other._currentAngularSpeed2 = this._currentAngularSpeed2;
  58228. }
  58229. if (this._currentVelocityGradient) {
  58230. other._currentVelocityGradient = this._currentVelocityGradient;
  58231. other._currentVelocity1 = this._currentVelocity1;
  58232. other._currentVelocity2 = this._currentVelocity2;
  58233. }
  58234. if (this._currentLimitVelocityGradient) {
  58235. other._currentLimitVelocityGradient = this._currentLimitVelocityGradient;
  58236. other._currentLimitVelocity1 = this._currentLimitVelocity1;
  58237. other._currentLimitVelocity2 = this._currentLimitVelocity2;
  58238. }
  58239. if (this._currentDragGradient) {
  58240. other._currentDragGradient = this._currentDragGradient;
  58241. other._currentDrag1 = this._currentDrag1;
  58242. other._currentDrag2 = this._currentDrag2;
  58243. }
  58244. if (this.particleSystem.isAnimationSheetEnabled) {
  58245. other._initialStartSpriteCellID = this._initialStartSpriteCellID;
  58246. other._initialEndSpriteCellID = this._initialEndSpriteCellID;
  58247. }
  58248. if (this.particleSystem.useRampGradients) {
  58249. other.remapData.copyFrom(this.remapData);
  58250. }
  58251. if (this._randomNoiseCoordinates1) {
  58252. if (other._randomNoiseCoordinates1) {
  58253. other._randomNoiseCoordinates1.copyFrom(this._randomNoiseCoordinates1);
  58254. other._randomNoiseCoordinates2.copyFrom(this._randomNoiseCoordinates2);
  58255. }
  58256. else {
  58257. other._randomNoiseCoordinates1 = this._randomNoiseCoordinates1.clone();
  58258. other._randomNoiseCoordinates2 = this._randomNoiseCoordinates2.clone();
  58259. }
  58260. }
  58261. };
  58262. Particle._Count = 0;
  58263. return Particle;
  58264. }());
  58265. BABYLON.Particle = Particle;
  58266. })(BABYLON || (BABYLON = {}));
  58267. //# sourceMappingURL=babylon.particle.js.map
  58268. var BABYLON;
  58269. (function (BABYLON) {
  58270. /**
  58271. * This represents the base class for particle system in Babylon.
  58272. * 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.
  58273. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  58274. * @example https://doc.babylonjs.com/babylon101/particles
  58275. */
  58276. var BaseParticleSystem = /** @class */ (function () {
  58277. /**
  58278. * Instantiates a particle system.
  58279. * 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.
  58280. * @param name The name of the particle system
  58281. */
  58282. function BaseParticleSystem(name) {
  58283. /**
  58284. * List of animations used by the particle system.
  58285. */
  58286. this.animations = [];
  58287. /**
  58288. * The rendering group used by the Particle system to chose when to render.
  58289. */
  58290. this.renderingGroupId = 0;
  58291. /**
  58292. * The emitter represents the Mesh or position we are attaching the particle system to.
  58293. */
  58294. this.emitter = null;
  58295. /**
  58296. * The maximum number of particles to emit per frame
  58297. */
  58298. this.emitRate = 10;
  58299. /**
  58300. * If you want to launch only a few particles at once, that can be done, as well.
  58301. */
  58302. this.manualEmitCount = -1;
  58303. /**
  58304. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  58305. */
  58306. this.updateSpeed = 0.01;
  58307. /**
  58308. * The amount of time the particle system is running (depends of the overall update speed).
  58309. */
  58310. this.targetStopDuration = 0;
  58311. /**
  58312. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  58313. */
  58314. this.disposeOnStop = false;
  58315. /**
  58316. * Minimum power of emitting particles.
  58317. */
  58318. this.minEmitPower = 1;
  58319. /**
  58320. * Maximum power of emitting particles.
  58321. */
  58322. this.maxEmitPower = 1;
  58323. /**
  58324. * Minimum life time of emitting particles.
  58325. */
  58326. this.minLifeTime = 1;
  58327. /**
  58328. * Maximum life time of emitting particles.
  58329. */
  58330. this.maxLifeTime = 1;
  58331. /**
  58332. * Minimum Size of emitting particles.
  58333. */
  58334. this.minSize = 1;
  58335. /**
  58336. * Maximum Size of emitting particles.
  58337. */
  58338. this.maxSize = 1;
  58339. /**
  58340. * Minimum scale of emitting particles on X axis.
  58341. */
  58342. this.minScaleX = 1;
  58343. /**
  58344. * Maximum scale of emitting particles on X axis.
  58345. */
  58346. this.maxScaleX = 1;
  58347. /**
  58348. * Minimum scale of emitting particles on Y axis.
  58349. */
  58350. this.minScaleY = 1;
  58351. /**
  58352. * Maximum scale of emitting particles on Y axis.
  58353. */
  58354. this.maxScaleY = 1;
  58355. /**
  58356. * Gets or sets the minimal initial rotation in radians.
  58357. */
  58358. this.minInitialRotation = 0;
  58359. /**
  58360. * Gets or sets the maximal initial rotation in radians.
  58361. */
  58362. this.maxInitialRotation = 0;
  58363. /**
  58364. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  58365. */
  58366. this.minAngularSpeed = 0;
  58367. /**
  58368. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  58369. */
  58370. this.maxAngularSpeed = 0;
  58371. /**
  58372. * The layer mask we are rendering the particles through.
  58373. */
  58374. this.layerMask = 0x0FFFFFFF;
  58375. /**
  58376. * This can help using your own shader to render the particle system.
  58377. * The according effect will be created
  58378. */
  58379. this.customShader = null;
  58380. /**
  58381. * By default particle system starts as soon as they are created. This prevents the
  58382. * automatic start to happen and let you decide when to start emitting particles.
  58383. */
  58384. this.preventAutoStart = false;
  58385. /** Gets or sets the strength to apply to the noise value (default is (10, 10, 10)) */
  58386. this.noiseStrength = new BABYLON.Vector3(10, 10, 10);
  58387. /**
  58388. * Callback triggered when the particle animation is ending.
  58389. */
  58390. this.onAnimationEnd = null;
  58391. /**
  58392. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  58393. */
  58394. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  58395. /**
  58396. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  58397. * to override the particles.
  58398. */
  58399. this.forceDepthWrite = false;
  58400. /** 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 */
  58401. this.preWarmCycles = 0;
  58402. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  58403. this.preWarmStepOffset = 1;
  58404. /**
  58405. * If using a spritesheet (isAnimationSheetEnabled) defines the speed of the sprite loop (default is 1 meaning the animation will play once during the entire particle lifetime)
  58406. */
  58407. this.spriteCellChangeSpeed = 1;
  58408. /**
  58409. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  58410. */
  58411. this.startSpriteCellID = 0;
  58412. /**
  58413. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  58414. */
  58415. this.endSpriteCellID = 0;
  58416. /**
  58417. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  58418. */
  58419. this.spriteCellWidth = 0;
  58420. /**
  58421. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  58422. */
  58423. this.spriteCellHeight = 0;
  58424. /**
  58425. * This allows the system to random pick the start cell ID between startSpriteCellID and endSpriteCellID
  58426. */
  58427. this.spriteRandomStartCell = false;
  58428. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  58429. this.translationPivot = new BABYLON.Vector2(0, 0);
  58430. /**
  58431. * Gets or sets a boolean indicating that hosted animations (in the system.animations array) must be started when system.start() is called
  58432. */
  58433. this.beginAnimationOnStart = false;
  58434. /**
  58435. * Gets or sets the frame to start the animation from when beginAnimationOnStart is true
  58436. */
  58437. this.beginAnimationFrom = 0;
  58438. /**
  58439. * Gets or sets the frame to end the animation on when beginAnimationOnStart is true
  58440. */
  58441. this.beginAnimationTo = 60;
  58442. /**
  58443. * Gets or sets a boolean indicating if animations must loop when beginAnimationOnStart is true
  58444. */
  58445. this.beginAnimationLoop = false;
  58446. /**
  58447. * You can use gravity if you want to give an orientation to your particles.
  58448. */
  58449. this.gravity = BABYLON.Vector3.Zero();
  58450. this._colorGradients = null;
  58451. this._sizeGradients = null;
  58452. this._lifeTimeGradients = null;
  58453. this._angularSpeedGradients = null;
  58454. this._velocityGradients = null;
  58455. this._limitVelocityGradients = null;
  58456. this._dragGradients = null;
  58457. this._emitRateGradients = null;
  58458. this._startSizeGradients = null;
  58459. this._rampGradients = null;
  58460. this._colorRemapGradients = null;
  58461. this._alphaRemapGradients = null;
  58462. /**
  58463. * Defines the delay in milliseconds before starting the system (0 by default)
  58464. */
  58465. this.startDelay = 0;
  58466. /** Gets or sets a value indicating the damping to apply if the limit velocity factor is reached */
  58467. this.limitVelocityDamping = 0.4;
  58468. /**
  58469. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  58470. */
  58471. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  58472. /**
  58473. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  58474. */
  58475. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  58476. /**
  58477. * Color the particle will have at the end of its lifetime
  58478. */
  58479. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  58480. /**
  58481. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel
  58482. */
  58483. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  58484. /** @hidden */
  58485. this._isSubEmitter = false;
  58486. /**
  58487. * Gets or sets the billboard mode to use when isBillboardBased = true.
  58488. * Value can be: ParticleSystem.BILLBOARDMODE_ALL, ParticleSystem.BILLBOARDMODE_Y, ParticleSystem.BILLBOARDMODE_STRETCHED
  58489. */
  58490. this.billboardMode = BABYLON.ParticleSystem.BILLBOARDMODE_ALL;
  58491. this._isBillboardBased = true;
  58492. /**
  58493. * Local cache of defines for image processing.
  58494. */
  58495. this._imageProcessingConfigurationDefines = new BABYLON.ImageProcessingConfigurationDefines();
  58496. this.id = name;
  58497. this.name = name;
  58498. }
  58499. Object.defineProperty(BaseParticleSystem.prototype, "isAnimationSheetEnabled", {
  58500. /**
  58501. * Gets or sets whether an animation sprite sheet is enabled or not on the particle system
  58502. */
  58503. get: function () {
  58504. return this._isAnimationSheetEnabled;
  58505. },
  58506. set: function (value) {
  58507. if (this._isAnimationSheetEnabled == value) {
  58508. return;
  58509. }
  58510. this._isAnimationSheetEnabled = value;
  58511. this._reset();
  58512. },
  58513. enumerable: true,
  58514. configurable: true
  58515. });
  58516. /**
  58517. * Get hosting scene
  58518. * @returns the scene
  58519. */
  58520. BaseParticleSystem.prototype.getScene = function () {
  58521. return this._scene;
  58522. };
  58523. BaseParticleSystem.prototype._hasTargetStopDurationDependantGradient = function () {
  58524. return (this._startSizeGradients && this._startSizeGradients.length > 0)
  58525. || (this._emitRateGradients && this._emitRateGradients.length > 0)
  58526. || (this._lifeTimeGradients && this._lifeTimeGradients.length > 0);
  58527. };
  58528. /**
  58529. * Gets the current list of drag gradients.
  58530. * You must use addDragGradient and removeDragGradient to udpate this list
  58531. * @returns the list of drag gradients
  58532. */
  58533. BaseParticleSystem.prototype.getDragGradients = function () {
  58534. return this._dragGradients;
  58535. };
  58536. /**
  58537. * Gets the current list of limit velocity gradients.
  58538. * You must use addLimitVelocityGradient and removeLimitVelocityGradient to udpate this list
  58539. * @returns the list of limit velocity gradients
  58540. */
  58541. BaseParticleSystem.prototype.getLimitVelocityGradients = function () {
  58542. return this._limitVelocityGradients;
  58543. };
  58544. /**
  58545. * Gets the current list of color gradients.
  58546. * You must use addColorGradient and removeColorGradient to udpate this list
  58547. * @returns the list of color gradients
  58548. */
  58549. BaseParticleSystem.prototype.getColorGradients = function () {
  58550. return this._colorGradients;
  58551. };
  58552. /**
  58553. * Gets the current list of size gradients.
  58554. * You must use addSizeGradient and removeSizeGradient to udpate this list
  58555. * @returns the list of size gradients
  58556. */
  58557. BaseParticleSystem.prototype.getSizeGradients = function () {
  58558. return this._sizeGradients;
  58559. };
  58560. /**
  58561. * Gets the current list of color remap gradients.
  58562. * You must use addColorRemapGradient and removeColorRemapGradient to udpate this list
  58563. * @returns the list of color remap gradients
  58564. */
  58565. BaseParticleSystem.prototype.getColorRemapGradients = function () {
  58566. return this._colorRemapGradients;
  58567. };
  58568. /**
  58569. * Gets the current list of alpha remap gradients.
  58570. * You must use addAlphaRemapGradient and removeAlphaRemapGradient to udpate this list
  58571. * @returns the list of alpha remap gradients
  58572. */
  58573. BaseParticleSystem.prototype.getAlphaRemapGradients = function () {
  58574. return this._alphaRemapGradients;
  58575. };
  58576. /**
  58577. * Gets the current list of life time gradients.
  58578. * You must use addLifeTimeGradient and removeLifeTimeGradient to udpate this list
  58579. * @returns the list of life time gradients
  58580. */
  58581. BaseParticleSystem.prototype.getLifeTimeGradients = function () {
  58582. return this._lifeTimeGradients;
  58583. };
  58584. /**
  58585. * Gets the current list of angular speed gradients.
  58586. * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list
  58587. * @returns the list of angular speed gradients
  58588. */
  58589. BaseParticleSystem.prototype.getAngularSpeedGradients = function () {
  58590. return this._angularSpeedGradients;
  58591. };
  58592. /**
  58593. * Gets the current list of velocity gradients.
  58594. * You must use addVelocityGradient and removeVelocityGradient to udpate this list
  58595. * @returns the list of velocity gradients
  58596. */
  58597. BaseParticleSystem.prototype.getVelocityGradients = function () {
  58598. return this._velocityGradients;
  58599. };
  58600. /**
  58601. * Gets the current list of start size gradients.
  58602. * You must use addStartSizeGradient and removeStartSizeGradient to udpate this list
  58603. * @returns the list of start size gradients
  58604. */
  58605. BaseParticleSystem.prototype.getStartSizeGradients = function () {
  58606. return this._startSizeGradients;
  58607. };
  58608. /**
  58609. * Gets the current list of emit rate gradients.
  58610. * You must use addEmitRateGradient and removeEmitRateGradient to udpate this list
  58611. * @returns the list of emit rate gradients
  58612. */
  58613. BaseParticleSystem.prototype.getEmitRateGradients = function () {
  58614. return this._emitRateGradients;
  58615. };
  58616. Object.defineProperty(BaseParticleSystem.prototype, "direction1", {
  58617. /**
  58618. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  58619. * This only works when particleEmitterTyps is a BoxParticleEmitter
  58620. */
  58621. get: function () {
  58622. if (this.particleEmitterType.direction1) {
  58623. return this.particleEmitterType.direction1;
  58624. }
  58625. return BABYLON.Vector3.Zero();
  58626. },
  58627. set: function (value) {
  58628. if (this.particleEmitterType.direction1) {
  58629. this.particleEmitterType.direction1 = value;
  58630. }
  58631. },
  58632. enumerable: true,
  58633. configurable: true
  58634. });
  58635. Object.defineProperty(BaseParticleSystem.prototype, "direction2", {
  58636. /**
  58637. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  58638. * This only works when particleEmitterTyps is a BoxParticleEmitter
  58639. */
  58640. get: function () {
  58641. if (this.particleEmitterType.direction2) {
  58642. return this.particleEmitterType.direction2;
  58643. }
  58644. return BABYLON.Vector3.Zero();
  58645. },
  58646. set: function (value) {
  58647. if (this.particleEmitterType.direction2) {
  58648. this.particleEmitterType.direction2 = value;
  58649. }
  58650. },
  58651. enumerable: true,
  58652. configurable: true
  58653. });
  58654. Object.defineProperty(BaseParticleSystem.prototype, "minEmitBox", {
  58655. /**
  58656. * 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.
  58657. * This only works when particleEmitterTyps is a BoxParticleEmitter
  58658. */
  58659. get: function () {
  58660. if (this.particleEmitterType.minEmitBox) {
  58661. return this.particleEmitterType.minEmitBox;
  58662. }
  58663. return BABYLON.Vector3.Zero();
  58664. },
  58665. set: function (value) {
  58666. if (this.particleEmitterType.minEmitBox) {
  58667. this.particleEmitterType.minEmitBox = value;
  58668. }
  58669. },
  58670. enumerable: true,
  58671. configurable: true
  58672. });
  58673. Object.defineProperty(BaseParticleSystem.prototype, "maxEmitBox", {
  58674. /**
  58675. * 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.
  58676. * This only works when particleEmitterTyps is a BoxParticleEmitter
  58677. */
  58678. get: function () {
  58679. if (this.particleEmitterType.maxEmitBox) {
  58680. return this.particleEmitterType.maxEmitBox;
  58681. }
  58682. return BABYLON.Vector3.Zero();
  58683. },
  58684. set: function (value) {
  58685. if (this.particleEmitterType.maxEmitBox) {
  58686. this.particleEmitterType.maxEmitBox = value;
  58687. }
  58688. },
  58689. enumerable: true,
  58690. configurable: true
  58691. });
  58692. Object.defineProperty(BaseParticleSystem.prototype, "isBillboardBased", {
  58693. /**
  58694. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  58695. */
  58696. get: function () {
  58697. return this._isBillboardBased;
  58698. },
  58699. set: function (value) {
  58700. if (this._isBillboardBased === value) {
  58701. return;
  58702. }
  58703. this._isBillboardBased = value;
  58704. this._reset();
  58705. },
  58706. enumerable: true,
  58707. configurable: true
  58708. });
  58709. Object.defineProperty(BaseParticleSystem.prototype, "imageProcessingConfiguration", {
  58710. /**
  58711. * Gets the image processing configuration used either in this material.
  58712. */
  58713. get: function () {
  58714. return this._imageProcessingConfiguration;
  58715. },
  58716. /**
  58717. * Sets the Default image processing configuration used either in the this material.
  58718. *
  58719. * If sets to null, the scene one is in use.
  58720. */
  58721. set: function (value) {
  58722. this._attachImageProcessingConfiguration(value);
  58723. },
  58724. enumerable: true,
  58725. configurable: true
  58726. });
  58727. /**
  58728. * Attaches a new image processing configuration to the Standard Material.
  58729. * @param configuration
  58730. */
  58731. BaseParticleSystem.prototype._attachImageProcessingConfiguration = function (configuration) {
  58732. if (configuration === this._imageProcessingConfiguration) {
  58733. return;
  58734. }
  58735. // Pick the scene configuration if needed.
  58736. if (!configuration) {
  58737. this._imageProcessingConfiguration = this._scene.imageProcessingConfiguration;
  58738. }
  58739. else {
  58740. this._imageProcessingConfiguration = configuration;
  58741. }
  58742. };
  58743. /** @hidden */
  58744. BaseParticleSystem.prototype._reset = function () {
  58745. };
  58746. /** @hidden */
  58747. BaseParticleSystem.prototype._removeGradientAndTexture = function (gradient, gradients, texture) {
  58748. if (!gradients) {
  58749. return this;
  58750. }
  58751. var index = 0;
  58752. for (var _i = 0, gradients_1 = gradients; _i < gradients_1.length; _i++) {
  58753. var valueGradient = gradients_1[_i];
  58754. if (valueGradient.gradient === gradient) {
  58755. gradients.splice(index, 1);
  58756. break;
  58757. }
  58758. index++;
  58759. }
  58760. if (texture) {
  58761. texture.dispose();
  58762. }
  58763. return this;
  58764. };
  58765. /**
  58766. * Creates a Point Emitter for the particle system (emits directly from the emitter position)
  58767. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  58768. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  58769. * @returns the emitter
  58770. */
  58771. BaseParticleSystem.prototype.createPointEmitter = function (direction1, direction2) {
  58772. var particleEmitter = new BABYLON.PointParticleEmitter();
  58773. particleEmitter.direction1 = direction1;
  58774. particleEmitter.direction2 = direction2;
  58775. this.particleEmitterType = particleEmitter;
  58776. return particleEmitter;
  58777. };
  58778. /**
  58779. * Creates a Hemisphere Emitter for the particle system (emits along the hemisphere radius)
  58780. * @param radius The radius of the hemisphere to emit from
  58781. * @param radiusRange The range of the hemisphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  58782. * @returns the emitter
  58783. */
  58784. BaseParticleSystem.prototype.createHemisphericEmitter = function (radius, radiusRange) {
  58785. if (radius === void 0) { radius = 1; }
  58786. if (radiusRange === void 0) { radiusRange = 1; }
  58787. var particleEmitter = new BABYLON.HemisphericParticleEmitter(radius, radiusRange);
  58788. this.particleEmitterType = particleEmitter;
  58789. return particleEmitter;
  58790. };
  58791. /**
  58792. * Creates a Sphere Emitter for the particle system (emits along the sphere radius)
  58793. * @param radius The radius of the sphere to emit from
  58794. * @param radiusRange The range of the sphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  58795. * @returns the emitter
  58796. */
  58797. BaseParticleSystem.prototype.createSphereEmitter = function (radius, radiusRange) {
  58798. if (radius === void 0) { radius = 1; }
  58799. if (radiusRange === void 0) { radiusRange = 1; }
  58800. var particleEmitter = new BABYLON.SphereParticleEmitter(radius, radiusRange);
  58801. this.particleEmitterType = particleEmitter;
  58802. return particleEmitter;
  58803. };
  58804. /**
  58805. * Creates a Directed Sphere Emitter for the particle system (emits between direction1 and direction2)
  58806. * @param radius The radius of the sphere to emit from
  58807. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  58808. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  58809. * @returns the emitter
  58810. */
  58811. BaseParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  58812. if (radius === void 0) { radius = 1; }
  58813. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  58814. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  58815. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  58816. this.particleEmitterType = particleEmitter;
  58817. return particleEmitter;
  58818. };
  58819. /**
  58820. * Creates a Cylinder Emitter for the particle system (emits from the cylinder to the particle position)
  58821. * @param radius The radius of the emission cylinder
  58822. * @param height The height of the emission cylinder
  58823. * @param radiusRange The range of emission [0-1] 0 Surface only, 1 Entire Radius
  58824. * @param directionRandomizer How much to randomize the particle direction [0-1]
  58825. * @returns the emitter
  58826. */
  58827. BaseParticleSystem.prototype.createCylinderEmitter = function (radius, height, radiusRange, directionRandomizer) {
  58828. if (radius === void 0) { radius = 1; }
  58829. if (height === void 0) { height = 1; }
  58830. if (radiusRange === void 0) { radiusRange = 1; }
  58831. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  58832. var particleEmitter = new BABYLON.CylinderParticleEmitter(radius, height, radiusRange, directionRandomizer);
  58833. this.particleEmitterType = particleEmitter;
  58834. return particleEmitter;
  58835. };
  58836. /**
  58837. * Creates a Directed Cylinder Emitter for the particle system (emits between direction1 and direction2)
  58838. * @param radius The radius of the cylinder to emit from
  58839. * @param height The height of the emission cylinder
  58840. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  58841. * @param direction1 Particles are emitted between the direction1 and direction2 from within the cylinder
  58842. * @param direction2 Particles are emitted between the direction1 and direction2 from within the cylinder
  58843. * @returns the emitter
  58844. */
  58845. BaseParticleSystem.prototype.createDirectedCylinderEmitter = function (radius, height, radiusRange, direction1, direction2) {
  58846. if (radius === void 0) { radius = 1; }
  58847. if (height === void 0) { height = 1; }
  58848. if (radiusRange === void 0) { radiusRange = 1; }
  58849. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  58850. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  58851. var particleEmitter = new BABYLON.CylinderDirectedParticleEmitter(radius, height, radiusRange, direction1, direction2);
  58852. this.particleEmitterType = particleEmitter;
  58853. return particleEmitter;
  58854. };
  58855. /**
  58856. * Creates a Cone Emitter for the particle system (emits from the cone to the particle position)
  58857. * @param radius The radius of the cone to emit from
  58858. * @param angle The base angle of the cone
  58859. * @returns the emitter
  58860. */
  58861. BaseParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  58862. if (radius === void 0) { radius = 1; }
  58863. if (angle === void 0) { angle = Math.PI / 4; }
  58864. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  58865. this.particleEmitterType = particleEmitter;
  58866. return particleEmitter;
  58867. };
  58868. /**
  58869. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  58870. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  58871. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  58872. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  58873. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  58874. * @returns the emitter
  58875. */
  58876. BaseParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  58877. var particleEmitter = new BABYLON.BoxParticleEmitter();
  58878. this.particleEmitterType = particleEmitter;
  58879. this.direction1 = direction1;
  58880. this.direction2 = direction2;
  58881. this.minEmitBox = minEmitBox;
  58882. this.maxEmitBox = maxEmitBox;
  58883. return particleEmitter;
  58884. };
  58885. /**
  58886. * Source color is added to the destination color without alpha affecting the result
  58887. */
  58888. BaseParticleSystem.BLENDMODE_ONEONE = 0;
  58889. /**
  58890. * Blend current color and particle color using particle’s alpha
  58891. */
  58892. BaseParticleSystem.BLENDMODE_STANDARD = 1;
  58893. /**
  58894. * Add current color and particle color multiplied by particle’s alpha
  58895. */
  58896. BaseParticleSystem.BLENDMODE_ADD = 2;
  58897. /**
  58898. * Multiply current color with particle color
  58899. */
  58900. BaseParticleSystem.BLENDMODE_MULTIPLY = 3;
  58901. /**
  58902. * Multiply current color with particle color then add current color and particle color multiplied by particle’s alpha
  58903. */
  58904. BaseParticleSystem.BLENDMODE_MULTIPLYADD = 4;
  58905. return BaseParticleSystem;
  58906. }());
  58907. BABYLON.BaseParticleSystem = BaseParticleSystem;
  58908. })(BABYLON || (BABYLON = {}));
  58909. //# sourceMappingURL=babylon.baseParticleSystem.js.map
  58910. var BABYLON;
  58911. (function (BABYLON) {
  58912. /**
  58913. * This represents a particle system in Babylon.
  58914. * 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.
  58915. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  58916. * @example https://doc.babylonjs.com/babylon101/particles
  58917. */
  58918. var ParticleSystem = /** @class */ (function (_super) {
  58919. __extends(ParticleSystem, _super);
  58920. /**
  58921. * Instantiates a particle system.
  58922. * 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.
  58923. * @param name The name of the particle system
  58924. * @param capacity The max number of particles alive at the same time
  58925. * @param scene The scene the particle system belongs to
  58926. * @param customEffect a custom effect used to change the way particles are rendered by default
  58927. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  58928. * @param epsilon Offset used to render the particles
  58929. */
  58930. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  58931. if (customEffect === void 0) { customEffect = null; }
  58932. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  58933. if (epsilon === void 0) { epsilon = 0.01; }
  58934. var _this = _super.call(this, name) || this;
  58935. /**
  58936. * @hidden
  58937. */
  58938. _this._inheritedVelocityOffset = new BABYLON.Vector3();
  58939. /**
  58940. * An event triggered when the system is disposed
  58941. */
  58942. _this.onDisposeObservable = new BABYLON.Observable();
  58943. _this._particles = new Array();
  58944. _this._stockParticles = new Array();
  58945. _this._newPartsExcess = 0;
  58946. _this._vertexBuffers = {};
  58947. _this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  58948. _this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  58949. _this._scaledDirection = BABYLON.Vector3.Zero();
  58950. _this._scaledGravity = BABYLON.Vector3.Zero();
  58951. _this._currentRenderId = -1;
  58952. _this._useInstancing = false;
  58953. _this._started = false;
  58954. _this._stopped = false;
  58955. _this._actualFrame = 0;
  58956. /** @hidden */
  58957. _this._currentEmitRate1 = 0;
  58958. /** @hidden */
  58959. _this._currentEmitRate2 = 0;
  58960. /** @hidden */
  58961. _this._currentStartSize1 = 0;
  58962. /** @hidden */
  58963. _this._currentStartSize2 = 0;
  58964. _this._rawTextureWidth = 256;
  58965. _this._useRampGradients = false;
  58966. /**
  58967. * @hidden
  58968. * If the particle systems emitter should be disposed when the particle system is disposed
  58969. */
  58970. _this._disposeEmitterOnDispose = false;
  58971. // start of sub system methods
  58972. /**
  58973. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  58974. * Its lifetime will start back at 0.
  58975. */
  58976. _this.recycleParticle = function (particle) {
  58977. // move particle from activeParticle list to stock particles
  58978. var lastParticle = _this._particles.pop();
  58979. if (lastParticle !== particle) {
  58980. lastParticle.copyTo(particle);
  58981. }
  58982. _this._stockParticles.push(lastParticle);
  58983. };
  58984. _this._createParticle = function () {
  58985. var particle;
  58986. if (_this._stockParticles.length !== 0) {
  58987. particle = _this._stockParticles.pop();
  58988. particle._reset();
  58989. }
  58990. else {
  58991. particle = new BABYLON.Particle(_this);
  58992. }
  58993. // Attach emitters
  58994. if (_this._subEmitters && _this._subEmitters.length > 0) {
  58995. var subEmitters = _this._subEmitters[Math.floor(Math.random() * _this._subEmitters.length)];
  58996. particle._attachedSubEmitters = [];
  58997. subEmitters.forEach(function (subEmitter) {
  58998. if (subEmitter.type === BABYLON.SubEmitterType.ATTACHED) {
  58999. var newEmitter = subEmitter.clone();
  59000. particle._attachedSubEmitters.push(newEmitter);
  59001. newEmitter.particleSystem.start();
  59002. }
  59003. });
  59004. }
  59005. return particle;
  59006. };
  59007. _this._emitFromParticle = function (particle) {
  59008. if (!_this._subEmitters || _this._subEmitters.length === 0) {
  59009. return;
  59010. }
  59011. var templateIndex = Math.floor(Math.random() * _this._subEmitters.length);
  59012. _this._subEmitters[templateIndex].forEach(function (subEmitter) {
  59013. if (subEmitter.type === BABYLON.SubEmitterType.END) {
  59014. var subSystem = subEmitter.clone();
  59015. particle._inheritParticleInfoToSubEmitter(subSystem);
  59016. subSystem.particleSystem._rootParticleSystem = _this;
  59017. _this.activeSubSystems.push(subSystem.particleSystem);
  59018. subSystem.particleSystem.start();
  59019. }
  59020. });
  59021. };
  59022. _this._capacity = capacity;
  59023. _this._epsilon = epsilon;
  59024. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  59025. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  59026. // Setup the default processing configuration to the scene.
  59027. _this._attachImageProcessingConfiguration(null);
  59028. _this._customEffect = customEffect;
  59029. _this._scene.particleSystems.push(_this);
  59030. _this._useInstancing = _this._scene.getEngine().getCaps().instancedArrays;
  59031. _this._createIndexBuffer();
  59032. _this._createVertexBuffers();
  59033. // Default emitter type
  59034. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  59035. // Update
  59036. _this.updateFunction = function (particles) {
  59037. var noiseTextureSize = null;
  59038. var noiseTextureData = null;
  59039. if (_this.noiseTexture) { // We need to get texture data back to CPU
  59040. noiseTextureSize = _this.noiseTexture.getSize();
  59041. noiseTextureData = (_this.noiseTexture.getContent());
  59042. }
  59043. var _loop_1 = function () {
  59044. particle = particles[index];
  59045. var scaledUpdateSpeed = _this._scaledUpdateSpeed;
  59046. var previousAge = particle.age;
  59047. particle.age += scaledUpdateSpeed;
  59048. // Evaluate step to death
  59049. if (particle.age > particle.lifeTime) {
  59050. var diff = particle.age - previousAge;
  59051. var oldDiff = particle.lifeTime - previousAge;
  59052. scaledUpdateSpeed = (oldDiff * scaledUpdateSpeed) / diff;
  59053. particle.age = particle.lifeTime;
  59054. }
  59055. var ratio = particle.age / particle.lifeTime;
  59056. // Color
  59057. if (_this._colorGradients && _this._colorGradients.length > 0) {
  59058. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorGradients, function (currentGradient, nextGradient, scale) {
  59059. if (currentGradient !== particle._currentColorGradient) {
  59060. particle._currentColor1.copyFrom(particle._currentColor2);
  59061. nextGradient.getColorToRef(particle._currentColor2);
  59062. particle._currentColorGradient = currentGradient;
  59063. }
  59064. BABYLON.Color4.LerpToRef(particle._currentColor1, particle._currentColor2, scale, particle.color);
  59065. });
  59066. }
  59067. else {
  59068. particle.colorStep.scaleToRef(scaledUpdateSpeed, _this._scaledColorStep);
  59069. particle.color.addInPlace(_this._scaledColorStep);
  59070. if (particle.color.a < 0) {
  59071. particle.color.a = 0;
  59072. }
  59073. }
  59074. // Angular speed
  59075. if (_this._angularSpeedGradients && _this._angularSpeedGradients.length > 0) {
  59076. BABYLON.Tools.GetCurrentGradient(ratio, _this._angularSpeedGradients, function (currentGradient, nextGradient, scale) {
  59077. if (currentGradient !== particle._currentAngularSpeedGradient) {
  59078. particle._currentAngularSpeed1 = particle._currentAngularSpeed2;
  59079. particle._currentAngularSpeed2 = nextGradient.getFactor();
  59080. particle._currentAngularSpeedGradient = currentGradient;
  59081. }
  59082. particle.angularSpeed = BABYLON.Scalar.Lerp(particle._currentAngularSpeed1, particle._currentAngularSpeed2, scale);
  59083. });
  59084. }
  59085. particle.angle += particle.angularSpeed * scaledUpdateSpeed;
  59086. // Direction
  59087. var directionScale = scaledUpdateSpeed;
  59088. /// Velocity
  59089. if (_this._velocityGradients && _this._velocityGradients.length > 0) {
  59090. BABYLON.Tools.GetCurrentGradient(ratio, _this._velocityGradients, function (currentGradient, nextGradient, scale) {
  59091. if (currentGradient !== particle._currentVelocityGradient) {
  59092. particle._currentVelocity1 = particle._currentVelocity2;
  59093. particle._currentVelocity2 = nextGradient.getFactor();
  59094. particle._currentVelocityGradient = currentGradient;
  59095. }
  59096. directionScale *= BABYLON.Scalar.Lerp(particle._currentVelocity1, particle._currentVelocity2, scale);
  59097. });
  59098. }
  59099. particle.direction.scaleToRef(directionScale, _this._scaledDirection);
  59100. /// Limit velocity
  59101. if (_this._limitVelocityGradients && _this._limitVelocityGradients.length > 0) {
  59102. BABYLON.Tools.GetCurrentGradient(ratio, _this._limitVelocityGradients, function (currentGradient, nextGradient, scale) {
  59103. if (currentGradient !== particle._currentLimitVelocityGradient) {
  59104. particle._currentLimitVelocity1 = particle._currentLimitVelocity2;
  59105. particle._currentLimitVelocity2 = nextGradient.getFactor();
  59106. particle._currentLimitVelocityGradient = currentGradient;
  59107. }
  59108. var limitVelocity = BABYLON.Scalar.Lerp(particle._currentLimitVelocity1, particle._currentLimitVelocity2, scale);
  59109. var currentVelocity = particle.direction.length();
  59110. if (currentVelocity > limitVelocity) {
  59111. particle.direction.scaleInPlace(_this.limitVelocityDamping);
  59112. }
  59113. });
  59114. }
  59115. /// Drag
  59116. if (_this._dragGradients && _this._dragGradients.length > 0) {
  59117. BABYLON.Tools.GetCurrentGradient(ratio, _this._dragGradients, function (currentGradient, nextGradient, scale) {
  59118. if (currentGradient !== particle._currentDragGradient) {
  59119. particle._currentDrag1 = particle._currentDrag2;
  59120. particle._currentDrag2 = nextGradient.getFactor();
  59121. particle._currentDragGradient = currentGradient;
  59122. }
  59123. var drag = BABYLON.Scalar.Lerp(particle._currentDrag1, particle._currentDrag2, scale);
  59124. _this._scaledDirection.scaleInPlace(1.0 - drag);
  59125. });
  59126. }
  59127. particle.position.addInPlace(_this._scaledDirection);
  59128. // Noise
  59129. if (noiseTextureData && noiseTextureSize) {
  59130. var fetchedColorR = _this._fetchR(particle._randomNoiseCoordinates1.x, particle._randomNoiseCoordinates1.y, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  59131. var fetchedColorG = _this._fetchR(particle._randomNoiseCoordinates1.z, particle._randomNoiseCoordinates2.x, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  59132. var fetchedColorB = _this._fetchR(particle._randomNoiseCoordinates2.y, particle._randomNoiseCoordinates2.z, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  59133. var force = BABYLON.Tmp.Vector3[0];
  59134. var scaledForce = BABYLON.Tmp.Vector3[1];
  59135. force.copyFromFloats((2 * fetchedColorR - 1) * _this.noiseStrength.x, (2 * fetchedColorG - 1) * _this.noiseStrength.y, (2 * fetchedColorB - 1) * _this.noiseStrength.z);
  59136. force.scaleToRef(scaledUpdateSpeed, scaledForce);
  59137. particle.direction.addInPlace(scaledForce);
  59138. }
  59139. // Gravity
  59140. _this.gravity.scaleToRef(scaledUpdateSpeed, _this._scaledGravity);
  59141. particle.direction.addInPlace(_this._scaledGravity);
  59142. // Size
  59143. if (_this._sizeGradients && _this._sizeGradients.length > 0) {
  59144. BABYLON.Tools.GetCurrentGradient(ratio, _this._sizeGradients, function (currentGradient, nextGradient, scale) {
  59145. if (currentGradient !== particle._currentSizeGradient) {
  59146. particle._currentSize1 = particle._currentSize2;
  59147. particle._currentSize2 = nextGradient.getFactor();
  59148. particle._currentSizeGradient = currentGradient;
  59149. }
  59150. particle.size = BABYLON.Scalar.Lerp(particle._currentSize1, particle._currentSize2, scale);
  59151. });
  59152. }
  59153. // Remap data
  59154. if (_this._useRampGradients) {
  59155. if (_this._colorRemapGradients && _this._colorRemapGradients.length > 0) {
  59156. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorRemapGradients, function (currentGradient, nextGradient, scale) {
  59157. var min = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  59158. var max = BABYLON.Scalar.Lerp(currentGradient.factor2, nextGradient.factor2, scale);
  59159. particle.remapData.x = min;
  59160. particle.remapData.y = max - min;
  59161. });
  59162. }
  59163. if (_this._alphaRemapGradients && _this._alphaRemapGradients.length > 0) {
  59164. BABYLON.Tools.GetCurrentGradient(ratio, _this._alphaRemapGradients, function (currentGradient, nextGradient, scale) {
  59165. var min = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  59166. var max = BABYLON.Scalar.Lerp(currentGradient.factor2, nextGradient.factor2, scale);
  59167. particle.remapData.z = min;
  59168. particle.remapData.w = max - min;
  59169. });
  59170. }
  59171. }
  59172. if (_this._isAnimationSheetEnabled) {
  59173. particle.updateCellIndex();
  59174. }
  59175. // Update the position of the attached sub-emitters to match their attached particle
  59176. particle._inheritParticleInfoToSubEmitters();
  59177. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  59178. _this._emitFromParticle(particle);
  59179. if (particle._attachedSubEmitters) {
  59180. particle._attachedSubEmitters.forEach(function (subEmitter) {
  59181. subEmitter.particleSystem.disposeOnStop = true;
  59182. subEmitter.particleSystem.stop();
  59183. });
  59184. particle._attachedSubEmitters = null;
  59185. }
  59186. _this.recycleParticle(particle);
  59187. index--;
  59188. return "continue";
  59189. }
  59190. };
  59191. var particle;
  59192. for (var index = 0; index < particles.length; index++) {
  59193. _loop_1();
  59194. }
  59195. };
  59196. return _this;
  59197. }
  59198. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  59199. /**
  59200. * Sets a callback that will be triggered when the system is disposed
  59201. */
  59202. set: function (callback) {
  59203. if (this._onDisposeObserver) {
  59204. this.onDisposeObservable.remove(this._onDisposeObserver);
  59205. }
  59206. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  59207. },
  59208. enumerable: true,
  59209. configurable: true
  59210. });
  59211. Object.defineProperty(ParticleSystem.prototype, "useRampGradients", {
  59212. /** Gets or sets a boolean indicating that ramp gradients must be used
  59213. * @see http://doc.babylonjs.com/babylon101/particles#ramp-gradients
  59214. */
  59215. get: function () {
  59216. return this._useRampGradients;
  59217. },
  59218. set: function (value) {
  59219. if (this._useRampGradients === value) {
  59220. return;
  59221. }
  59222. this._useRampGradients = value;
  59223. this._resetEffect();
  59224. },
  59225. enumerable: true,
  59226. configurable: true
  59227. });
  59228. Object.defineProperty(ParticleSystem.prototype, "particles", {
  59229. //end of Sub-emitter
  59230. /**
  59231. * Gets the current list of active particles
  59232. */
  59233. get: function () {
  59234. return this._particles;
  59235. },
  59236. enumerable: true,
  59237. configurable: true
  59238. });
  59239. /**
  59240. * Returns the string "ParticleSystem"
  59241. * @returns a string containing the class name
  59242. */
  59243. ParticleSystem.prototype.getClassName = function () {
  59244. return "ParticleSystem";
  59245. };
  59246. ParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor, factor2) {
  59247. var newGradient = new BABYLON.FactorGradient();
  59248. newGradient.gradient = gradient;
  59249. newGradient.factor1 = factor;
  59250. newGradient.factor2 = factor2;
  59251. factorGradients.push(newGradient);
  59252. factorGradients.sort(function (a, b) {
  59253. if (a.gradient < b.gradient) {
  59254. return -1;
  59255. }
  59256. else if (a.gradient > b.gradient) {
  59257. return 1;
  59258. }
  59259. return 0;
  59260. });
  59261. };
  59262. ParticleSystem.prototype._removeFactorGradient = function (factorGradients, gradient) {
  59263. if (!factorGradients) {
  59264. return;
  59265. }
  59266. var index = 0;
  59267. for (var _i = 0, factorGradients_1 = factorGradients; _i < factorGradients_1.length; _i++) {
  59268. var factorGradient = factorGradients_1[_i];
  59269. if (factorGradient.gradient === gradient) {
  59270. factorGradients.splice(index, 1);
  59271. break;
  59272. }
  59273. index++;
  59274. }
  59275. };
  59276. /**
  59277. * Adds a new life time gradient
  59278. * @param gradient defines the gradient to use (between 0 and 1)
  59279. * @param factor defines the life time factor to affect to the specified gradient
  59280. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  59281. * @returns the current particle system
  59282. */
  59283. ParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  59284. if (!this._lifeTimeGradients) {
  59285. this._lifeTimeGradients = [];
  59286. }
  59287. this._addFactorGradient(this._lifeTimeGradients, gradient, factor, factor2);
  59288. return this;
  59289. };
  59290. /**
  59291. * Remove a specific life time gradient
  59292. * @param gradient defines the gradient to remove
  59293. * @returns the current particle system
  59294. */
  59295. ParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  59296. this._removeFactorGradient(this._lifeTimeGradients, gradient);
  59297. return this;
  59298. };
  59299. /**
  59300. * Adds a new size gradient
  59301. * @param gradient defines the gradient to use (between 0 and 1)
  59302. * @param factor defines the size factor to affect to the specified gradient
  59303. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  59304. * @returns the current particle system
  59305. */
  59306. ParticleSystem.prototype.addSizeGradient = function (gradient, factor, factor2) {
  59307. if (!this._sizeGradients) {
  59308. this._sizeGradients = [];
  59309. }
  59310. this._addFactorGradient(this._sizeGradients, gradient, factor, factor2);
  59311. return this;
  59312. };
  59313. /**
  59314. * Remove a specific size gradient
  59315. * @param gradient defines the gradient to remove
  59316. * @returns the current particle system
  59317. */
  59318. ParticleSystem.prototype.removeSizeGradient = function (gradient) {
  59319. this._removeFactorGradient(this._sizeGradients, gradient);
  59320. return this;
  59321. };
  59322. /**
  59323. * Adds a new color remap gradient
  59324. * @param gradient defines the gradient to use (between 0 and 1)
  59325. * @param min defines the color remap minimal range
  59326. * @param max defines the color remap maximal range
  59327. * @returns the current particle system
  59328. */
  59329. ParticleSystem.prototype.addColorRemapGradient = function (gradient, min, max) {
  59330. if (!this._colorRemapGradients) {
  59331. this._colorRemapGradients = [];
  59332. }
  59333. this._addFactorGradient(this._colorRemapGradients, gradient, min, max);
  59334. return this;
  59335. };
  59336. /**
  59337. * Remove a specific color remap gradient
  59338. * @param gradient defines the gradient to remove
  59339. * @returns the current particle system
  59340. */
  59341. ParticleSystem.prototype.removeColorRemapGradient = function (gradient) {
  59342. this._removeFactorGradient(this._colorRemapGradients, gradient);
  59343. return this;
  59344. };
  59345. /**
  59346. * Adds a new alpha remap gradient
  59347. * @param gradient defines the gradient to use (between 0 and 1)
  59348. * @param min defines the alpha remap minimal range
  59349. * @param max defines the alpha remap maximal range
  59350. * @returns the current particle system
  59351. */
  59352. ParticleSystem.prototype.addAlphaRemapGradient = function (gradient, min, max) {
  59353. if (!this._alphaRemapGradients) {
  59354. this._alphaRemapGradients = [];
  59355. }
  59356. this._addFactorGradient(this._alphaRemapGradients, gradient, min, max);
  59357. return this;
  59358. };
  59359. /**
  59360. * Remove a specific alpha remap gradient
  59361. * @param gradient defines the gradient to remove
  59362. * @returns the current particle system
  59363. */
  59364. ParticleSystem.prototype.removeAlphaRemapGradient = function (gradient) {
  59365. this._removeFactorGradient(this._alphaRemapGradients, gradient);
  59366. return this;
  59367. };
  59368. /**
  59369. * Adds a new angular speed gradient
  59370. * @param gradient defines the gradient to use (between 0 and 1)
  59371. * @param factor defines the angular speed to affect to the specified gradient
  59372. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  59373. * @returns the current particle system
  59374. */
  59375. ParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor, factor2) {
  59376. if (!this._angularSpeedGradients) {
  59377. this._angularSpeedGradients = [];
  59378. }
  59379. this._addFactorGradient(this._angularSpeedGradients, gradient, factor, factor2);
  59380. return this;
  59381. };
  59382. /**
  59383. * Remove a specific angular speed gradient
  59384. * @param gradient defines the gradient to remove
  59385. * @returns the current particle system
  59386. */
  59387. ParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  59388. this._removeFactorGradient(this._angularSpeedGradients, gradient);
  59389. return this;
  59390. };
  59391. /**
  59392. * Adds a new velocity gradient
  59393. * @param gradient defines the gradient to use (between 0 and 1)
  59394. * @param factor defines the velocity to affect to the specified gradient
  59395. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  59396. * @returns the current particle system
  59397. */
  59398. ParticleSystem.prototype.addVelocityGradient = function (gradient, factor, factor2) {
  59399. if (!this._velocityGradients) {
  59400. this._velocityGradients = [];
  59401. }
  59402. this._addFactorGradient(this._velocityGradients, gradient, factor, factor2);
  59403. return this;
  59404. };
  59405. /**
  59406. * Remove a specific velocity gradient
  59407. * @param gradient defines the gradient to remove
  59408. * @returns the current particle system
  59409. */
  59410. ParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  59411. this._removeFactorGradient(this._velocityGradients, gradient);
  59412. return this;
  59413. };
  59414. /**
  59415. * Adds a new limit velocity gradient
  59416. * @param gradient defines the gradient to use (between 0 and 1)
  59417. * @param factor defines the limit velocity value to affect to the specified gradient
  59418. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  59419. * @returns the current particle system
  59420. */
  59421. ParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor, factor2) {
  59422. if (!this._limitVelocityGradients) {
  59423. this._limitVelocityGradients = [];
  59424. }
  59425. this._addFactorGradient(this._limitVelocityGradients, gradient, factor, factor2);
  59426. return this;
  59427. };
  59428. /**
  59429. * Remove a specific limit velocity gradient
  59430. * @param gradient defines the gradient to remove
  59431. * @returns the current particle system
  59432. */
  59433. ParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  59434. this._removeFactorGradient(this._limitVelocityGradients, gradient);
  59435. return this;
  59436. };
  59437. /**
  59438. * Adds a new drag gradient
  59439. * @param gradient defines the gradient to use (between 0 and 1)
  59440. * @param factor defines the drag value to affect to the specified gradient
  59441. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  59442. * @returns the current particle system
  59443. */
  59444. ParticleSystem.prototype.addDragGradient = function (gradient, factor, factor2) {
  59445. if (!this._dragGradients) {
  59446. this._dragGradients = [];
  59447. }
  59448. this._addFactorGradient(this._dragGradients, gradient, factor, factor2);
  59449. return this;
  59450. };
  59451. /**
  59452. * Remove a specific drag gradient
  59453. * @param gradient defines the gradient to remove
  59454. * @returns the current particle system
  59455. */
  59456. ParticleSystem.prototype.removeDragGradient = function (gradient) {
  59457. this._removeFactorGradient(this._dragGradients, gradient);
  59458. return this;
  59459. };
  59460. /**
  59461. * Adds a new emit rate gradient (please note that this will only work if you set the targetStopDuration property)
  59462. * @param gradient defines the gradient to use (between 0 and 1)
  59463. * @param factor defines the emit rate value to affect to the specified gradient
  59464. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  59465. * @returns the current particle system
  59466. */
  59467. ParticleSystem.prototype.addEmitRateGradient = function (gradient, factor, factor2) {
  59468. if (!this._emitRateGradients) {
  59469. this._emitRateGradients = [];
  59470. }
  59471. this._addFactorGradient(this._emitRateGradients, gradient, factor, factor2);
  59472. return this;
  59473. };
  59474. /**
  59475. * Remove a specific emit rate gradient
  59476. * @param gradient defines the gradient to remove
  59477. * @returns the current particle system
  59478. */
  59479. ParticleSystem.prototype.removeEmitRateGradient = function (gradient) {
  59480. this._removeFactorGradient(this._emitRateGradients, gradient);
  59481. return this;
  59482. };
  59483. /**
  59484. * Adds a new start size gradient (please note that this will only work if you set the targetStopDuration property)
  59485. * @param gradient defines the gradient to use (between 0 and 1)
  59486. * @param factor defines the start size value to affect to the specified gradient
  59487. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  59488. * @returns the current particle system
  59489. */
  59490. ParticleSystem.prototype.addStartSizeGradient = function (gradient, factor, factor2) {
  59491. if (!this._startSizeGradients) {
  59492. this._startSizeGradients = [];
  59493. }
  59494. this._addFactorGradient(this._startSizeGradients, gradient, factor, factor2);
  59495. return this;
  59496. };
  59497. /**
  59498. * Remove a specific start size gradient
  59499. * @param gradient defines the gradient to remove
  59500. * @returns the current particle system
  59501. */
  59502. ParticleSystem.prototype.removeStartSizeGradient = function (gradient) {
  59503. this._removeFactorGradient(this._emitRateGradients, gradient);
  59504. return this;
  59505. };
  59506. ParticleSystem.prototype._createRampGradientTexture = function () {
  59507. if (!this._rampGradients || !this._rampGradients.length || this._rampGradientsTexture) {
  59508. return;
  59509. }
  59510. var data = new Uint8Array(this._rawTextureWidth * 4);
  59511. var tmpColor = BABYLON.Tmp.Color3[0];
  59512. for (var x = 0; x < this._rawTextureWidth; x++) {
  59513. var ratio = x / this._rawTextureWidth;
  59514. BABYLON.Tools.GetCurrentGradient(ratio, this._rampGradients, function (currentGradient, nextGradient, scale) {
  59515. BABYLON.Color3.LerpToRef(currentGradient.color, nextGradient.color, scale, tmpColor);
  59516. data[x * 4] = tmpColor.r * 255;
  59517. data[x * 4 + 1] = tmpColor.g * 255;
  59518. data[x * 4 + 2] = tmpColor.b * 255;
  59519. data[x * 4 + 3] = 255;
  59520. });
  59521. }
  59522. this._rampGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  59523. };
  59524. /**
  59525. * Gets the current list of ramp gradients.
  59526. * You must use addRampGradient and removeRampGradient to udpate this list
  59527. * @returns the list of ramp gradients
  59528. */
  59529. ParticleSystem.prototype.getRampGradients = function () {
  59530. return this._rampGradients;
  59531. };
  59532. /**
  59533. * Adds a new ramp gradient used to remap particle colors
  59534. * @param gradient defines the gradient to use (between 0 and 1)
  59535. * @param color defines the color to affect to the specified gradient
  59536. * @returns the current particle system
  59537. */
  59538. ParticleSystem.prototype.addRampGradient = function (gradient, color) {
  59539. if (!this._rampGradients) {
  59540. this._rampGradients = [];
  59541. }
  59542. var rampGradient = new BABYLON.Color3Gradient();
  59543. rampGradient.gradient = gradient;
  59544. rampGradient.color = color;
  59545. this._rampGradients.push(rampGradient);
  59546. this._rampGradients.sort(function (a, b) {
  59547. if (a.gradient < b.gradient) {
  59548. return -1;
  59549. }
  59550. else if (a.gradient > b.gradient) {
  59551. return 1;
  59552. }
  59553. return 0;
  59554. });
  59555. if (this._rampGradientsTexture) {
  59556. this._rampGradientsTexture.dispose();
  59557. this._rampGradientsTexture = null;
  59558. }
  59559. this._createRampGradientTexture();
  59560. return this;
  59561. };
  59562. /**
  59563. * Remove a specific ramp gradient
  59564. * @param gradient defines the gradient to remove
  59565. * @returns the current particle system
  59566. */
  59567. ParticleSystem.prototype.removeRampGradient = function (gradient) {
  59568. this._removeGradientAndTexture(gradient, this._rampGradients, this._rampGradientsTexture);
  59569. this._rampGradientsTexture = null;
  59570. if (this._rampGradients && this._rampGradients.length > 0) {
  59571. this._createRampGradientTexture();
  59572. }
  59573. return this;
  59574. };
  59575. /**
  59576. * Adds a new color gradient
  59577. * @param gradient defines the gradient to use (between 0 and 1)
  59578. * @param color1 defines the color to affect to the specified gradient
  59579. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  59580. * @returns this particle system
  59581. */
  59582. ParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  59583. if (!this._colorGradients) {
  59584. this._colorGradients = [];
  59585. }
  59586. var colorGradient = new BABYLON.ColorGradient();
  59587. colorGradient.gradient = gradient;
  59588. colorGradient.color1 = color1;
  59589. colorGradient.color2 = color2;
  59590. this._colorGradients.push(colorGradient);
  59591. this._colorGradients.sort(function (a, b) {
  59592. if (a.gradient < b.gradient) {
  59593. return -1;
  59594. }
  59595. else if (a.gradient > b.gradient) {
  59596. return 1;
  59597. }
  59598. return 0;
  59599. });
  59600. return this;
  59601. };
  59602. /**
  59603. * Remove a specific color gradient
  59604. * @param gradient defines the gradient to remove
  59605. * @returns this particle system
  59606. */
  59607. ParticleSystem.prototype.removeColorGradient = function (gradient) {
  59608. if (!this._colorGradients) {
  59609. return this;
  59610. }
  59611. var index = 0;
  59612. for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
  59613. var colorGradient = _a[_i];
  59614. if (colorGradient.gradient === gradient) {
  59615. this._colorGradients.splice(index, 1);
  59616. break;
  59617. }
  59618. index++;
  59619. }
  59620. return this;
  59621. };
  59622. ParticleSystem.prototype._fetchR = function (u, v, width, height, pixels) {
  59623. u = Math.abs(u) * 0.5 + 0.5;
  59624. v = Math.abs(v) * 0.5 + 0.5;
  59625. var wrappedU = ((u * width) % width) | 0;
  59626. var wrappedV = ((v * height) % height) | 0;
  59627. var position = (wrappedU + wrappedV * width) * 4;
  59628. return pixels[position] / 255;
  59629. };
  59630. ParticleSystem.prototype._reset = function () {
  59631. this._resetEffect();
  59632. };
  59633. ParticleSystem.prototype._resetEffect = function () {
  59634. if (this._vertexBuffer) {
  59635. this._vertexBuffer.dispose();
  59636. this._vertexBuffer = null;
  59637. }
  59638. if (this._spriteBuffer) {
  59639. this._spriteBuffer.dispose();
  59640. this._spriteBuffer = null;
  59641. }
  59642. this._createVertexBuffers();
  59643. };
  59644. ParticleSystem.prototype._createVertexBuffers = function () {
  59645. this._vertexBufferSize = this._useInstancing ? 10 : 12;
  59646. if (this._isAnimationSheetEnabled) {
  59647. this._vertexBufferSize += 1;
  59648. }
  59649. if (!this._isBillboardBased || this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  59650. this._vertexBufferSize += 3;
  59651. }
  59652. if (this._useRampGradients) {
  59653. this._vertexBufferSize += 4;
  59654. }
  59655. var engine = this._scene.getEngine();
  59656. this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
  59657. this._vertexBuffer = new BABYLON.Buffer(engine, this._vertexData, true, this._vertexBufferSize);
  59658. var dataOffset = 0;
  59659. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  59660. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  59661. dataOffset += 3;
  59662. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  59663. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  59664. dataOffset += 4;
  59665. var options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  59666. this._vertexBuffers["angle"] = options;
  59667. dataOffset += 1;
  59668. var size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  59669. this._vertexBuffers["size"] = size;
  59670. dataOffset += 2;
  59671. if (this._isAnimationSheetEnabled) {
  59672. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  59673. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  59674. dataOffset += 1;
  59675. }
  59676. if (!this._isBillboardBased || this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  59677. var directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  59678. this._vertexBuffers["direction"] = directionBuffer;
  59679. dataOffset += 3;
  59680. }
  59681. if (this._useRampGradients) {
  59682. var rampDataBuffer = this._vertexBuffer.createVertexBuffer("remapData", dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  59683. this._vertexBuffers["remapData"] = rampDataBuffer;
  59684. dataOffset += 4;
  59685. }
  59686. var offsets;
  59687. if (this._useInstancing) {
  59688. var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
  59689. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 2);
  59690. offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2);
  59691. }
  59692. else {
  59693. offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  59694. dataOffset += 2;
  59695. }
  59696. this._vertexBuffers["offset"] = offsets;
  59697. };
  59698. ParticleSystem.prototype._createIndexBuffer = function () {
  59699. if (this._useInstancing) {
  59700. return;
  59701. }
  59702. var indices = [];
  59703. var index = 0;
  59704. for (var count = 0; count < this._capacity; count++) {
  59705. indices.push(index);
  59706. indices.push(index + 1);
  59707. indices.push(index + 2);
  59708. indices.push(index);
  59709. indices.push(index + 2);
  59710. indices.push(index + 3);
  59711. index += 4;
  59712. }
  59713. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  59714. };
  59715. /**
  59716. * Gets the maximum number of particles active at the same time.
  59717. * @returns The max number of active particles.
  59718. */
  59719. ParticleSystem.prototype.getCapacity = function () {
  59720. return this._capacity;
  59721. };
  59722. /**
  59723. * Gets whether there are still active particles in the system.
  59724. * @returns True if it is alive, otherwise false.
  59725. */
  59726. ParticleSystem.prototype.isAlive = function () {
  59727. return this._alive;
  59728. };
  59729. /**
  59730. * Gets if the system has been started. (Note: this will still be true after stop is called)
  59731. * @returns True if it has been started, otherwise false.
  59732. */
  59733. ParticleSystem.prototype.isStarted = function () {
  59734. return this._started;
  59735. };
  59736. ParticleSystem.prototype._prepareSubEmitterInternalArray = function () {
  59737. var _this = this;
  59738. this._subEmitters = new Array();
  59739. if (this.subEmitters) {
  59740. this.subEmitters.forEach(function (subEmitter) {
  59741. if (subEmitter instanceof ParticleSystem) {
  59742. _this._subEmitters.push([new BABYLON.SubEmitter(subEmitter)]);
  59743. }
  59744. else if (subEmitter instanceof BABYLON.SubEmitter) {
  59745. _this._subEmitters.push([subEmitter]);
  59746. }
  59747. else if (subEmitter instanceof Array) {
  59748. _this._subEmitters.push(subEmitter);
  59749. }
  59750. });
  59751. }
  59752. };
  59753. /**
  59754. * Starts the particle system and begins to emit
  59755. * @param delay defines the delay in milliseconds before starting the system (this.startDelay by default)
  59756. */
  59757. ParticleSystem.prototype.start = function (delay) {
  59758. var _this = this;
  59759. if (delay === void 0) { delay = this.startDelay; }
  59760. if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) {
  59761. throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";
  59762. }
  59763. if (delay) {
  59764. setTimeout(function () {
  59765. _this.start(0);
  59766. }, delay);
  59767. return;
  59768. }
  59769. // Convert the subEmitters field to the constant type field _subEmitters
  59770. this._prepareSubEmitterInternalArray();
  59771. this._started = true;
  59772. this._stopped = false;
  59773. this._actualFrame = 0;
  59774. if (this._subEmitters && this._subEmitters.length != 0) {
  59775. this.activeSubSystems = new Array();
  59776. }
  59777. // Reset emit gradient so it acts the same on every start
  59778. if (this._emitRateGradients) {
  59779. if (this._emitRateGradients.length > 0) {
  59780. this._currentEmitRateGradient = this._emitRateGradients[0];
  59781. this._currentEmitRate1 = this._currentEmitRateGradient.getFactor();
  59782. this._currentEmitRate2 = this._currentEmitRate1;
  59783. }
  59784. if (this._emitRateGradients.length > 1) {
  59785. this._currentEmitRate2 = this._emitRateGradients[1].getFactor();
  59786. }
  59787. }
  59788. // Reset start size gradient so it acts the same on every start
  59789. if (this._startSizeGradients) {
  59790. if (this._startSizeGradients.length > 0) {
  59791. this._currentStartSizeGradient = this._startSizeGradients[0];
  59792. this._currentStartSize1 = this._currentStartSizeGradient.getFactor();
  59793. this._currentStartSize2 = this._currentStartSize1;
  59794. }
  59795. if (this._startSizeGradients.length > 1) {
  59796. this._currentStartSize2 = this._startSizeGradients[1].getFactor();
  59797. }
  59798. }
  59799. if (this.preWarmCycles) {
  59800. if (this.emitter instanceof BABYLON.AbstractMesh) {
  59801. this.emitter.computeWorldMatrix(true);
  59802. }
  59803. var noiseTextureAsProcedural_1 = this.noiseTexture;
  59804. if (noiseTextureAsProcedural_1 && noiseTextureAsProcedural_1.onGeneratedObservable) {
  59805. noiseTextureAsProcedural_1.onGeneratedObservable.addOnce(function () {
  59806. setTimeout(function () {
  59807. for (var index = 0; index < _this.preWarmCycles; index++) {
  59808. _this.animate(true);
  59809. noiseTextureAsProcedural_1.render();
  59810. }
  59811. });
  59812. });
  59813. }
  59814. else {
  59815. for (var index = 0; index < this.preWarmCycles; index++) {
  59816. this.animate(true);
  59817. }
  59818. }
  59819. }
  59820. // Animations
  59821. if (this.beginAnimationOnStart && this.animations && this.animations.length > 0) {
  59822. this.getScene().beginAnimation(this, this.beginAnimationFrom, this.beginAnimationTo, this.beginAnimationLoop);
  59823. }
  59824. };
  59825. /**
  59826. * Stops the particle system.
  59827. * @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.
  59828. */
  59829. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  59830. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  59831. this._stopped = true;
  59832. if (stopSubEmitters) {
  59833. this._stopSubEmitters();
  59834. }
  59835. };
  59836. // animation sheet
  59837. /**
  59838. * Remove all active particles
  59839. */
  59840. ParticleSystem.prototype.reset = function () {
  59841. this._stockParticles = [];
  59842. this._particles = [];
  59843. };
  59844. /**
  59845. * @hidden (for internal use only)
  59846. */
  59847. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  59848. var offset = index * this._vertexBufferSize;
  59849. this._vertexData[offset++] = particle.position.x;
  59850. this._vertexData[offset++] = particle.position.y;
  59851. this._vertexData[offset++] = particle.position.z;
  59852. this._vertexData[offset++] = particle.color.r;
  59853. this._vertexData[offset++] = particle.color.g;
  59854. this._vertexData[offset++] = particle.color.b;
  59855. this._vertexData[offset++] = particle.color.a;
  59856. this._vertexData[offset++] = particle.angle;
  59857. this._vertexData[offset++] = particle.scale.x * particle.size;
  59858. this._vertexData[offset++] = particle.scale.y * particle.size;
  59859. if (this._isAnimationSheetEnabled) {
  59860. this._vertexData[offset++] = particle.cellIndex;
  59861. }
  59862. if (!this._isBillboardBased) {
  59863. if (particle._initialDirection) {
  59864. this._vertexData[offset++] = particle._initialDirection.x;
  59865. this._vertexData[offset++] = particle._initialDirection.y;
  59866. this._vertexData[offset++] = particle._initialDirection.z;
  59867. }
  59868. else {
  59869. this._vertexData[offset++] = particle.direction.x;
  59870. this._vertexData[offset++] = particle.direction.y;
  59871. this._vertexData[offset++] = particle.direction.z;
  59872. }
  59873. }
  59874. else if (this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  59875. this._vertexData[offset++] = particle.direction.x;
  59876. this._vertexData[offset++] = particle.direction.y;
  59877. this._vertexData[offset++] = particle.direction.z;
  59878. }
  59879. if (this._useRampGradients) {
  59880. this._vertexData[offset++] = particle.remapData.x;
  59881. this._vertexData[offset++] = particle.remapData.y;
  59882. this._vertexData[offset++] = particle.remapData.z;
  59883. this._vertexData[offset++] = particle.remapData.w;
  59884. }
  59885. if (!this._useInstancing) {
  59886. if (this._isAnimationSheetEnabled) {
  59887. if (offsetX === 0)
  59888. offsetX = this._epsilon;
  59889. else if (offsetX === 1)
  59890. offsetX = 1 - this._epsilon;
  59891. if (offsetY === 0)
  59892. offsetY = this._epsilon;
  59893. else if (offsetY === 1)
  59894. offsetY = 1 - this._epsilon;
  59895. }
  59896. this._vertexData[offset++] = offsetX;
  59897. this._vertexData[offset++] = offsetY;
  59898. }
  59899. };
  59900. ParticleSystem.prototype._stopSubEmitters = function () {
  59901. if (!this.activeSubSystems) {
  59902. return;
  59903. }
  59904. this.activeSubSystems.forEach(function (subSystem) {
  59905. subSystem.stop(true);
  59906. });
  59907. this.activeSubSystems = new Array();
  59908. };
  59909. ParticleSystem.prototype._removeFromRoot = function () {
  59910. if (!this._rootParticleSystem) {
  59911. return;
  59912. }
  59913. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  59914. if (index !== -1) {
  59915. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  59916. }
  59917. this._rootParticleSystem = null;
  59918. };
  59919. // End of sub system methods
  59920. ParticleSystem.prototype._update = function (newParticles) {
  59921. var _this = this;
  59922. // Update current
  59923. this._alive = this._particles.length > 0;
  59924. if (this.emitter.position) {
  59925. var emitterMesh = this.emitter;
  59926. this._emitterWorldMatrix = emitterMesh.getWorldMatrix();
  59927. }
  59928. else {
  59929. var emitterPosition = this.emitter;
  59930. this._emitterWorldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  59931. }
  59932. this.updateFunction(this._particles);
  59933. // Add new ones
  59934. var particle;
  59935. var _loop_2 = function () {
  59936. if (this_1._particles.length === this_1._capacity) {
  59937. return "break";
  59938. }
  59939. particle = this_1._createParticle();
  59940. this_1._particles.push(particle);
  59941. // Emitter
  59942. var emitPower = BABYLON.Scalar.RandomRange(this_1.minEmitPower, this_1.maxEmitPower);
  59943. if (this_1.startPositionFunction) {
  59944. this_1.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  59945. }
  59946. else {
  59947. this_1.particleEmitterType.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  59948. }
  59949. if (this_1.startDirectionFunction) {
  59950. this_1.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  59951. }
  59952. else {
  59953. this_1.particleEmitterType.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  59954. }
  59955. if (emitPower === 0) {
  59956. if (!particle._initialDirection) {
  59957. particle._initialDirection = particle.direction.clone();
  59958. }
  59959. else {
  59960. particle._initialDirection.copyFrom(particle.direction);
  59961. }
  59962. }
  59963. else {
  59964. particle._initialDirection = null;
  59965. }
  59966. particle.direction.scaleInPlace(emitPower);
  59967. // Life time
  59968. if (this_1.targetStopDuration && this_1._lifeTimeGradients && this_1._lifeTimeGradients.length > 0) {
  59969. var ratio_1 = BABYLON.Scalar.Clamp(this_1._actualFrame / this_1.targetStopDuration);
  59970. BABYLON.Tools.GetCurrentGradient(ratio_1, this_1._lifeTimeGradients, function (currentGradient, nextGradient, scale) {
  59971. var factorGradient1 = currentGradient;
  59972. var factorGradient2 = nextGradient;
  59973. var lifeTime1 = factorGradient1.getFactor();
  59974. var lifeTime2 = factorGradient2.getFactor();
  59975. var gradient = (ratio_1 - factorGradient1.gradient) / (factorGradient2.gradient - factorGradient1.gradient);
  59976. particle.lifeTime = BABYLON.Scalar.Lerp(lifeTime1, lifeTime2, gradient);
  59977. });
  59978. }
  59979. else {
  59980. particle.lifeTime = BABYLON.Scalar.RandomRange(this_1.minLifeTime, this_1.maxLifeTime);
  59981. }
  59982. // Size
  59983. if (!this_1._sizeGradients || this_1._sizeGradients.length === 0) {
  59984. particle.size = BABYLON.Scalar.RandomRange(this_1.minSize, this_1.maxSize);
  59985. }
  59986. else {
  59987. particle._currentSizeGradient = this_1._sizeGradients[0];
  59988. particle._currentSize1 = particle._currentSizeGradient.getFactor();
  59989. particle.size = particle._currentSize1;
  59990. if (this_1._sizeGradients.length > 1) {
  59991. particle._currentSize2 = this_1._sizeGradients[1].getFactor();
  59992. }
  59993. else {
  59994. particle._currentSize2 = particle._currentSize1;
  59995. }
  59996. }
  59997. // Size and scale
  59998. particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this_1.minScaleX, this_1.maxScaleX), BABYLON.Scalar.RandomRange(this_1.minScaleY, this_1.maxScaleY));
  59999. // Adjust scale by start size
  60000. if (this_1._startSizeGradients && this_1._startSizeGradients[0] && this_1.targetStopDuration) {
  60001. var ratio = this_1._actualFrame / this_1.targetStopDuration;
  60002. BABYLON.Tools.GetCurrentGradient(ratio, this_1._startSizeGradients, function (currentGradient, nextGradient, scale) {
  60003. if (currentGradient !== _this._currentStartSizeGradient) {
  60004. _this._currentStartSize1 = _this._currentStartSize2;
  60005. _this._currentStartSize2 = nextGradient.getFactor();
  60006. _this._currentStartSizeGradient = currentGradient;
  60007. }
  60008. var value = BABYLON.Scalar.Lerp(_this._currentStartSize1, _this._currentStartSize2, scale);
  60009. particle.scale.scaleInPlace(value);
  60010. });
  60011. }
  60012. // Angle
  60013. if (!this_1._angularSpeedGradients || this_1._angularSpeedGradients.length === 0) {
  60014. particle.angularSpeed = BABYLON.Scalar.RandomRange(this_1.minAngularSpeed, this_1.maxAngularSpeed);
  60015. }
  60016. else {
  60017. particle._currentAngularSpeedGradient = this_1._angularSpeedGradients[0];
  60018. particle.angularSpeed = particle._currentAngularSpeedGradient.getFactor();
  60019. particle._currentAngularSpeed1 = particle.angularSpeed;
  60020. if (this_1._angularSpeedGradients.length > 1) {
  60021. particle._currentAngularSpeed2 = this_1._angularSpeedGradients[1].getFactor();
  60022. }
  60023. else {
  60024. particle._currentAngularSpeed2 = particle._currentAngularSpeed1;
  60025. }
  60026. }
  60027. particle.angle = BABYLON.Scalar.RandomRange(this_1.minInitialRotation, this_1.maxInitialRotation);
  60028. // Velocity
  60029. if (this_1._velocityGradients && this_1._velocityGradients.length > 0) {
  60030. particle._currentVelocityGradient = this_1._velocityGradients[0];
  60031. particle._currentVelocity1 = particle._currentVelocityGradient.getFactor();
  60032. if (this_1._velocityGradients.length > 1) {
  60033. particle._currentVelocity2 = this_1._velocityGradients[1].getFactor();
  60034. }
  60035. else {
  60036. particle._currentVelocity2 = particle._currentVelocity1;
  60037. }
  60038. }
  60039. // Limit velocity
  60040. if (this_1._limitVelocityGradients && this_1._limitVelocityGradients.length > 0) {
  60041. particle._currentLimitVelocityGradient = this_1._limitVelocityGradients[0];
  60042. particle._currentLimitVelocity1 = particle._currentLimitVelocityGradient.getFactor();
  60043. if (this_1._limitVelocityGradients.length > 1) {
  60044. particle._currentLimitVelocity2 = this_1._limitVelocityGradients[1].getFactor();
  60045. }
  60046. else {
  60047. particle._currentLimitVelocity2 = particle._currentLimitVelocity1;
  60048. }
  60049. }
  60050. // Drag
  60051. if (this_1._dragGradients && this_1._dragGradients.length > 0) {
  60052. particle._currentDragGradient = this_1._dragGradients[0];
  60053. particle._currentDrag1 = particle._currentDragGradient.getFactor();
  60054. if (this_1._dragGradients.length > 1) {
  60055. particle._currentDrag2 = this_1._dragGradients[1].getFactor();
  60056. }
  60057. else {
  60058. particle._currentDrag2 = particle._currentDrag1;
  60059. }
  60060. }
  60061. // Color
  60062. if (!this_1._colorGradients || this_1._colorGradients.length === 0) {
  60063. step = BABYLON.Scalar.RandomRange(0, 1.0);
  60064. BABYLON.Color4.LerpToRef(this_1.color1, this_1.color2, step, particle.color);
  60065. this_1.colorDead.subtractToRef(particle.color, this_1._colorDiff);
  60066. this_1._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  60067. }
  60068. else {
  60069. particle._currentColorGradient = this_1._colorGradients[0];
  60070. particle._currentColorGradient.getColorToRef(particle.color);
  60071. particle._currentColor1.copyFrom(particle.color);
  60072. if (this_1._colorGradients.length > 1) {
  60073. this_1._colorGradients[1].getColorToRef(particle._currentColor2);
  60074. }
  60075. else {
  60076. particle._currentColor2.copyFrom(particle.color);
  60077. }
  60078. }
  60079. // Sheet
  60080. if (this_1._isAnimationSheetEnabled) {
  60081. particle._initialStartSpriteCellID = this_1.startSpriteCellID;
  60082. particle._initialEndSpriteCellID = this_1.endSpriteCellID;
  60083. }
  60084. // Inherited Velocity
  60085. particle.direction.addInPlace(this_1._inheritedVelocityOffset);
  60086. // Ramp
  60087. if (this_1._useRampGradients) {
  60088. particle.remapData = new BABYLON.Vector4(0, 1, 0, 1);
  60089. }
  60090. // Noise texture coordinates
  60091. if (this_1.noiseTexture) {
  60092. if (particle._randomNoiseCoordinates1) {
  60093. particle._randomNoiseCoordinates1.copyFromFloats(Math.random(), Math.random(), Math.random());
  60094. particle._randomNoiseCoordinates2.copyFromFloats(Math.random(), Math.random(), Math.random());
  60095. }
  60096. else {
  60097. particle._randomNoiseCoordinates1 = new BABYLON.Vector3(Math.random(), Math.random(), Math.random());
  60098. particle._randomNoiseCoordinates2 = new BABYLON.Vector3(Math.random(), Math.random(), Math.random());
  60099. }
  60100. }
  60101. // Update the position of the attached sub-emitters to match their attached particle
  60102. particle._inheritParticleInfoToSubEmitters();
  60103. };
  60104. var this_1 = this, step;
  60105. for (var index = 0; index < newParticles; index++) {
  60106. var state_1 = _loop_2();
  60107. if (state_1 === "break")
  60108. break;
  60109. }
  60110. };
  60111. /** @hidden */
  60112. ParticleSystem._GetAttributeNamesOrOptions = function (isAnimationSheetEnabled, isBillboardBased, useRampGradients) {
  60113. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  60114. if (isBillboardBased === void 0) { isBillboardBased = false; }
  60115. if (useRampGradients === void 0) { useRampGradients = false; }
  60116. var attributeNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "angle", "offset", "size"];
  60117. if (isAnimationSheetEnabled) {
  60118. attributeNamesOrOptions.push("cellIndex");
  60119. }
  60120. if (!isBillboardBased) {
  60121. attributeNamesOrOptions.push("direction");
  60122. }
  60123. if (useRampGradients) {
  60124. attributeNamesOrOptions.push("remapData");
  60125. }
  60126. return attributeNamesOrOptions;
  60127. };
  60128. /** @hidden */
  60129. ParticleSystem._GetEffectCreationOptions = function (isAnimationSheetEnabled) {
  60130. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  60131. var effectCreationOption = ["invView", "view", "projection", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "textureMask", "translationPivot", "eyePosition"];
  60132. if (isAnimationSheetEnabled) {
  60133. effectCreationOption.push("particlesInfos");
  60134. }
  60135. return effectCreationOption;
  60136. };
  60137. /** @hidden */
  60138. ParticleSystem.prototype._getEffect = function (blendMode) {
  60139. if (this._customEffect) {
  60140. return this._customEffect;
  60141. }
  60142. ;
  60143. var defines = [];
  60144. if (this._scene.clipPlane) {
  60145. defines.push("#define CLIPPLANE");
  60146. }
  60147. if (this._scene.clipPlane2) {
  60148. defines.push("#define CLIPPLANE2");
  60149. }
  60150. if (this._scene.clipPlane3) {
  60151. defines.push("#define CLIPPLANE3");
  60152. }
  60153. if (this._scene.clipPlane4) {
  60154. defines.push("#define CLIPPLANE4");
  60155. }
  60156. if (this._isAnimationSheetEnabled) {
  60157. defines.push("#define ANIMATESHEET");
  60158. }
  60159. if (blendMode === ParticleSystem.BLENDMODE_MULTIPLY) {
  60160. defines.push("#define BLENDMULTIPLYMODE");
  60161. }
  60162. if (this._useRampGradients) {
  60163. defines.push("#define RAMPGRADIENT");
  60164. }
  60165. if (this._isBillboardBased) {
  60166. defines.push("#define BILLBOARD");
  60167. switch (this.billboardMode) {
  60168. case ParticleSystem.BILLBOARDMODE_Y:
  60169. defines.push("#define BILLBOARDY");
  60170. break;
  60171. case ParticleSystem.BILLBOARDMODE_STRETCHED:
  60172. defines.push("#define BILLBOARDSTRETCHED");
  60173. break;
  60174. case ParticleSystem.BILLBOARDMODE_ALL:
  60175. default:
  60176. break;
  60177. }
  60178. }
  60179. if (this._imageProcessingConfiguration) {
  60180. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  60181. defines.push(this._imageProcessingConfigurationDefines.toString());
  60182. }
  60183. // Effect
  60184. var join = defines.join("\n");
  60185. if (this._cachedDefines !== join) {
  60186. this._cachedDefines = join;
  60187. var attributesNamesOrOptions = ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased && this.billboardMode !== ParticleSystem.BILLBOARDMODE_STRETCHED, this._useRampGradients);
  60188. var effectCreationOption = ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled);
  60189. var samplers = ["diffuseSampler", "rampSampler"];
  60190. if (BABYLON.ImageProcessingConfiguration) {
  60191. BABYLON.ImageProcessingConfiguration.PrepareUniforms(effectCreationOption, this._imageProcessingConfigurationDefines);
  60192. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  60193. }
  60194. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, samplers, join);
  60195. }
  60196. return this._effect;
  60197. };
  60198. /**
  60199. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  60200. * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)
  60201. */
  60202. ParticleSystem.prototype.animate = function (preWarmOnly) {
  60203. var _this = this;
  60204. if (preWarmOnly === void 0) { preWarmOnly = false; }
  60205. if (!this._started)
  60206. return;
  60207. if (!preWarmOnly) {
  60208. // Check
  60209. if (!this.isReady())
  60210. return;
  60211. if (this._currentRenderId === this._scene.getRenderId()) {
  60212. return;
  60213. }
  60214. this._currentRenderId = this._scene.getRenderId();
  60215. }
  60216. this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  60217. // Determine the number of particles we need to create
  60218. var newParticles;
  60219. if (this.manualEmitCount > -1) {
  60220. newParticles = this.manualEmitCount;
  60221. this._newPartsExcess = 0;
  60222. this.manualEmitCount = 0;
  60223. }
  60224. else {
  60225. var rate_1 = this.emitRate;
  60226. if (this._emitRateGradients && this._emitRateGradients.length > 0 && this.targetStopDuration) {
  60227. var ratio = this._actualFrame / this.targetStopDuration;
  60228. BABYLON.Tools.GetCurrentGradient(ratio, this._emitRateGradients, function (currentGradient, nextGradient, scale) {
  60229. if (currentGradient !== _this._currentEmitRateGradient) {
  60230. _this._currentEmitRate1 = _this._currentEmitRate2;
  60231. _this._currentEmitRate2 = nextGradient.getFactor();
  60232. _this._currentEmitRateGradient = currentGradient;
  60233. }
  60234. rate_1 = BABYLON.Scalar.Lerp(_this._currentEmitRate1, _this._currentEmitRate2, scale);
  60235. });
  60236. }
  60237. newParticles = ((rate_1 * this._scaledUpdateSpeed) >> 0);
  60238. this._newPartsExcess += rate_1 * this._scaledUpdateSpeed - newParticles;
  60239. }
  60240. if (this._newPartsExcess > 1.0) {
  60241. newParticles += this._newPartsExcess >> 0;
  60242. this._newPartsExcess -= this._newPartsExcess >> 0;
  60243. }
  60244. this._alive = false;
  60245. if (!this._stopped) {
  60246. this._actualFrame += this._scaledUpdateSpeed;
  60247. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  60248. this.stop();
  60249. }
  60250. else {
  60251. newParticles = 0;
  60252. }
  60253. this._update(newParticles);
  60254. // Stopped?
  60255. if (this._stopped) {
  60256. if (!this._alive) {
  60257. this._started = false;
  60258. if (this.onAnimationEnd) {
  60259. this.onAnimationEnd();
  60260. }
  60261. if (this.disposeOnStop) {
  60262. this._scene._toBeDisposed.push(this);
  60263. }
  60264. }
  60265. }
  60266. if (!preWarmOnly) {
  60267. // Update VBO
  60268. var offset = 0;
  60269. for (var index = 0; index < this._particles.length; index++) {
  60270. var particle = this._particles[index];
  60271. this._appendParticleVertices(offset, particle);
  60272. offset += this._useInstancing ? 1 : 4;
  60273. }
  60274. if (this._vertexBuffer) {
  60275. this._vertexBuffer.update(this._vertexData);
  60276. }
  60277. }
  60278. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  60279. this.stop();
  60280. }
  60281. };
  60282. ParticleSystem.prototype._appendParticleVertices = function (offset, particle) {
  60283. this._appendParticleVertex(offset++, particle, 0, 0);
  60284. if (!this._useInstancing) {
  60285. this._appendParticleVertex(offset++, particle, 1, 0);
  60286. this._appendParticleVertex(offset++, particle, 1, 1);
  60287. this._appendParticleVertex(offset++, particle, 0, 1);
  60288. }
  60289. };
  60290. /**
  60291. * Rebuilds the particle system.
  60292. */
  60293. ParticleSystem.prototype.rebuild = function () {
  60294. this._createIndexBuffer();
  60295. if (this._vertexBuffer) {
  60296. this._vertexBuffer._rebuild();
  60297. }
  60298. };
  60299. /**
  60300. * Is this system ready to be used/rendered
  60301. * @return true if the system is ready
  60302. */
  60303. ParticleSystem.prototype.isReady = function () {
  60304. if (!this.emitter || !this._imageProcessingConfiguration.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  60305. return false;
  60306. }
  60307. if (this.blendMode !== ParticleSystem.BLENDMODE_MULTIPLYADD) {
  60308. if (!this._getEffect(this.blendMode).isReady()) {
  60309. return false;
  60310. }
  60311. }
  60312. else {
  60313. if (!this._getEffect(ParticleSystem.BLENDMODE_MULTIPLY).isReady()) {
  60314. return false;
  60315. }
  60316. if (!this._getEffect(ParticleSystem.BLENDMODE_ADD).isReady()) {
  60317. return false;
  60318. }
  60319. }
  60320. return true;
  60321. };
  60322. ParticleSystem.prototype._render = function (blendMode) {
  60323. var effect = this._getEffect(blendMode);
  60324. var engine = this._scene.getEngine();
  60325. // Render
  60326. engine.enableEffect(effect);
  60327. var viewMatrix = this._scene.getViewMatrix();
  60328. effect.setTexture("diffuseSampler", this.particleTexture);
  60329. effect.setMatrix("view", viewMatrix);
  60330. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  60331. if (this._isAnimationSheetEnabled && this.particleTexture) {
  60332. var baseSize = this.particleTexture.getBaseSize();
  60333. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  60334. }
  60335. effect.setVector2("translationPivot", this.translationPivot);
  60336. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  60337. if (this._isBillboardBased) {
  60338. var camera = this._scene.activeCamera;
  60339. effect.setVector3("eyePosition", camera.globalPosition);
  60340. }
  60341. if (this._rampGradientsTexture) {
  60342. effect.setTexture("rampSampler", this._rampGradientsTexture);
  60343. }
  60344. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  60345. var invView = viewMatrix.clone();
  60346. invView.invert();
  60347. effect.setMatrix("invView", invView);
  60348. BABYLON.MaterialHelper.BindClipPlane(effect, this._scene);
  60349. }
  60350. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  60351. // image processing
  60352. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  60353. this._imageProcessingConfiguration.bind(effect);
  60354. }
  60355. // Draw order
  60356. switch (blendMode) {
  60357. case ParticleSystem.BLENDMODE_ADD:
  60358. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  60359. break;
  60360. case ParticleSystem.BLENDMODE_ONEONE:
  60361. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  60362. break;
  60363. case ParticleSystem.BLENDMODE_STANDARD:
  60364. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  60365. break;
  60366. case ParticleSystem.BLENDMODE_MULTIPLY:
  60367. engine.setAlphaMode(BABYLON.Engine.ALPHA_MULTIPLY);
  60368. break;
  60369. }
  60370. if (this._useInstancing) {
  60371. engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._particles.length);
  60372. }
  60373. else {
  60374. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  60375. }
  60376. return this._particles.length;
  60377. };
  60378. /**
  60379. * Renders the particle system in its current state.
  60380. * @returns the current number of particles
  60381. */
  60382. ParticleSystem.prototype.render = function () {
  60383. // Check
  60384. if (!this.isReady() || !this._particles.length) {
  60385. return 0;
  60386. }
  60387. var engine = this._scene.getEngine();
  60388. engine.setState(false);
  60389. if (this.forceDepthWrite) {
  60390. engine.setDepthWrite(true);
  60391. }
  60392. var outparticles = 0;
  60393. if (this.blendMode === ParticleSystem.BLENDMODE_MULTIPLYADD) {
  60394. outparticles = this._render(ParticleSystem.BLENDMODE_MULTIPLY) + this._render(ParticleSystem.BLENDMODE_ADD);
  60395. }
  60396. outparticles = this._render(this.blendMode);
  60397. engine.unbindInstanceAttributes();
  60398. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  60399. return outparticles;
  60400. };
  60401. /**
  60402. * Disposes the particle system and free the associated resources
  60403. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  60404. */
  60405. ParticleSystem.prototype.dispose = function (disposeTexture) {
  60406. if (disposeTexture === void 0) { disposeTexture = true; }
  60407. if (this._vertexBuffer) {
  60408. this._vertexBuffer.dispose();
  60409. this._vertexBuffer = null;
  60410. }
  60411. if (this._spriteBuffer) {
  60412. this._spriteBuffer.dispose();
  60413. this._spriteBuffer = null;
  60414. }
  60415. if (this._indexBuffer) {
  60416. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  60417. this._indexBuffer = null;
  60418. }
  60419. if (disposeTexture && this.particleTexture) {
  60420. this.particleTexture.dispose();
  60421. this.particleTexture = null;
  60422. }
  60423. if (disposeTexture && this.noiseTexture) {
  60424. this.noiseTexture.dispose();
  60425. this.noiseTexture = null;
  60426. }
  60427. if (this._rampGradientsTexture) {
  60428. this._rampGradientsTexture.dispose();
  60429. this._rampGradientsTexture = null;
  60430. }
  60431. this._removeFromRoot();
  60432. if (this._subEmitters && this._subEmitters.length) {
  60433. for (var index = 0; index < this._subEmitters.length; index++) {
  60434. for (var _i = 0, _a = this._subEmitters[index]; _i < _a.length; _i++) {
  60435. var subEmitter = _a[_i];
  60436. subEmitter.dispose();
  60437. }
  60438. }
  60439. this._subEmitters = [];
  60440. this.subEmitters = [];
  60441. }
  60442. if (this._disposeEmitterOnDispose && this.emitter && this.emitter.dispose) {
  60443. this.emitter.dispose(true);
  60444. }
  60445. // Remove from scene
  60446. var index = this._scene.particleSystems.indexOf(this);
  60447. if (index > -1) {
  60448. this._scene.particleSystems.splice(index, 1);
  60449. }
  60450. this._scene._activeParticleSystems.dispose();
  60451. // Callback
  60452. this.onDisposeObservable.notifyObservers(this);
  60453. this.onDisposeObservable.clear();
  60454. this.reset();
  60455. };
  60456. // Clone
  60457. /**
  60458. * Clones the particle system.
  60459. * @param name The name of the cloned object
  60460. * @param newEmitter The new emitter to use
  60461. * @returns the cloned particle system
  60462. */
  60463. ParticleSystem.prototype.clone = function (name, newEmitter) {
  60464. var custom = null;
  60465. var program = null;
  60466. if (this.customShader != null) {
  60467. program = this.customShader;
  60468. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  60469. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  60470. }
  60471. else if (this._customEffect) {
  60472. custom = this._customEffect;
  60473. }
  60474. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  60475. result.customShader = program;
  60476. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader", "noiseTexture"]);
  60477. if (newEmitter === undefined) {
  60478. newEmitter = this.emitter;
  60479. }
  60480. result.noiseTexture = this.noiseTexture;
  60481. result.emitter = newEmitter;
  60482. if (this.particleTexture) {
  60483. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  60484. }
  60485. // Clone gradients
  60486. if (this._colorGradients) {
  60487. this._colorGradients.forEach(function (v) {
  60488. result.addColorGradient(v.gradient, v.color1, v.color2);
  60489. });
  60490. }
  60491. if (this._dragGradients) {
  60492. this._dragGradients.forEach(function (v) {
  60493. result.addDragGradient(v.gradient, v.factor1, v.factor2);
  60494. });
  60495. }
  60496. if (this._angularSpeedGradients) {
  60497. this._angularSpeedGradients.forEach(function (v) {
  60498. result.addAngularSpeedGradient(v.gradient, v.factor1, v.factor2);
  60499. });
  60500. }
  60501. if (this._emitRateGradients) {
  60502. this._emitRateGradients.forEach(function (v) {
  60503. result.addEmitRateGradient(v.gradient, v.factor1, v.factor2);
  60504. });
  60505. }
  60506. if (this._lifeTimeGradients) {
  60507. this._lifeTimeGradients.forEach(function (v) {
  60508. result.addLifeTimeGradient(v.gradient, v.factor1, v.factor2);
  60509. });
  60510. }
  60511. if (this._limitVelocityGradients) {
  60512. this._limitVelocityGradients.forEach(function (v) {
  60513. result.addLimitVelocityGradient(v.gradient, v.factor1, v.factor2);
  60514. });
  60515. }
  60516. if (this._sizeGradients) {
  60517. this._sizeGradients.forEach(function (v) {
  60518. result.addSizeGradient(v.gradient, v.factor1, v.factor2);
  60519. });
  60520. }
  60521. if (this._startSizeGradients) {
  60522. this._startSizeGradients.forEach(function (v) {
  60523. result.addStartSizeGradient(v.gradient, v.factor1, v.factor2);
  60524. });
  60525. }
  60526. if (this._velocityGradients) {
  60527. this._velocityGradients.forEach(function (v) {
  60528. result.addVelocityGradient(v.gradient, v.factor1, v.factor2);
  60529. });
  60530. }
  60531. if (this._rampGradients) {
  60532. this._rampGradients.forEach(function (v) {
  60533. result.addRampGradient(v.gradient, v.color);
  60534. });
  60535. }
  60536. if (this._colorRemapGradients) {
  60537. this._colorRemapGradients.forEach(function (v) {
  60538. result.addColorRemapGradient(v.gradient, v.factor1, v.factor2);
  60539. });
  60540. }
  60541. if (this._alphaRemapGradients) {
  60542. this._alphaRemapGradients.forEach(function (v) {
  60543. result.addAlphaRemapGradient(v.gradient, v.factor1, v.factor2);
  60544. });
  60545. }
  60546. if (!this.preventAutoStart) {
  60547. result.start();
  60548. }
  60549. return result;
  60550. };
  60551. /**
  60552. * Serializes the particle system to a JSON object.
  60553. * @returns the JSON object
  60554. */
  60555. ParticleSystem.prototype.serialize = function () {
  60556. var serializationObject = {};
  60557. ParticleSystem._Serialize(serializationObject, this);
  60558. serializationObject.textureMask = this.textureMask.asArray();
  60559. serializationObject.customShader = this.customShader;
  60560. serializationObject.preventAutoStart = this.preventAutoStart;
  60561. // SubEmitters
  60562. if (this.subEmitters) {
  60563. serializationObject.subEmitters = [];
  60564. if (!this._subEmitters) {
  60565. this._prepareSubEmitterInternalArray();
  60566. }
  60567. for (var _i = 0, _a = this._subEmitters; _i < _a.length; _i++) {
  60568. var subs = _a[_i];
  60569. var cell = [];
  60570. for (var _b = 0, subs_1 = subs; _b < subs_1.length; _b++) {
  60571. var sub = subs_1[_b];
  60572. cell.push(sub.serialize());
  60573. }
  60574. serializationObject.subEmitters.push(cell);
  60575. }
  60576. }
  60577. return serializationObject;
  60578. };
  60579. /** @hidden */
  60580. ParticleSystem._Serialize = function (serializationObject, particleSystem) {
  60581. serializationObject.name = particleSystem.name;
  60582. serializationObject.id = particleSystem.id;
  60583. serializationObject.capacity = particleSystem.getCapacity();
  60584. // Emitter
  60585. if (particleSystem.emitter.position) {
  60586. var emitterMesh = particleSystem.emitter;
  60587. serializationObject.emitterId = emitterMesh.id;
  60588. }
  60589. else {
  60590. var emitterPosition = particleSystem.emitter;
  60591. serializationObject.emitter = emitterPosition.asArray();
  60592. }
  60593. // Emitter
  60594. if (particleSystem.particleEmitterType) {
  60595. serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize();
  60596. }
  60597. if (particleSystem.particleTexture) {
  60598. serializationObject.textureName = particleSystem.particleTexture.name;
  60599. serializationObject.invertY = particleSystem.particleTexture._invertY;
  60600. }
  60601. // Animations
  60602. BABYLON.Animation.AppendSerializedAnimations(particleSystem, serializationObject);
  60603. serializationObject.beginAnimationOnStart = particleSystem.beginAnimationOnStart;
  60604. serializationObject.beginAnimationFrom = particleSystem.beginAnimationFrom;
  60605. serializationObject.beginAnimationTo = particleSystem.beginAnimationTo;
  60606. serializationObject.beginAnimationLoop = particleSystem.beginAnimationLoop;
  60607. // Particle system
  60608. serializationObject.startDelay = particleSystem.startDelay;
  60609. serializationObject.renderingGroupId = particleSystem.renderingGroupId;
  60610. serializationObject.isBillboardBased = particleSystem.isBillboardBased;
  60611. serializationObject.billboardMode = particleSystem.billboardMode;
  60612. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  60613. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  60614. serializationObject.minSize = particleSystem.minSize;
  60615. serializationObject.maxSize = particleSystem.maxSize;
  60616. serializationObject.minScaleX = particleSystem.minScaleX;
  60617. serializationObject.maxScaleX = particleSystem.maxScaleX;
  60618. serializationObject.minScaleY = particleSystem.minScaleY;
  60619. serializationObject.maxScaleY = particleSystem.maxScaleY;
  60620. serializationObject.minEmitPower = particleSystem.minEmitPower;
  60621. serializationObject.maxEmitPower = particleSystem.maxEmitPower;
  60622. serializationObject.minLifeTime = particleSystem.minLifeTime;
  60623. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  60624. serializationObject.emitRate = particleSystem.emitRate;
  60625. serializationObject.gravity = particleSystem.gravity.asArray();
  60626. serializationObject.noiseStrength = particleSystem.noiseStrength.asArray();
  60627. serializationObject.color1 = particleSystem.color1.asArray();
  60628. serializationObject.color2 = particleSystem.color2.asArray();
  60629. serializationObject.colorDead = particleSystem.colorDead.asArray();
  60630. serializationObject.updateSpeed = particleSystem.updateSpeed;
  60631. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  60632. serializationObject.blendMode = particleSystem.blendMode;
  60633. serializationObject.preWarmCycles = particleSystem.preWarmCycles;
  60634. serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset;
  60635. serializationObject.minInitialRotation = particleSystem.minInitialRotation;
  60636. serializationObject.maxInitialRotation = particleSystem.maxInitialRotation;
  60637. serializationObject.startSpriteCellID = particleSystem.startSpriteCellID;
  60638. serializationObject.endSpriteCellID = particleSystem.endSpriteCellID;
  60639. serializationObject.spriteCellChangeSpeed = particleSystem.spriteCellChangeSpeed;
  60640. serializationObject.spriteCellWidth = particleSystem.spriteCellWidth;
  60641. serializationObject.spriteCellHeight = particleSystem.spriteCellHeight;
  60642. serializationObject.spriteRandomStartCell = particleSystem.spriteRandomStartCell;
  60643. serializationObject.isAnimationSheetEnabled = particleSystem.isAnimationSheetEnabled;
  60644. var colorGradients = particleSystem.getColorGradients();
  60645. if (colorGradients) {
  60646. serializationObject.colorGradients = [];
  60647. for (var _i = 0, colorGradients_1 = colorGradients; _i < colorGradients_1.length; _i++) {
  60648. var colorGradient = colorGradients_1[_i];
  60649. var serializedGradient = {
  60650. gradient: colorGradient.gradient,
  60651. color1: colorGradient.color1.asArray()
  60652. };
  60653. if (colorGradient.color2) {
  60654. serializedGradient.color2 = colorGradient.color2.asArray();
  60655. }
  60656. serializationObject.colorGradients.push(serializedGradient);
  60657. }
  60658. }
  60659. var rampGradients = particleSystem.getRampGradients();
  60660. if (rampGradients) {
  60661. serializationObject.rampGradients = [];
  60662. for (var _a = 0, rampGradients_1 = rampGradients; _a < rampGradients_1.length; _a++) {
  60663. var rampGradient = rampGradients_1[_a];
  60664. var serializedGradient = {
  60665. gradient: rampGradient.gradient,
  60666. color: rampGradient.color.asArray()
  60667. };
  60668. serializationObject.rampGradients.push(serializedGradient);
  60669. }
  60670. serializationObject.useRampGradients = particleSystem.useRampGradients;
  60671. }
  60672. var colorRemapGradients = particleSystem.getColorRemapGradients();
  60673. if (colorRemapGradients) {
  60674. serializationObject.colorRemapGradients = [];
  60675. for (var _b = 0, colorRemapGradients_1 = colorRemapGradients; _b < colorRemapGradients_1.length; _b++) {
  60676. var colorRemapGradient = colorRemapGradients_1[_b];
  60677. var serializedGradient = {
  60678. gradient: colorRemapGradient.gradient,
  60679. factor1: colorRemapGradient.factor1
  60680. };
  60681. if (colorRemapGradient.factor2 !== undefined) {
  60682. serializedGradient.factor2 = colorRemapGradient.factor2;
  60683. }
  60684. serializationObject.colorRemapGradients.push(serializedGradient);
  60685. }
  60686. }
  60687. var alphaRemapGradients = particleSystem.getAlphaRemapGradients();
  60688. if (alphaRemapGradients) {
  60689. serializationObject.alphaRemapGradients = [];
  60690. for (var _c = 0, alphaRemapGradients_1 = alphaRemapGradients; _c < alphaRemapGradients_1.length; _c++) {
  60691. var alphaRemapGradient = alphaRemapGradients_1[_c];
  60692. var serializedGradient = {
  60693. gradient: alphaRemapGradient.gradient,
  60694. factor1: alphaRemapGradient.factor1
  60695. };
  60696. if (alphaRemapGradient.factor2 !== undefined) {
  60697. serializedGradient.factor2 = alphaRemapGradient.factor2;
  60698. }
  60699. serializationObject.alphaRemapGradients.push(serializedGradient);
  60700. }
  60701. }
  60702. var sizeGradients = particleSystem.getSizeGradients();
  60703. if (sizeGradients) {
  60704. serializationObject.sizeGradients = [];
  60705. for (var _d = 0, sizeGradients_1 = sizeGradients; _d < sizeGradients_1.length; _d++) {
  60706. var sizeGradient = sizeGradients_1[_d];
  60707. var serializedGradient = {
  60708. gradient: sizeGradient.gradient,
  60709. factor1: sizeGradient.factor1
  60710. };
  60711. if (sizeGradient.factor2 !== undefined) {
  60712. serializedGradient.factor2 = sizeGradient.factor2;
  60713. }
  60714. serializationObject.sizeGradients.push(serializedGradient);
  60715. }
  60716. }
  60717. var angularSpeedGradients = particleSystem.getAngularSpeedGradients();
  60718. if (angularSpeedGradients) {
  60719. serializationObject.angularSpeedGradients = [];
  60720. for (var _e = 0, angularSpeedGradients_1 = angularSpeedGradients; _e < angularSpeedGradients_1.length; _e++) {
  60721. var angularSpeedGradient = angularSpeedGradients_1[_e];
  60722. var serializedGradient = {
  60723. gradient: angularSpeedGradient.gradient,
  60724. factor1: angularSpeedGradient.factor1
  60725. };
  60726. if (angularSpeedGradient.factor2 !== undefined) {
  60727. serializedGradient.factor2 = angularSpeedGradient.factor2;
  60728. }
  60729. serializationObject.angularSpeedGradients.push(serializedGradient);
  60730. }
  60731. }
  60732. var velocityGradients = particleSystem.getVelocityGradients();
  60733. if (velocityGradients) {
  60734. serializationObject.velocityGradients = [];
  60735. for (var _f = 0, velocityGradients_1 = velocityGradients; _f < velocityGradients_1.length; _f++) {
  60736. var velocityGradient = velocityGradients_1[_f];
  60737. var serializedGradient = {
  60738. gradient: velocityGradient.gradient,
  60739. factor1: velocityGradient.factor1
  60740. };
  60741. if (velocityGradient.factor2 !== undefined) {
  60742. serializedGradient.factor2 = velocityGradient.factor2;
  60743. }
  60744. serializationObject.velocityGradients.push(serializedGradient);
  60745. }
  60746. }
  60747. var dragGradients = particleSystem.getDragGradients();
  60748. if (dragGradients) {
  60749. serializationObject.dragyGradients = [];
  60750. for (var _g = 0, dragGradients_1 = dragGradients; _g < dragGradients_1.length; _g++) {
  60751. var dragGradient = dragGradients_1[_g];
  60752. var serializedGradient = {
  60753. gradient: dragGradient.gradient,
  60754. factor1: dragGradient.factor1
  60755. };
  60756. if (dragGradient.factor2 !== undefined) {
  60757. serializedGradient.factor2 = dragGradient.factor2;
  60758. }
  60759. serializationObject.dragGradients.push(serializedGradient);
  60760. }
  60761. }
  60762. var emitRateGradients = particleSystem.getEmitRateGradients();
  60763. if (emitRateGradients) {
  60764. serializationObject.emitRateGradients = [];
  60765. for (var _h = 0, emitRateGradients_1 = emitRateGradients; _h < emitRateGradients_1.length; _h++) {
  60766. var emitRateGradient = emitRateGradients_1[_h];
  60767. var serializedGradient = {
  60768. gradient: emitRateGradient.gradient,
  60769. factor1: emitRateGradient.factor1
  60770. };
  60771. if (emitRateGradient.factor2 !== undefined) {
  60772. serializedGradient.factor2 = emitRateGradient.factor2;
  60773. }
  60774. serializationObject.emitRateGradients.push(serializedGradient);
  60775. }
  60776. }
  60777. var startSizeGradients = particleSystem.getStartSizeGradients();
  60778. if (startSizeGradients) {
  60779. serializationObject.startSizeGradients = [];
  60780. for (var _j = 0, startSizeGradients_1 = startSizeGradients; _j < startSizeGradients_1.length; _j++) {
  60781. var startSizeGradient = startSizeGradients_1[_j];
  60782. var serializedGradient = {
  60783. gradient: startSizeGradient.gradient,
  60784. factor1: startSizeGradient.factor1
  60785. };
  60786. if (startSizeGradient.factor2 !== undefined) {
  60787. serializedGradient.factor2 = startSizeGradient.factor2;
  60788. }
  60789. serializationObject.startSizeGradients.push(serializedGradient);
  60790. }
  60791. }
  60792. var lifeTimeGradients = particleSystem.getLifeTimeGradients();
  60793. if (lifeTimeGradients) {
  60794. serializationObject.lifeTimeGradients = [];
  60795. for (var _k = 0, lifeTimeGradients_1 = lifeTimeGradients; _k < lifeTimeGradients_1.length; _k++) {
  60796. var lifeTimeGradient = lifeTimeGradients_1[_k];
  60797. var serializedGradient = {
  60798. gradient: lifeTimeGradient.gradient,
  60799. factor1: lifeTimeGradient.factor1
  60800. };
  60801. if (lifeTimeGradient.factor2 !== undefined) {
  60802. serializedGradient.factor2 = lifeTimeGradient.factor2;
  60803. }
  60804. serializationObject.lifeTimeGradients.push(serializedGradient);
  60805. }
  60806. }
  60807. var limitVelocityGradients = particleSystem.getLimitVelocityGradients();
  60808. if (limitVelocityGradients) {
  60809. serializationObject.limitVelocityGradients = [];
  60810. for (var _l = 0, limitVelocityGradients_1 = limitVelocityGradients; _l < limitVelocityGradients_1.length; _l++) {
  60811. var limitVelocityGradient = limitVelocityGradients_1[_l];
  60812. var serializedGradient = {
  60813. gradient: limitVelocityGradient.gradient,
  60814. factor1: limitVelocityGradient.factor1
  60815. };
  60816. if (limitVelocityGradient.factor2 !== undefined) {
  60817. serializedGradient.factor2 = limitVelocityGradient.factor2;
  60818. }
  60819. serializationObject.limitVelocityGradients.push(serializedGradient);
  60820. }
  60821. serializationObject.limitVelocityDamping = particleSystem.limitVelocityDamping;
  60822. }
  60823. if (particleSystem.noiseTexture) {
  60824. serializationObject.noiseTexture = particleSystem.noiseTexture.serialize();
  60825. }
  60826. };
  60827. /** @hidden */
  60828. ParticleSystem._Parse = function (parsedParticleSystem, particleSystem, scene, rootUrl) {
  60829. // Texture
  60830. if (parsedParticleSystem.textureName) {
  60831. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene, false, parsedParticleSystem.invertY !== undefined ? parsedParticleSystem.invertY : true);
  60832. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  60833. }
  60834. // Emitter
  60835. if (!parsedParticleSystem.emitterId && parsedParticleSystem.emitterId !== 0 && parsedParticleSystem.emitter === undefined) {
  60836. particleSystem.emitter = BABYLON.Vector3.Zero();
  60837. }
  60838. else if (parsedParticleSystem.emitterId) {
  60839. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  60840. }
  60841. else {
  60842. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  60843. }
  60844. // Misc.
  60845. if (parsedParticleSystem.renderingGroupId !== undefined) {
  60846. particleSystem.renderingGroupId = parsedParticleSystem.renderingGroupId;
  60847. }
  60848. if (parsedParticleSystem.isBillboardBased !== undefined) {
  60849. particleSystem.isBillboardBased = parsedParticleSystem.isBillboardBased;
  60850. }
  60851. if (parsedParticleSystem.billboardMode !== undefined) {
  60852. particleSystem.billboardMode = parsedParticleSystem.billboardMode;
  60853. }
  60854. // Animations
  60855. if (parsedParticleSystem.animations) {
  60856. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  60857. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  60858. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  60859. }
  60860. particleSystem.beginAnimationOnStart = parsedParticleSystem.beginAnimationOnStart;
  60861. particleSystem.beginAnimationFrom = parsedParticleSystem.beginAnimationFrom;
  60862. particleSystem.beginAnimationTo = parsedParticleSystem.beginAnimationTo;
  60863. particleSystem.beginAnimationLoop = parsedParticleSystem.beginAnimationLoop;
  60864. }
  60865. if (parsedParticleSystem.autoAnimate) {
  60866. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  60867. }
  60868. // Particle system
  60869. particleSystem.startDelay = parsedParticleSystem.startDelay | 0;
  60870. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  60871. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  60872. particleSystem.minSize = parsedParticleSystem.minSize;
  60873. particleSystem.maxSize = parsedParticleSystem.maxSize;
  60874. if (parsedParticleSystem.minScaleX) {
  60875. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  60876. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  60877. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  60878. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  60879. }
  60880. if (parsedParticleSystem.preWarmCycles !== undefined) {
  60881. particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;
  60882. particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;
  60883. }
  60884. if (parsedParticleSystem.minInitialRotation !== undefined) {
  60885. particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;
  60886. particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;
  60887. }
  60888. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  60889. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  60890. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  60891. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  60892. particleSystem.emitRate = parsedParticleSystem.emitRate;
  60893. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  60894. if (parsedParticleSystem.noiseStrength) {
  60895. particleSystem.noiseStrength = BABYLON.Vector3.FromArray(parsedParticleSystem.noiseStrength);
  60896. }
  60897. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  60898. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  60899. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  60900. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  60901. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  60902. particleSystem.blendMode = parsedParticleSystem.blendMode;
  60903. if (parsedParticleSystem.colorGradients) {
  60904. for (var _i = 0, _a = parsedParticleSystem.colorGradients; _i < _a.length; _i++) {
  60905. var colorGradient = _a[_i];
  60906. particleSystem.addColorGradient(colorGradient.gradient, BABYLON.Color4.FromArray(colorGradient.color1), colorGradient.color2 ? BABYLON.Color4.FromArray(colorGradient.color2) : undefined);
  60907. }
  60908. }
  60909. if (parsedParticleSystem.rampGradients) {
  60910. for (var _b = 0, _c = parsedParticleSystem.rampGradients; _b < _c.length; _b++) {
  60911. var rampGradient = _c[_b];
  60912. particleSystem.addRampGradient(rampGradient.gradient, BABYLON.Color3.FromArray(rampGradient.color));
  60913. }
  60914. particleSystem.useRampGradients = parsedParticleSystem.useRampGradients;
  60915. }
  60916. if (parsedParticleSystem.colorRemapGradients) {
  60917. for (var _d = 0, _e = parsedParticleSystem.colorRemapGradients; _d < _e.length; _d++) {
  60918. var colorRemapGradient = _e[_d];
  60919. particleSystem.addColorRemapGradient(colorRemapGradient.gradient, colorRemapGradient.factor1 !== undefined ? colorRemapGradient.factor1 : colorRemapGradient.factor, colorRemapGradient.factor2);
  60920. }
  60921. }
  60922. if (parsedParticleSystem.alphaRemapGradients) {
  60923. for (var _f = 0, _g = parsedParticleSystem.alphaRemapGradients; _f < _g.length; _f++) {
  60924. var alphaRemapGradient = _g[_f];
  60925. particleSystem.addAlphaRemapGradient(alphaRemapGradient.gradient, alphaRemapGradient.factor1 !== undefined ? alphaRemapGradient.factor1 : alphaRemapGradient.factor, alphaRemapGradient.factor2);
  60926. }
  60927. }
  60928. if (parsedParticleSystem.sizeGradients) {
  60929. for (var _h = 0, _j = parsedParticleSystem.sizeGradients; _h < _j.length; _h++) {
  60930. var sizeGradient = _j[_h];
  60931. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  60932. }
  60933. }
  60934. if (parsedParticleSystem.sizeGradients) {
  60935. for (var _k = 0, _l = parsedParticleSystem.sizeGradients; _k < _l.length; _k++) {
  60936. var sizeGradient = _l[_k];
  60937. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  60938. }
  60939. }
  60940. if (parsedParticleSystem.angularSpeedGradients) {
  60941. for (var _m = 0, _o = parsedParticleSystem.angularSpeedGradients; _m < _o.length; _m++) {
  60942. var angularSpeedGradient = _o[_m];
  60943. particleSystem.addAngularSpeedGradient(angularSpeedGradient.gradient, angularSpeedGradient.factor1 !== undefined ? angularSpeedGradient.factor1 : angularSpeedGradient.factor, angularSpeedGradient.factor2);
  60944. }
  60945. }
  60946. if (parsedParticleSystem.velocityGradients) {
  60947. for (var _p = 0, _q = parsedParticleSystem.velocityGradients; _p < _q.length; _p++) {
  60948. var velocityGradient = _q[_p];
  60949. particleSystem.addVelocityGradient(velocityGradient.gradient, velocityGradient.factor1 !== undefined ? velocityGradient.factor1 : velocityGradient.factor, velocityGradient.factor2);
  60950. }
  60951. }
  60952. if (parsedParticleSystem.dragGradients) {
  60953. for (var _r = 0, _s = parsedParticleSystem.dragGradients; _r < _s.length; _r++) {
  60954. var dragGradient = _s[_r];
  60955. particleSystem.addDragGradient(dragGradient.gradient, dragGradient.factor1 !== undefined ? dragGradient.factor1 : dragGradient.factor, dragGradient.factor2);
  60956. }
  60957. }
  60958. if (parsedParticleSystem.emitRateGradients) {
  60959. for (var _t = 0, _u = parsedParticleSystem.emitRateGradients; _t < _u.length; _t++) {
  60960. var emitRateGradient = _u[_t];
  60961. particleSystem.addEmitRateGradient(emitRateGradient.gradient, emitRateGradient.factor1 !== undefined ? emitRateGradient.factor1 : emitRateGradient.factor, emitRateGradient.factor2);
  60962. }
  60963. }
  60964. if (parsedParticleSystem.startSizeGradients) {
  60965. for (var _v = 0, _w = parsedParticleSystem.startSizeGradients; _v < _w.length; _v++) {
  60966. var startSizeGradient = _w[_v];
  60967. particleSystem.addStartSizeGradient(startSizeGradient.gradient, startSizeGradient.factor1 !== undefined ? startSizeGradient.factor1 : startSizeGradient.factor, startSizeGradient.factor2);
  60968. }
  60969. }
  60970. if (parsedParticleSystem.lifeTimeGradients) {
  60971. for (var _x = 0, _y = parsedParticleSystem.lifeTimeGradients; _x < _y.length; _x++) {
  60972. var lifeTimeGradient = _y[_x];
  60973. particleSystem.addLifeTimeGradient(lifeTimeGradient.gradient, lifeTimeGradient.factor1 !== undefined ? lifeTimeGradient.factor1 : lifeTimeGradient.factor, lifeTimeGradient.factor2);
  60974. }
  60975. }
  60976. if (parsedParticleSystem.limitVelocityGradients) {
  60977. for (var _z = 0, _0 = parsedParticleSystem.limitVelocityGradients; _z < _0.length; _z++) {
  60978. var limitVelocityGradient = _0[_z];
  60979. particleSystem.addLimitVelocityGradient(limitVelocityGradient.gradient, limitVelocityGradient.factor1 !== undefined ? limitVelocityGradient.factor1 : limitVelocityGradient.factor, limitVelocityGradient.factor2);
  60980. }
  60981. particleSystem.limitVelocityDamping = parsedParticleSystem.limitVelocityDamping;
  60982. }
  60983. if (parsedParticleSystem.noiseTexture) {
  60984. particleSystem.noiseTexture = BABYLON.ProceduralTexture.Parse(parsedParticleSystem.noiseTexture, scene, rootUrl);
  60985. }
  60986. // Emitter
  60987. var emitterType;
  60988. if (parsedParticleSystem.particleEmitterType) {
  60989. switch (parsedParticleSystem.particleEmitterType.type) {
  60990. case "SphereParticleEmitter":
  60991. emitterType = new BABYLON.SphereParticleEmitter();
  60992. break;
  60993. case "SphereDirectedParticleEmitter":
  60994. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  60995. break;
  60996. case "ConeEmitter":
  60997. case "ConeParticleEmitter":
  60998. emitterType = new BABYLON.ConeParticleEmitter();
  60999. break;
  61000. case "CylinderParticleEmitter":
  61001. emitterType = new BABYLON.CylinderParticleEmitter();
  61002. break;
  61003. case "HemisphericParticleEmitter":
  61004. emitterType = new BABYLON.HemisphericParticleEmitter();
  61005. break;
  61006. case "BoxEmitter":
  61007. case "BoxParticleEmitter":
  61008. default:
  61009. emitterType = new BABYLON.BoxParticleEmitter();
  61010. break;
  61011. }
  61012. emitterType.parse(parsedParticleSystem.particleEmitterType);
  61013. }
  61014. else {
  61015. emitterType = new BABYLON.BoxParticleEmitter();
  61016. emitterType.parse(parsedParticleSystem);
  61017. }
  61018. particleSystem.particleEmitterType = emitterType;
  61019. // Animation sheet
  61020. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  61021. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  61022. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  61023. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  61024. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  61025. particleSystem.spriteRandomStartCell = parsedParticleSystem.spriteRandomStartCell;
  61026. };
  61027. /**
  61028. * Parses a JSON object to create a particle system.
  61029. * @param parsedParticleSystem The JSON object to parse
  61030. * @param scene The scene to create the particle system in
  61031. * @param rootUrl The root url to use to load external dependencies like texture
  61032. * @param doNotStart Ignore the preventAutoStart attribute and does not start
  61033. * @returns the Parsed particle system
  61034. */
  61035. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl, doNotStart) {
  61036. if (doNotStart === void 0) { doNotStart = false; }
  61037. var name = parsedParticleSystem.name;
  61038. var custom = null;
  61039. var program = null;
  61040. if (parsedParticleSystem.customShader) {
  61041. program = parsedParticleSystem.customShader;
  61042. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  61043. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  61044. }
  61045. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  61046. particleSystem.customShader = program;
  61047. if (parsedParticleSystem.id) {
  61048. particleSystem.id = parsedParticleSystem.id;
  61049. }
  61050. // SubEmitters
  61051. if (parsedParticleSystem.subEmitters) {
  61052. particleSystem.subEmitters = [];
  61053. for (var _i = 0, _a = parsedParticleSystem.subEmitters; _i < _a.length; _i++) {
  61054. var cell = _a[_i];
  61055. var cellArray = [];
  61056. for (var _b = 0, cell_1 = cell; _b < cell_1.length; _b++) {
  61057. var sub = cell_1[_b];
  61058. cellArray.push(BABYLON.SubEmitter.Parse(sub, scene, rootUrl));
  61059. }
  61060. particleSystem.subEmitters.push(cellArray);
  61061. }
  61062. }
  61063. ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  61064. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  61065. // Auto start
  61066. if (parsedParticleSystem.preventAutoStart) {
  61067. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  61068. }
  61069. if (!doNotStart && !particleSystem.preventAutoStart) {
  61070. particleSystem.start();
  61071. }
  61072. return particleSystem;
  61073. };
  61074. /**
  61075. * Billboard mode will only apply to Y axis
  61076. */
  61077. ParticleSystem.BILLBOARDMODE_Y = 2;
  61078. /**
  61079. * Billboard mode will apply to all axes
  61080. */
  61081. ParticleSystem.BILLBOARDMODE_ALL = 7;
  61082. /**
  61083. * Special billboard mode where the particle will be biilboard to the camera but rotated to align with direction
  61084. */
  61085. ParticleSystem.BILLBOARDMODE_STRETCHED = 8;
  61086. return ParticleSystem;
  61087. }(BABYLON.BaseParticleSystem));
  61088. BABYLON.ParticleSystem = ParticleSystem;
  61089. })(BABYLON || (BABYLON = {}));
  61090. //# sourceMappingURL=babylon.particleSystem.js.map
  61091. var BABYLON;
  61092. (function (BABYLON) {
  61093. /**
  61094. * Particle emitter emitting particles from the inside of a box.
  61095. * It emits the particles randomly between 2 given directions.
  61096. */
  61097. var BoxParticleEmitter = /** @class */ (function () {
  61098. /**
  61099. * Creates a new instance BoxParticleEmitter
  61100. */
  61101. function BoxParticleEmitter() {
  61102. /**
  61103. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  61104. */
  61105. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  61106. /**
  61107. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  61108. */
  61109. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  61110. /**
  61111. * 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.
  61112. */
  61113. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  61114. /**
  61115. * 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.
  61116. */
  61117. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  61118. }
  61119. /**
  61120. * Called by the particle System when the direction is computed for the created particle.
  61121. * @param worldMatrix is the world matrix of the particle system
  61122. * @param directionToUpdate is the direction vector to update with the result
  61123. * @param particle is the particle we are computed the direction for
  61124. */
  61125. BoxParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  61126. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  61127. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  61128. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  61129. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  61130. };
  61131. /**
  61132. * Called by the particle System when the position is computed for the created particle.
  61133. * @param worldMatrix is the world matrix of the particle system
  61134. * @param positionToUpdate is the position vector to update with the result
  61135. * @param particle is the particle we are computed the position for
  61136. */
  61137. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  61138. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  61139. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  61140. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  61141. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  61142. };
  61143. /**
  61144. * Clones the current emitter and returns a copy of it
  61145. * @returns the new emitter
  61146. */
  61147. BoxParticleEmitter.prototype.clone = function () {
  61148. var newOne = new BoxParticleEmitter();
  61149. BABYLON.Tools.DeepCopy(this, newOne);
  61150. return newOne;
  61151. };
  61152. /**
  61153. * Called by the GPUParticleSystem to setup the update shader
  61154. * @param effect defines the update shader
  61155. */
  61156. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  61157. effect.setVector3("direction1", this.direction1);
  61158. effect.setVector3("direction2", this.direction2);
  61159. effect.setVector3("minEmitBox", this.minEmitBox);
  61160. effect.setVector3("maxEmitBox", this.maxEmitBox);
  61161. };
  61162. /**
  61163. * Returns a string to use to update the GPU particles update shader
  61164. * @returns a string containng the defines string
  61165. */
  61166. BoxParticleEmitter.prototype.getEffectDefines = function () {
  61167. return "#define BOXEMITTER";
  61168. };
  61169. /**
  61170. * Returns the string "BoxParticleEmitter"
  61171. * @returns a string containing the class name
  61172. */
  61173. BoxParticleEmitter.prototype.getClassName = function () {
  61174. return "BoxParticleEmitter";
  61175. };
  61176. /**
  61177. * Serializes the particle system to a JSON object.
  61178. * @returns the JSON object
  61179. */
  61180. BoxParticleEmitter.prototype.serialize = function () {
  61181. var serializationObject = {};
  61182. serializationObject.type = this.getClassName();
  61183. serializationObject.direction1 = this.direction1.asArray();
  61184. serializationObject.direction2 = this.direction2.asArray();
  61185. serializationObject.minEmitBox = this.minEmitBox.asArray();
  61186. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  61187. return serializationObject;
  61188. };
  61189. /**
  61190. * Parse properties from a JSON object
  61191. * @param serializationObject defines the JSON object
  61192. */
  61193. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  61194. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  61195. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  61196. BABYLON.Vector3.FromArrayToRef(serializationObject.minEmitBox, 0, this.minEmitBox);
  61197. BABYLON.Vector3.FromArrayToRef(serializationObject.maxEmitBox, 0, this.maxEmitBox);
  61198. };
  61199. return BoxParticleEmitter;
  61200. }());
  61201. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  61202. })(BABYLON || (BABYLON = {}));
  61203. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  61204. var BABYLON;
  61205. (function (BABYLON) {
  61206. /**
  61207. * Particle emitter emitting particles from the inside of a cylinder.
  61208. * It emits the particles alongside the cylinder radius. The emission direction might be randomized.
  61209. */
  61210. var CylinderParticleEmitter = /** @class */ (function () {
  61211. /**
  61212. * Creates a new instance CylinderParticleEmitter
  61213. * @param radius the radius of the emission cylinder (1 by default)
  61214. * @param height the height of the emission cylinder (1 by default)
  61215. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  61216. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  61217. */
  61218. function CylinderParticleEmitter(
  61219. /**
  61220. * The radius of the emission cylinder.
  61221. */
  61222. radius,
  61223. /**
  61224. * The height of the emission cylinder.
  61225. */
  61226. height,
  61227. /**
  61228. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  61229. */
  61230. radiusRange,
  61231. /**
  61232. * How much to randomize the particle direction [0-1].
  61233. */
  61234. directionRandomizer) {
  61235. if (radius === void 0) { radius = 1; }
  61236. if (height === void 0) { height = 1; }
  61237. if (radiusRange === void 0) { radiusRange = 1; }
  61238. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  61239. this.radius = radius;
  61240. this.height = height;
  61241. this.radiusRange = radiusRange;
  61242. this.directionRandomizer = directionRandomizer;
  61243. }
  61244. /**
  61245. * Called by the particle System when the direction is computed for the created particle.
  61246. * @param worldMatrix is the world matrix of the particle system
  61247. * @param directionToUpdate is the direction vector to update with the result
  61248. * @param particle is the particle we are computed the direction for
  61249. */
  61250. CylinderParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  61251. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  61252. var randY = BABYLON.Scalar.RandomRange(-this.directionRandomizer / 2, this.directionRandomizer / 2);
  61253. var angle = Math.atan2(direction.x, direction.z);
  61254. angle += BABYLON.Scalar.RandomRange(-Math.PI / 2, Math.PI / 2) * this.directionRandomizer;
  61255. direction.y = randY; // set direction y to rand y to mirror normal of cylinder surface
  61256. direction.x = Math.sin(angle);
  61257. direction.z = Math.cos(angle);
  61258. direction.normalize();
  61259. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  61260. };
  61261. /**
  61262. * Called by the particle System when the position is computed for the created particle.
  61263. * @param worldMatrix is the world matrix of the particle system
  61264. * @param positionToUpdate is the position vector to update with the result
  61265. * @param particle is the particle we are computed the position for
  61266. */
  61267. CylinderParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  61268. var yPos = BABYLON.Scalar.RandomRange(-this.height / 2, this.height / 2);
  61269. var angle = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  61270. // Pick a properly distributed point within the circle https://programming.guide/random-point-within-circle.html
  61271. var radiusDistribution = BABYLON.Scalar.RandomRange((1 - this.radiusRange) * (1 - this.radiusRange), 1);
  61272. var positionRadius = Math.sqrt(radiusDistribution) * this.radius;
  61273. var xPos = positionRadius * Math.cos(angle);
  61274. var zPos = positionRadius * Math.sin(angle);
  61275. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(xPos, yPos, zPos, worldMatrix, positionToUpdate);
  61276. };
  61277. /**
  61278. * Clones the current emitter and returns a copy of it
  61279. * @returns the new emitter
  61280. */
  61281. CylinderParticleEmitter.prototype.clone = function () {
  61282. var newOne = new CylinderParticleEmitter(this.radius, this.directionRandomizer);
  61283. BABYLON.Tools.DeepCopy(this, newOne);
  61284. return newOne;
  61285. };
  61286. /**
  61287. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  61288. * @param effect defines the update shader
  61289. */
  61290. CylinderParticleEmitter.prototype.applyToShader = function (effect) {
  61291. effect.setFloat("radius", this.radius);
  61292. effect.setFloat("height", this.height);
  61293. effect.setFloat("radiusRange", this.radiusRange);
  61294. effect.setFloat("directionRandomizer", this.directionRandomizer);
  61295. };
  61296. /**
  61297. * Returns a string to use to update the GPU particles update shader
  61298. * @returns a string containng the defines string
  61299. */
  61300. CylinderParticleEmitter.prototype.getEffectDefines = function () {
  61301. return "#define CYLINDEREMITTER";
  61302. };
  61303. /**
  61304. * Returns the string "CylinderParticleEmitter"
  61305. * @returns a string containing the class name
  61306. */
  61307. CylinderParticleEmitter.prototype.getClassName = function () {
  61308. return "CylinderParticleEmitter";
  61309. };
  61310. /**
  61311. * Serializes the particle system to a JSON object.
  61312. * @returns the JSON object
  61313. */
  61314. CylinderParticleEmitter.prototype.serialize = function () {
  61315. var serializationObject = {};
  61316. serializationObject.type = this.getClassName();
  61317. serializationObject.radius = this.radius;
  61318. serializationObject.height = this.height;
  61319. serializationObject.radiusRange = this.radiusRange;
  61320. serializationObject.directionRandomizer = this.directionRandomizer;
  61321. return serializationObject;
  61322. };
  61323. /**
  61324. * Parse properties from a JSON object
  61325. * @param serializationObject defines the JSON object
  61326. */
  61327. CylinderParticleEmitter.prototype.parse = function (serializationObject) {
  61328. this.radius = serializationObject.radius;
  61329. this.height = serializationObject.height;
  61330. this.radiusRange = serializationObject.radiusRange;
  61331. this.directionRandomizer = serializationObject.directionRandomizer;
  61332. };
  61333. return CylinderParticleEmitter;
  61334. }());
  61335. BABYLON.CylinderParticleEmitter = CylinderParticleEmitter;
  61336. /**
  61337. * Particle emitter emitting particles from the inside of a cylinder.
  61338. * It emits the particles randomly between two vectors.
  61339. */
  61340. var CylinderDirectedParticleEmitter = /** @class */ (function (_super) {
  61341. __extends(CylinderDirectedParticleEmitter, _super);
  61342. /**
  61343. * Creates a new instance CylinderDirectedParticleEmitter
  61344. * @param radius the radius of the emission cylinder (1 by default)
  61345. * @param height the height of the emission cylinder (1 by default)
  61346. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  61347. * @param direction1 the min limit of the emission direction (up vector by default)
  61348. * @param direction2 the max limit of the emission direction (up vector by default)
  61349. */
  61350. function CylinderDirectedParticleEmitter(radius, height, radiusRange,
  61351. /**
  61352. * The min limit of the emission direction.
  61353. */
  61354. direction1,
  61355. /**
  61356. * The max limit of the emission direction.
  61357. */
  61358. direction2) {
  61359. if (radius === void 0) { radius = 1; }
  61360. if (height === void 0) { height = 1; }
  61361. if (radiusRange === void 0) { radiusRange = 1; }
  61362. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  61363. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  61364. var _this = _super.call(this, radius, height, radiusRange) || this;
  61365. _this.direction1 = direction1;
  61366. _this.direction2 = direction2;
  61367. return _this;
  61368. }
  61369. /**
  61370. * Called by the particle System when the direction is computed for the created particle.
  61371. * @param worldMatrix is the world matrix of the particle system
  61372. * @param directionToUpdate is the direction vector to update with the result
  61373. * @param particle is the particle we are computed the direction for
  61374. */
  61375. CylinderDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  61376. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  61377. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  61378. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  61379. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  61380. };
  61381. /**
  61382. * Clones the current emitter and returns a copy of it
  61383. * @returns the new emitter
  61384. */
  61385. CylinderDirectedParticleEmitter.prototype.clone = function () {
  61386. var newOne = new CylinderDirectedParticleEmitter(this.radius, this.height, this.radiusRange, this.direction1, this.direction2);
  61387. BABYLON.Tools.DeepCopy(this, newOne);
  61388. return newOne;
  61389. };
  61390. /**
  61391. * Called by the GPUParticleSystem to setup the update shader
  61392. * @param effect defines the update shader
  61393. */
  61394. CylinderDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  61395. effect.setFloat("radius", this.radius);
  61396. effect.setFloat("height", this.height);
  61397. effect.setFloat("radiusRange", this.radiusRange);
  61398. effect.setVector3("direction1", this.direction1);
  61399. effect.setVector3("direction2", this.direction2);
  61400. };
  61401. /**
  61402. * Returns a string to use to update the GPU particles update shader
  61403. * @returns a string containng the defines string
  61404. */
  61405. CylinderDirectedParticleEmitter.prototype.getEffectDefines = function () {
  61406. return "#define CYLINDEREMITTER\n#define DIRECTEDCYLINDEREMITTER";
  61407. };
  61408. /**
  61409. * Returns the string "CylinderDirectedParticleEmitter"
  61410. * @returns a string containing the class name
  61411. */
  61412. CylinderDirectedParticleEmitter.prototype.getClassName = function () {
  61413. return "CylinderDirectedParticleEmitter";
  61414. };
  61415. /**
  61416. * Serializes the particle system to a JSON object.
  61417. * @returns the JSON object
  61418. */
  61419. CylinderDirectedParticleEmitter.prototype.serialize = function () {
  61420. var serializationObject = _super.prototype.serialize.call(this);
  61421. serializationObject.direction1 = this.direction1.asArray();
  61422. serializationObject.direction2 = this.direction2.asArray();
  61423. return serializationObject;
  61424. };
  61425. /**
  61426. * Parse properties from a JSON object
  61427. * @param serializationObject defines the JSON object
  61428. */
  61429. CylinderDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  61430. _super.prototype.parse.call(this, serializationObject);
  61431. this.direction1.copyFrom(serializationObject.direction1);
  61432. this.direction2.copyFrom(serializationObject.direction2);
  61433. };
  61434. return CylinderDirectedParticleEmitter;
  61435. }(CylinderParticleEmitter));
  61436. BABYLON.CylinderDirectedParticleEmitter = CylinderDirectedParticleEmitter;
  61437. })(BABYLON || (BABYLON = {}));
  61438. //# sourceMappingURL=babylon.cylinderParticleEmitter.js.map
  61439. var BABYLON;
  61440. (function (BABYLON) {
  61441. /**
  61442. * Particle emitter emitting particles from the inside of a cone.
  61443. * It emits the particles alongside the cone volume from the base to the particle.
  61444. * The emission direction might be randomized.
  61445. */
  61446. var ConeParticleEmitter = /** @class */ (function () {
  61447. /**
  61448. * Creates a new instance ConeParticleEmitter
  61449. * @param radius the radius of the emission cone (1 by default)
  61450. * @param angles the cone base angle (PI by default)
  61451. * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)
  61452. */
  61453. function ConeParticleEmitter(radius, angle,
  61454. /** defines how much to randomize the particle direction [0-1] (default is 0) */
  61455. directionRandomizer) {
  61456. if (radius === void 0) { radius = 1; }
  61457. if (angle === void 0) { angle = Math.PI; }
  61458. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  61459. this.directionRandomizer = directionRandomizer;
  61460. /**
  61461. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  61462. */
  61463. this.radiusRange = 1;
  61464. /**
  61465. * Gets or sets a value indicating where on the height the start position should be picked (1 = everywhere, 0 = only surface)
  61466. */
  61467. this.heightRange = 1;
  61468. /**
  61469. * Gets or sets a value indicating if all the particles should be emitted from the spawn point only (the base of the cone)
  61470. */
  61471. this.emitFromSpawnPointOnly = false;
  61472. this.angle = angle;
  61473. this.radius = radius;
  61474. }
  61475. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  61476. /**
  61477. * Gets or sets the radius of the emission cone
  61478. */
  61479. get: function () {
  61480. return this._radius;
  61481. },
  61482. set: function (value) {
  61483. this._radius = value;
  61484. this._buildHeight();
  61485. },
  61486. enumerable: true,
  61487. configurable: true
  61488. });
  61489. Object.defineProperty(ConeParticleEmitter.prototype, "angle", {
  61490. /**
  61491. * Gets or sets the angle of the emission cone
  61492. */
  61493. get: function () {
  61494. return this._angle;
  61495. },
  61496. set: function (value) {
  61497. this._angle = value;
  61498. this._buildHeight();
  61499. },
  61500. enumerable: true,
  61501. configurable: true
  61502. });
  61503. ConeParticleEmitter.prototype._buildHeight = function () {
  61504. if (this._angle !== 0) {
  61505. this._height = this._radius / Math.tan(this._angle / 2);
  61506. }
  61507. else {
  61508. this._height = 1;
  61509. }
  61510. };
  61511. /**
  61512. * Called by the particle System when the direction is computed for the created particle.
  61513. * @param worldMatrix is the world matrix of the particle system
  61514. * @param directionToUpdate is the direction vector to update with the result
  61515. * @param particle is the particle we are computed the direction for
  61516. */
  61517. ConeParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  61518. if (Math.abs(Math.cos(this._angle)) === 1.0) {
  61519. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, 1.0, 0, worldMatrix, directionToUpdate);
  61520. }
  61521. else {
  61522. // measure the direction Vector from the emitter to the particle.
  61523. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  61524. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  61525. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  61526. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  61527. direction.x += randX;
  61528. direction.y += randY;
  61529. direction.z += randZ;
  61530. direction.normalize();
  61531. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  61532. }
  61533. };
  61534. /**
  61535. * Called by the particle System when the position is computed for the created particle.
  61536. * @param worldMatrix is the world matrix of the particle system
  61537. * @param positionToUpdate is the position vector to update with the result
  61538. * @param particle is the particle we are computed the position for
  61539. */
  61540. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  61541. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  61542. var h;
  61543. if (!this.emitFromSpawnPointOnly) {
  61544. h = BABYLON.Scalar.RandomRange(0, this.heightRange);
  61545. // Better distribution in a cone at normal angles.
  61546. h = 1 - h * h;
  61547. }
  61548. else {
  61549. h = 0.0001;
  61550. }
  61551. var radius = this._radius - BABYLON.Scalar.RandomRange(0, this._radius * this.radiusRange);
  61552. radius = radius * h;
  61553. var randX = radius * Math.sin(s);
  61554. var randZ = radius * Math.cos(s);
  61555. var randY = h * this._height;
  61556. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  61557. };
  61558. /**
  61559. * Clones the current emitter and returns a copy of it
  61560. * @returns the new emitter
  61561. */
  61562. ConeParticleEmitter.prototype.clone = function () {
  61563. var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);
  61564. BABYLON.Tools.DeepCopy(this, newOne);
  61565. return newOne;
  61566. };
  61567. /**
  61568. * Called by the GPUParticleSystem to setup the update shader
  61569. * @param effect defines the update shader
  61570. */
  61571. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  61572. effect.setFloat2("radius", this._radius, this.radiusRange);
  61573. effect.setFloat("coneAngle", this._angle);
  61574. effect.setFloat2("height", this._height, this.heightRange);
  61575. effect.setFloat("directionRandomizer", this.directionRandomizer);
  61576. };
  61577. /**
  61578. * Returns a string to use to update the GPU particles update shader
  61579. * @returns a string containng the defines string
  61580. */
  61581. ConeParticleEmitter.prototype.getEffectDefines = function () {
  61582. var defines = "#define CONEEMITTER";
  61583. if (this.emitFromSpawnPointOnly) {
  61584. defines += "\n#define CONEEMITTERSPAWNPOINT";
  61585. }
  61586. return defines;
  61587. };
  61588. /**
  61589. * Returns the string "ConeParticleEmitter"
  61590. * @returns a string containing the class name
  61591. */
  61592. ConeParticleEmitter.prototype.getClassName = function () {
  61593. return "ConeParticleEmitter";
  61594. };
  61595. /**
  61596. * Serializes the particle system to a JSON object.
  61597. * @returns the JSON object
  61598. */
  61599. ConeParticleEmitter.prototype.serialize = function () {
  61600. var serializationObject = {};
  61601. serializationObject.type = this.getClassName();
  61602. serializationObject.radius = this._radius;
  61603. serializationObject.angle = this._angle;
  61604. serializationObject.directionRandomizer = this.directionRandomizer;
  61605. return serializationObject;
  61606. };
  61607. /**
  61608. * Parse properties from a JSON object
  61609. * @param serializationObject defines the JSON object
  61610. */
  61611. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  61612. this.radius = serializationObject.radius;
  61613. this.angle = serializationObject.angle;
  61614. this.directionRandomizer = serializationObject.directionRandomizer;
  61615. };
  61616. return ConeParticleEmitter;
  61617. }());
  61618. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  61619. })(BABYLON || (BABYLON = {}));
  61620. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  61621. var BABYLON;
  61622. (function (BABYLON) {
  61623. /**
  61624. * Particle emitter emitting particles from the inside of a sphere.
  61625. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  61626. */
  61627. var SphereParticleEmitter = /** @class */ (function () {
  61628. /**
  61629. * Creates a new instance SphereParticleEmitter
  61630. * @param radius the radius of the emission sphere (1 by default)
  61631. * @param radiusRange the range of the emission sphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  61632. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  61633. */
  61634. function SphereParticleEmitter(
  61635. /**
  61636. * The radius of the emission sphere.
  61637. */
  61638. radius,
  61639. /**
  61640. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  61641. */
  61642. radiusRange,
  61643. /**
  61644. * How much to randomize the particle direction [0-1].
  61645. */
  61646. directionRandomizer) {
  61647. if (radius === void 0) { radius = 1; }
  61648. if (radiusRange === void 0) { radiusRange = 1; }
  61649. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  61650. this.radius = radius;
  61651. this.radiusRange = radiusRange;
  61652. this.directionRandomizer = directionRandomizer;
  61653. }
  61654. /**
  61655. * Called by the particle System when the direction is computed for the created particle.
  61656. * @param worldMatrix is the world matrix of the particle system
  61657. * @param directionToUpdate is the direction vector to update with the result
  61658. * @param particle is the particle we are computed the direction for
  61659. */
  61660. SphereParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  61661. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  61662. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  61663. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  61664. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  61665. direction.x += randX;
  61666. direction.y += randY;
  61667. direction.z += randZ;
  61668. direction.normalize();
  61669. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  61670. };
  61671. /**
  61672. * Called by the particle System when the position is computed for the created particle.
  61673. * @param worldMatrix is the world matrix of the particle system
  61674. * @param positionToUpdate is the position vector to update with the result
  61675. * @param particle is the particle we are computed the position for
  61676. */
  61677. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  61678. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  61679. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  61680. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  61681. var theta = Math.acos(2 * v - 1);
  61682. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  61683. var randY = randRadius * Math.cos(theta);
  61684. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  61685. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  61686. };
  61687. /**
  61688. * Clones the current emitter and returns a copy of it
  61689. * @returns the new emitter
  61690. */
  61691. SphereParticleEmitter.prototype.clone = function () {
  61692. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  61693. BABYLON.Tools.DeepCopy(this, newOne);
  61694. return newOne;
  61695. };
  61696. /**
  61697. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  61698. * @param effect defines the update shader
  61699. */
  61700. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  61701. effect.setFloat("radius", this.radius);
  61702. effect.setFloat("radiusRange", this.radiusRange);
  61703. effect.setFloat("directionRandomizer", this.directionRandomizer);
  61704. };
  61705. /**
  61706. * Returns a string to use to update the GPU particles update shader
  61707. * @returns a string containng the defines string
  61708. */
  61709. SphereParticleEmitter.prototype.getEffectDefines = function () {
  61710. return "#define SPHEREEMITTER";
  61711. };
  61712. /**
  61713. * Returns the string "SphereParticleEmitter"
  61714. * @returns a string containing the class name
  61715. */
  61716. SphereParticleEmitter.prototype.getClassName = function () {
  61717. return "SphereParticleEmitter";
  61718. };
  61719. /**
  61720. * Serializes the particle system to a JSON object.
  61721. * @returns the JSON object
  61722. */
  61723. SphereParticleEmitter.prototype.serialize = function () {
  61724. var serializationObject = {};
  61725. serializationObject.type = this.getClassName();
  61726. serializationObject.radius = this.radius;
  61727. serializationObject.radiusRange = this.radiusRange;
  61728. serializationObject.directionRandomizer = this.directionRandomizer;
  61729. return serializationObject;
  61730. };
  61731. /**
  61732. * Parse properties from a JSON object
  61733. * @param serializationObject defines the JSON object
  61734. */
  61735. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  61736. this.radius = serializationObject.radius;
  61737. this.radiusRange = serializationObject.radiusRange;
  61738. this.directionRandomizer = serializationObject.directionRandomizer;
  61739. };
  61740. return SphereParticleEmitter;
  61741. }());
  61742. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  61743. /**
  61744. * Particle emitter emitting particles from the inside of a sphere.
  61745. * It emits the particles randomly between two vectors.
  61746. */
  61747. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  61748. __extends(SphereDirectedParticleEmitter, _super);
  61749. /**
  61750. * Creates a new instance SphereDirectedParticleEmitter
  61751. * @param radius the radius of the emission sphere (1 by default)
  61752. * @param direction1 the min limit of the emission direction (up vector by default)
  61753. * @param direction2 the max limit of the emission direction (up vector by default)
  61754. */
  61755. function SphereDirectedParticleEmitter(radius,
  61756. /**
  61757. * The min limit of the emission direction.
  61758. */
  61759. direction1,
  61760. /**
  61761. * The max limit of the emission direction.
  61762. */
  61763. direction2) {
  61764. if (radius === void 0) { radius = 1; }
  61765. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  61766. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  61767. var _this = _super.call(this, radius) || this;
  61768. _this.direction1 = direction1;
  61769. _this.direction2 = direction2;
  61770. return _this;
  61771. }
  61772. /**
  61773. * Called by the particle System when the direction is computed for the created particle.
  61774. * @param worldMatrix is the world matrix of the particle system
  61775. * @param directionToUpdate is the direction vector to update with the result
  61776. * @param particle is the particle we are computed the direction for
  61777. */
  61778. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  61779. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  61780. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  61781. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  61782. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  61783. };
  61784. /**
  61785. * Clones the current emitter and returns a copy of it
  61786. * @returns the new emitter
  61787. */
  61788. SphereDirectedParticleEmitter.prototype.clone = function () {
  61789. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  61790. BABYLON.Tools.DeepCopy(this, newOne);
  61791. return newOne;
  61792. };
  61793. /**
  61794. * Called by the GPUParticleSystem to setup the update shader
  61795. * @param effect defines the update shader
  61796. */
  61797. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  61798. effect.setFloat("radius", this.radius);
  61799. effect.setFloat("radiusRange", this.radiusRange);
  61800. effect.setVector3("direction1", this.direction1);
  61801. effect.setVector3("direction2", this.direction2);
  61802. };
  61803. /**
  61804. * Returns a string to use to update the GPU particles update shader
  61805. * @returns a string containng the defines string
  61806. */
  61807. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  61808. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  61809. };
  61810. /**
  61811. * Returns the string "SphereDirectedParticleEmitter"
  61812. * @returns a string containing the class name
  61813. */
  61814. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  61815. return "SphereDirectedParticleEmitter";
  61816. };
  61817. /**
  61818. * Serializes the particle system to a JSON object.
  61819. * @returns the JSON object
  61820. */
  61821. SphereDirectedParticleEmitter.prototype.serialize = function () {
  61822. var serializationObject = _super.prototype.serialize.call(this);
  61823. serializationObject.direction1 = this.direction1.asArray();
  61824. serializationObject.direction2 = this.direction2.asArray();
  61825. return serializationObject;
  61826. };
  61827. /**
  61828. * Parse properties from a JSON object
  61829. * @param serializationObject defines the JSON object
  61830. */
  61831. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  61832. _super.prototype.parse.call(this, serializationObject);
  61833. this.direction1.copyFrom(serializationObject.direction1);
  61834. this.direction2.copyFrom(serializationObject.direction2);
  61835. };
  61836. return SphereDirectedParticleEmitter;
  61837. }(SphereParticleEmitter));
  61838. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  61839. })(BABYLON || (BABYLON = {}));
  61840. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  61841. var BABYLON;
  61842. (function (BABYLON) {
  61843. /**
  61844. * Particle emitter emitting particles from the inside of a hemisphere.
  61845. * It emits the particles alongside the hemisphere radius. The emission direction might be randomized.
  61846. */
  61847. var HemisphericParticleEmitter = /** @class */ (function () {
  61848. /**
  61849. * Creates a new instance HemisphericParticleEmitter
  61850. * @param radius the radius of the emission hemisphere (1 by default)
  61851. * @param radiusRange the range of the emission hemisphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  61852. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  61853. */
  61854. function HemisphericParticleEmitter(
  61855. /**
  61856. * The radius of the emission hemisphere.
  61857. */
  61858. radius,
  61859. /**
  61860. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  61861. */
  61862. radiusRange,
  61863. /**
  61864. * How much to randomize the particle direction [0-1].
  61865. */
  61866. directionRandomizer) {
  61867. if (radius === void 0) { radius = 1; }
  61868. if (radiusRange === void 0) { radiusRange = 1; }
  61869. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  61870. this.radius = radius;
  61871. this.radiusRange = radiusRange;
  61872. this.directionRandomizer = directionRandomizer;
  61873. }
  61874. /**
  61875. * Called by the particle System when the direction is computed for the created particle.
  61876. * @param worldMatrix is the world matrix of the particle system
  61877. * @param directionToUpdate is the direction vector to update with the result
  61878. * @param particle is the particle we are computed the direction for
  61879. */
  61880. HemisphericParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  61881. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  61882. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  61883. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  61884. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  61885. direction.x += randX;
  61886. direction.y += randY;
  61887. direction.z += randZ;
  61888. direction.normalize();
  61889. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  61890. };
  61891. /**
  61892. * Called by the particle System when the position is computed for the created particle.
  61893. * @param worldMatrix is the world matrix of the particle system
  61894. * @param positionToUpdate is the position vector to update with the result
  61895. * @param particle is the particle we are computed the position for
  61896. */
  61897. HemisphericParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  61898. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  61899. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  61900. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  61901. var theta = Math.acos(2 * v - 1);
  61902. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  61903. var randY = randRadius * Math.cos(theta);
  61904. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  61905. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, Math.abs(randY), randZ, worldMatrix, positionToUpdate);
  61906. };
  61907. /**
  61908. * Clones the current emitter and returns a copy of it
  61909. * @returns the new emitter
  61910. */
  61911. HemisphericParticleEmitter.prototype.clone = function () {
  61912. var newOne = new HemisphericParticleEmitter(this.radius, this.directionRandomizer);
  61913. BABYLON.Tools.DeepCopy(this, newOne);
  61914. return newOne;
  61915. };
  61916. /**
  61917. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  61918. * @param effect defines the update shader
  61919. */
  61920. HemisphericParticleEmitter.prototype.applyToShader = function (effect) {
  61921. effect.setFloat("radius", this.radius);
  61922. effect.setFloat("radiusRange", this.radiusRange);
  61923. effect.setFloat("directionRandomizer", this.directionRandomizer);
  61924. };
  61925. /**
  61926. * Returns a string to use to update the GPU particles update shader
  61927. * @returns a string containng the defines string
  61928. */
  61929. HemisphericParticleEmitter.prototype.getEffectDefines = function () {
  61930. return "#define HEMISPHERICEMITTER";
  61931. };
  61932. /**
  61933. * Returns the string "HemisphericParticleEmitter"
  61934. * @returns a string containing the class name
  61935. */
  61936. HemisphericParticleEmitter.prototype.getClassName = function () {
  61937. return "HemisphericParticleEmitter";
  61938. };
  61939. /**
  61940. * Serializes the particle system to a JSON object.
  61941. * @returns the JSON object
  61942. */
  61943. HemisphericParticleEmitter.prototype.serialize = function () {
  61944. var serializationObject = {};
  61945. serializationObject.type = this.getClassName();
  61946. serializationObject.radius = this.radius;
  61947. serializationObject.radiusRange = this.radiusRange;
  61948. serializationObject.directionRandomizer = this.directionRandomizer;
  61949. return serializationObject;
  61950. };
  61951. /**
  61952. * Parse properties from a JSON object
  61953. * @param serializationObject defines the JSON object
  61954. */
  61955. HemisphericParticleEmitter.prototype.parse = function (serializationObject) {
  61956. this.radius = serializationObject.radius;
  61957. this.radiusRange = serializationObject.radiusRange;
  61958. this.directionRandomizer = serializationObject.directionRandomizer;
  61959. };
  61960. return HemisphericParticleEmitter;
  61961. }());
  61962. BABYLON.HemisphericParticleEmitter = HemisphericParticleEmitter;
  61963. })(BABYLON || (BABYLON = {}));
  61964. //# sourceMappingURL=babylon.hemisphericParticleEmitter.js.map
  61965. var BABYLON;
  61966. (function (BABYLON) {
  61967. /**
  61968. * Particle emitter emitting particles from a point.
  61969. * It emits the particles randomly between 2 given directions.
  61970. */
  61971. var PointParticleEmitter = /** @class */ (function () {
  61972. /**
  61973. * Creates a new instance PointParticleEmitter
  61974. */
  61975. function PointParticleEmitter() {
  61976. /**
  61977. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  61978. */
  61979. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  61980. /**
  61981. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  61982. */
  61983. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  61984. }
  61985. /**
  61986. * Called by the particle System when the direction is computed for the created particle.
  61987. * @param worldMatrix is the world matrix of the particle system
  61988. * @param directionToUpdate is the direction vector to update with the result
  61989. * @param particle is the particle we are computed the direction for
  61990. */
  61991. PointParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  61992. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  61993. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  61994. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  61995. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  61996. };
  61997. /**
  61998. * Called by the particle System when the position is computed for the created particle.
  61999. * @param worldMatrix is the world matrix of the particle system
  62000. * @param positionToUpdate is the position vector to update with the result
  62001. * @param particle is the particle we are computed the position for
  62002. */
  62003. PointParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  62004. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0, 0, 0, worldMatrix, positionToUpdate);
  62005. };
  62006. /**
  62007. * Clones the current emitter and returns a copy of it
  62008. * @returns the new emitter
  62009. */
  62010. PointParticleEmitter.prototype.clone = function () {
  62011. var newOne = new PointParticleEmitter();
  62012. BABYLON.Tools.DeepCopy(this, newOne);
  62013. return newOne;
  62014. };
  62015. /**
  62016. * Called by the GPUParticleSystem to setup the update shader
  62017. * @param effect defines the update shader
  62018. */
  62019. PointParticleEmitter.prototype.applyToShader = function (effect) {
  62020. effect.setVector3("direction1", this.direction1);
  62021. effect.setVector3("direction2", this.direction2);
  62022. };
  62023. /**
  62024. * Returns a string to use to update the GPU particles update shader
  62025. * @returns a string containng the defines string
  62026. */
  62027. PointParticleEmitter.prototype.getEffectDefines = function () {
  62028. return "#define POINTEMITTER";
  62029. };
  62030. /**
  62031. * Returns the string "PointParticleEmitter"
  62032. * @returns a string containing the class name
  62033. */
  62034. PointParticleEmitter.prototype.getClassName = function () {
  62035. return "PointParticleEmitter";
  62036. };
  62037. /**
  62038. * Serializes the particle system to a JSON object.
  62039. * @returns the JSON object
  62040. */
  62041. PointParticleEmitter.prototype.serialize = function () {
  62042. var serializationObject = {};
  62043. serializationObject.type = this.getClassName();
  62044. serializationObject.direction1 = this.direction1.asArray();
  62045. serializationObject.direction2 = this.direction2.asArray();
  62046. return serializationObject;
  62047. };
  62048. /**
  62049. * Parse properties from a JSON object
  62050. * @param serializationObject defines the JSON object
  62051. */
  62052. PointParticleEmitter.prototype.parse = function (serializationObject) {
  62053. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  62054. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  62055. };
  62056. return PointParticleEmitter;
  62057. }());
  62058. BABYLON.PointParticleEmitter = PointParticleEmitter;
  62059. })(BABYLON || (BABYLON = {}));
  62060. //# sourceMappingURL=babylon.pointParticleEmitter.js.map
  62061. var BABYLON;
  62062. (function (BABYLON) {
  62063. // Adds the parsers to the scene parsers.
  62064. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedData, scene, container, rootUrl) {
  62065. var individualParser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  62066. if (!individualParser) {
  62067. return;
  62068. }
  62069. // Particles Systems
  62070. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  62071. for (var index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  62072. var parsedParticleSystem = parsedData.particleSystems[index];
  62073. container.particleSystems.push(individualParser(parsedParticleSystem, scene, rootUrl));
  62074. }
  62075. }
  62076. });
  62077. BABYLON.AbstractScene.AddIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedParticleSystem, scene, rootUrl) {
  62078. if (parsedParticleSystem.activeParticleCount) {
  62079. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  62080. return ps;
  62081. }
  62082. else {
  62083. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  62084. return ps;
  62085. }
  62086. });
  62087. BABYLON.Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  62088. if (uniformsNames === void 0) { uniformsNames = []; }
  62089. if (samplers === void 0) { samplers = []; }
  62090. if (defines === void 0) { defines = ""; }
  62091. var attributesNamesOrOptions = BABYLON.ParticleSystem._GetAttributeNamesOrOptions();
  62092. var effectCreationOption = BABYLON.ParticleSystem._GetEffectCreationOptions();
  62093. if (defines.indexOf(" BILLBOARD") === -1) {
  62094. defines += "\n#define BILLBOARD\n";
  62095. }
  62096. if (samplers.indexOf("diffuseSampler") === -1) {
  62097. samplers.push("diffuseSampler");
  62098. }
  62099. return this.createEffect({
  62100. vertex: "particles",
  62101. fragmentElement: fragmentName
  62102. }, attributesNamesOrOptions, effectCreationOption.concat(uniformsNames), samplers, defines, fallbacks, onCompiled, onError);
  62103. };
  62104. BABYLON.Mesh.prototype.getEmittedParticleSystems = function () {
  62105. var results = new Array();
  62106. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  62107. var particleSystem = this.getScene().particleSystems[index];
  62108. if (particleSystem.emitter === this) {
  62109. results.push(particleSystem);
  62110. }
  62111. }
  62112. return results;
  62113. };
  62114. BABYLON.Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  62115. var results = new Array();
  62116. var descendants = this.getDescendants();
  62117. descendants.push(this);
  62118. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  62119. var particleSystem = this.getScene().particleSystems[index];
  62120. var emitter = particleSystem.emitter;
  62121. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  62122. results.push(particleSystem);
  62123. }
  62124. }
  62125. return results;
  62126. };
  62127. })(BABYLON || (BABYLON = {}));
  62128. //# sourceMappingURL=babylon.particleSystemComponent.js.map
  62129. var BABYLON;
  62130. (function (BABYLON) {
  62131. /**
  62132. * Type of sub emitter
  62133. */
  62134. var SubEmitterType;
  62135. (function (SubEmitterType) {
  62136. /**
  62137. * Attached to the particle over it's lifetime
  62138. */
  62139. SubEmitterType[SubEmitterType["ATTACHED"] = 0] = "ATTACHED";
  62140. /**
  62141. * Created when the particle dies
  62142. */
  62143. SubEmitterType[SubEmitterType["END"] = 1] = "END";
  62144. })(SubEmitterType = BABYLON.SubEmitterType || (BABYLON.SubEmitterType = {}));
  62145. /**
  62146. * Sub emitter class used to emit particles from an existing particle
  62147. */
  62148. var SubEmitter = /** @class */ (function () {
  62149. /**
  62150. * Creates a sub emitter
  62151. * @param particleSystem the particle system to be used by the sub emitter
  62152. */
  62153. function SubEmitter(
  62154. /**
  62155. * the particle system to be used by the sub emitter
  62156. */
  62157. particleSystem) {
  62158. this.particleSystem = particleSystem;
  62159. /**
  62160. * Type of the submitter (Default: END)
  62161. */
  62162. this.type = SubEmitterType.END;
  62163. /**
  62164. * If the particle should inherit the direction from the particle it's attached to. (+Y will face the direction the particle is moving) (Default: false)
  62165. * Note: This only is supported when using an emitter of type Mesh
  62166. */
  62167. this.inheritDirection = false;
  62168. /**
  62169. * How much of the attached particles speed should be added to the sub emitted particle (default: 0)
  62170. */
  62171. this.inheritedVelocityAmount = 0;
  62172. }
  62173. /**
  62174. * Clones the sub emitter
  62175. * @returns the cloned sub emitter
  62176. */
  62177. SubEmitter.prototype.clone = function () {
  62178. // Clone particle system
  62179. var emitter = this.particleSystem.emitter;
  62180. if (!emitter) {
  62181. emitter = new BABYLON.Vector3();
  62182. }
  62183. else if (emitter instanceof BABYLON.Vector3) {
  62184. emitter = emitter.clone();
  62185. }
  62186. else if (emitter instanceof BABYLON.AbstractMesh) {
  62187. emitter = new BABYLON.Mesh("", emitter.getScene());
  62188. emitter.isVisible = false;
  62189. }
  62190. var clone = new SubEmitter(this.particleSystem.clone("", emitter));
  62191. // Clone properties
  62192. clone.type = this.type;
  62193. clone.inheritDirection = this.inheritDirection;
  62194. clone.inheritedVelocityAmount = this.inheritedVelocityAmount;
  62195. clone.particleSystem._disposeEmitterOnDispose = true;
  62196. clone.particleSystem.disposeOnStop = true;
  62197. return clone;
  62198. };
  62199. /**
  62200. * Serialize current object to a JSON object
  62201. * @returns the serialized object
  62202. */
  62203. SubEmitter.prototype.serialize = function () {
  62204. var serializationObject = {};
  62205. serializationObject.type = this.type;
  62206. serializationObject.inheritDirection = this.inheritDirection;
  62207. serializationObject.inheritedVelocityAmount = this.inheritedVelocityAmount;
  62208. serializationObject.particleSystem = this.particleSystem.serialize();
  62209. return serializationObject;
  62210. };
  62211. /**
  62212. * Creates a new SubEmitter from a serialized JSON version
  62213. * @param serializationObject defines the JSON object to read from
  62214. * @param scene defines the hosting scene
  62215. * @param rootUrl defines the rootUrl for data loading
  62216. * @returns a new SubEmitter
  62217. */
  62218. SubEmitter.Parse = function (serializationObject, scene, rootUrl) {
  62219. var system = serializationObject.particleSystem;
  62220. var subEmitter = new SubEmitter(BABYLON.ParticleSystem.Parse(system, scene, rootUrl));
  62221. subEmitter.type = serializationObject.type;
  62222. subEmitter.inheritDirection = serializationObject.inheritDirection;
  62223. subEmitter.inheritedVelocityAmount = serializationObject.inheritedVelocityAmount;
  62224. subEmitter.particleSystem._isSubEmitter = true;
  62225. return subEmitter;
  62226. };
  62227. /** Release associated resources */
  62228. SubEmitter.prototype.dispose = function () {
  62229. this.particleSystem.dispose();
  62230. };
  62231. return SubEmitter;
  62232. }());
  62233. BABYLON.SubEmitter = SubEmitter;
  62234. })(BABYLON || (BABYLON = {}));
  62235. //# sourceMappingURL=babylon.subEmitter.js.map
  62236. var BABYLON;
  62237. (function (BABYLON) {
  62238. /**
  62239. * The ShaderMaterial object has the necessary methods to pass data from your scene to the Vertex and Fragment Shaders and returns a material that can be applied to any mesh.
  62240. *
  62241. * This returned material effects how the mesh will look based on the code in the shaders.
  62242. *
  62243. * @see http://doc.babylonjs.com/how_to/shader_material
  62244. */
  62245. var ShaderMaterial = /** @class */ (function (_super) {
  62246. __extends(ShaderMaterial, _super);
  62247. /**
  62248. * Instantiate a new shader material.
  62249. * The ShaderMaterial object has the necessary methods to pass data from your scene to the Vertex and Fragment Shaders and returns a material that can be applied to any mesh.
  62250. * This returned material effects how the mesh will look based on the code in the shaders.
  62251. * @see http://doc.babylonjs.com/how_to/shader_material
  62252. * @param name Define the name of the material in the scene
  62253. * @param scene Define the scene the material belongs to
  62254. * @param shaderPath Defines the route to the shader code in one of three ways:
  62255. * - object - { vertex: "custom", fragment: "custom" }, used with BABYLON.Effect.ShadersStore["customVertexShader"] and BABYLON.Effect.ShadersStore["customFragmentShader"]
  62256. * - object - { vertexElement: "vertexShaderCode", fragmentElement: "fragmentShaderCode" }, used with shader code in <script> tags
  62257. * - string - "./COMMON_NAME", used with external files COMMON_NAME.vertex.fx and COMMON_NAME.fragment.fx in index.html folder.
  62258. * @param options Define the options used to create the shader
  62259. */
  62260. function ShaderMaterial(name, scene, shaderPath, options) {
  62261. if (options === void 0) { options = {}; }
  62262. var _this = _super.call(this, name, scene) || this;
  62263. _this._textures = {};
  62264. _this._textureArrays = {};
  62265. _this._floats = {};
  62266. _this._ints = {};
  62267. _this._floatsArrays = {};
  62268. _this._colors3 = {};
  62269. _this._colors3Arrays = {};
  62270. _this._colors4 = {};
  62271. _this._vectors2 = {};
  62272. _this._vectors3 = {};
  62273. _this._vectors4 = {};
  62274. _this._matrices = {};
  62275. _this._matrices3x3 = {};
  62276. _this._matrices2x2 = {};
  62277. _this._vectors2Arrays = {};
  62278. _this._vectors3Arrays = {};
  62279. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  62280. _this._shaderPath = shaderPath;
  62281. _this._options = __assign({ needAlphaBlending: false, needAlphaTesting: false, attributes: ["position", "normal", "uv"], uniforms: ["worldViewProjection"], uniformBuffers: [], samplers: [], defines: [] }, options);
  62282. return _this;
  62283. }
  62284. /**
  62285. * Gets the current class name of the material e.g. "ShaderMaterial"
  62286. * Mainly use in serialization.
  62287. * @returns the class name
  62288. */
  62289. ShaderMaterial.prototype.getClassName = function () {
  62290. return "ShaderMaterial";
  62291. };
  62292. /**
  62293. * Specifies if the material will require alpha blending
  62294. * @returns a boolean specifying if alpha blending is needed
  62295. */
  62296. ShaderMaterial.prototype.needAlphaBlending = function () {
  62297. return (this.alpha < 1.0) || this._options.needAlphaBlending;
  62298. };
  62299. /**
  62300. * Specifies if this material should be rendered in alpha test mode
  62301. * @returns a boolean specifying if an alpha test is needed.
  62302. */
  62303. ShaderMaterial.prototype.needAlphaTesting = function () {
  62304. return this._options.needAlphaTesting;
  62305. };
  62306. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  62307. if (this._options.uniforms.indexOf(uniformName) === -1) {
  62308. this._options.uniforms.push(uniformName);
  62309. }
  62310. };
  62311. /**
  62312. * Set a texture in the shader.
  62313. * @param name Define the name of the uniform samplers as defined in the shader
  62314. * @param texture Define the texture to bind to this sampler
  62315. * @return the material itself allowing "fluent" like uniform updates
  62316. */
  62317. ShaderMaterial.prototype.setTexture = function (name, texture) {
  62318. if (this._options.samplers.indexOf(name) === -1) {
  62319. this._options.samplers.push(name);
  62320. }
  62321. this._textures[name] = texture;
  62322. return this;
  62323. };
  62324. /**
  62325. * Set a texture array in the shader.
  62326. * @param name Define the name of the uniform sampler array as defined in the shader
  62327. * @param textures Define the list of textures to bind to this sampler
  62328. * @return the material itself allowing "fluent" like uniform updates
  62329. */
  62330. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  62331. if (this._options.samplers.indexOf(name) === -1) {
  62332. this._options.samplers.push(name);
  62333. }
  62334. this._checkUniform(name);
  62335. this._textureArrays[name] = textures;
  62336. return this;
  62337. };
  62338. /**
  62339. * Set a float in the shader.
  62340. * @param name Define the name of the uniform as defined in the shader
  62341. * @param value Define the value to give to the uniform
  62342. * @return the material itself allowing "fluent" like uniform updates
  62343. */
  62344. ShaderMaterial.prototype.setFloat = function (name, value) {
  62345. this._checkUniform(name);
  62346. this._floats[name] = value;
  62347. return this;
  62348. };
  62349. /**
  62350. * Set a int in the shader.
  62351. * @param name Define the name of the uniform as defined in the shader
  62352. * @param value Define the value to give to the uniform
  62353. * @return the material itself allowing "fluent" like uniform updates
  62354. */
  62355. ShaderMaterial.prototype.setInt = function (name, value) {
  62356. this._checkUniform(name);
  62357. this._ints[name] = value;
  62358. return this;
  62359. };
  62360. /**
  62361. * Set an array of floats in the shader.
  62362. * @param name Define the name of the uniform as defined in the shader
  62363. * @param value Define the value to give to the uniform
  62364. * @return the material itself allowing "fluent" like uniform updates
  62365. */
  62366. ShaderMaterial.prototype.setFloats = function (name, value) {
  62367. this._checkUniform(name);
  62368. this._floatsArrays[name] = value;
  62369. return this;
  62370. };
  62371. /**
  62372. * Set a vec3 in the shader from a Color3.
  62373. * @param name Define the name of the uniform as defined in the shader
  62374. * @param value Define the value to give to the uniform
  62375. * @return the material itself allowing "fluent" like uniform updates
  62376. */
  62377. ShaderMaterial.prototype.setColor3 = function (name, value) {
  62378. this._checkUniform(name);
  62379. this._colors3[name] = value;
  62380. return this;
  62381. };
  62382. /**
  62383. * Set a vec3 array in the shader from a Color3 array.
  62384. * @param name Define the name of the uniform as defined in the shader
  62385. * @param value Define the value to give to the uniform
  62386. * @return the material itself allowing "fluent" like uniform updates
  62387. */
  62388. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  62389. this._checkUniform(name);
  62390. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  62391. color.toArray(arr, arr.length);
  62392. return arr;
  62393. }, []);
  62394. return this;
  62395. };
  62396. /**
  62397. * Set a vec4 in the shader from a Color4.
  62398. * @param name Define the name of the uniform as defined in the shader
  62399. * @param value Define the value to give to the uniform
  62400. * @return the material itself allowing "fluent" like uniform updates
  62401. */
  62402. ShaderMaterial.prototype.setColor4 = function (name, value) {
  62403. this._checkUniform(name);
  62404. this._colors4[name] = value;
  62405. return this;
  62406. };
  62407. /**
  62408. * Set a vec2 in the shader from a Vector2.
  62409. * @param name Define the name of the uniform as defined in the shader
  62410. * @param value Define the value to give to the uniform
  62411. * @return the material itself allowing "fluent" like uniform updates
  62412. */
  62413. ShaderMaterial.prototype.setVector2 = function (name, value) {
  62414. this._checkUniform(name);
  62415. this._vectors2[name] = value;
  62416. return this;
  62417. };
  62418. /**
  62419. * Set a vec3 in the shader from a Vector3.
  62420. * @param name Define the name of the uniform as defined in the shader
  62421. * @param value Define the value to give to the uniform
  62422. * @return the material itself allowing "fluent" like uniform updates
  62423. */
  62424. ShaderMaterial.prototype.setVector3 = function (name, value) {
  62425. this._checkUniform(name);
  62426. this._vectors3[name] = value;
  62427. return this;
  62428. };
  62429. /**
  62430. * Set a vec4 in the shader from a Vector4.
  62431. * @param name Define the name of the uniform as defined in the shader
  62432. * @param value Define the value to give to the uniform
  62433. * @return the material itself allowing "fluent" like uniform updates
  62434. */
  62435. ShaderMaterial.prototype.setVector4 = function (name, value) {
  62436. this._checkUniform(name);
  62437. this._vectors4[name] = value;
  62438. return this;
  62439. };
  62440. /**
  62441. * Set a mat4 in the shader from a Matrix.
  62442. * @param name Define the name of the uniform as defined in the shader
  62443. * @param value Define the value to give to the uniform
  62444. * @return the material itself allowing "fluent" like uniform updates
  62445. */
  62446. ShaderMaterial.prototype.setMatrix = function (name, value) {
  62447. this._checkUniform(name);
  62448. this._matrices[name] = value;
  62449. return this;
  62450. };
  62451. /**
  62452. * Set a mat3 in the shader from a Float32Array.
  62453. * @param name Define the name of the uniform as defined in the shader
  62454. * @param value Define the value to give to the uniform
  62455. * @return the material itself allowing "fluent" like uniform updates
  62456. */
  62457. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  62458. this._checkUniform(name);
  62459. this._matrices3x3[name] = value;
  62460. return this;
  62461. };
  62462. /**
  62463. * Set a mat2 in the shader from a Float32Array.
  62464. * @param name Define the name of the uniform as defined in the shader
  62465. * @param value Define the value to give to the uniform
  62466. * @return the material itself allowing "fluent" like uniform updates
  62467. */
  62468. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  62469. this._checkUniform(name);
  62470. this._matrices2x2[name] = value;
  62471. return this;
  62472. };
  62473. /**
  62474. * Set a vec2 array in the shader from a number array.
  62475. * @param name Define the name of the uniform as defined in the shader
  62476. * @param value Define the value to give to the uniform
  62477. * @return the material itself allowing "fluent" like uniform updates
  62478. */
  62479. ShaderMaterial.prototype.setArray2 = function (name, value) {
  62480. this._checkUniform(name);
  62481. this._vectors2Arrays[name] = value;
  62482. return this;
  62483. };
  62484. /**
  62485. * Set a vec3 array in the shader from a number array.
  62486. * @param name Define the name of the uniform as defined in the shader
  62487. * @param value Define the value to give to the uniform
  62488. * @return the material itself allowing "fluent" like uniform updates
  62489. */
  62490. ShaderMaterial.prototype.setArray3 = function (name, value) {
  62491. this._checkUniform(name);
  62492. this._vectors3Arrays[name] = value;
  62493. return this;
  62494. };
  62495. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  62496. if (!mesh) {
  62497. return true;
  62498. }
  62499. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  62500. return false;
  62501. }
  62502. return false;
  62503. };
  62504. /**
  62505. * Checks if the material is ready to render the requested mesh
  62506. * @param mesh Define the mesh to render
  62507. * @param useInstances Define whether or not the material is used with instances
  62508. * @returns true if ready, otherwise false
  62509. */
  62510. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  62511. var scene = this.getScene();
  62512. var engine = scene.getEngine();
  62513. if (!this.checkReadyOnEveryCall) {
  62514. if (this._renderId === scene.getRenderId()) {
  62515. if (this._checkCache(scene, mesh, useInstances)) {
  62516. return true;
  62517. }
  62518. }
  62519. }
  62520. // Instances
  62521. var defines = [];
  62522. var attribs = [];
  62523. var fallbacks = new BABYLON.EffectFallbacks();
  62524. for (var index = 0; index < this._options.defines.length; index++) {
  62525. defines.push(this._options.defines[index]);
  62526. }
  62527. for (var index = 0; index < this._options.attributes.length; index++) {
  62528. attribs.push(this._options.attributes[index]);
  62529. }
  62530. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  62531. attribs.push(BABYLON.VertexBuffer.ColorKind);
  62532. defines.push("#define VERTEXCOLOR");
  62533. }
  62534. if (useInstances) {
  62535. defines.push("#define INSTANCES");
  62536. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  62537. }
  62538. // Bones
  62539. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  62540. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  62541. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  62542. if (mesh.numBoneInfluencers > 4) {
  62543. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  62544. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  62545. }
  62546. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  62547. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  62548. fallbacks.addCPUSkinningFallback(0, mesh);
  62549. if (this._options.uniforms.indexOf("mBones") === -1) {
  62550. this._options.uniforms.push("mBones");
  62551. }
  62552. }
  62553. else {
  62554. defines.push("#define NUM_BONE_INFLUENCERS 0");
  62555. }
  62556. // Textures
  62557. for (var name in this._textures) {
  62558. if (!this._textures[name].isReady()) {
  62559. return false;
  62560. }
  62561. }
  62562. // Alpha test
  62563. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  62564. defines.push("#define ALPHATEST");
  62565. }
  62566. var previousEffect = this._effect;
  62567. var join = defines.join("\n");
  62568. this._effect = engine.createEffect(this._shaderPath, {
  62569. attributes: attribs,
  62570. uniformsNames: this._options.uniforms,
  62571. uniformBuffersNames: this._options.uniformBuffers,
  62572. samplers: this._options.samplers,
  62573. defines: join,
  62574. fallbacks: fallbacks,
  62575. onCompiled: this.onCompiled,
  62576. onError: this.onError
  62577. }, engine);
  62578. if (!this._effect.isReady()) {
  62579. return false;
  62580. }
  62581. if (previousEffect !== this._effect) {
  62582. scene.resetCachedMaterial();
  62583. }
  62584. this._renderId = scene.getRenderId();
  62585. return true;
  62586. };
  62587. /**
  62588. * Binds the world matrix to the material
  62589. * @param world defines the world transformation matrix
  62590. */
  62591. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  62592. var scene = this.getScene();
  62593. if (!this._effect) {
  62594. return;
  62595. }
  62596. if (this._options.uniforms.indexOf("world") !== -1) {
  62597. this._effect.setMatrix("world", world);
  62598. }
  62599. if (this._options.uniforms.indexOf("worldView") !== -1) {
  62600. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  62601. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  62602. }
  62603. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  62604. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  62605. }
  62606. };
  62607. /**
  62608. * Binds the material to the mesh
  62609. * @param world defines the world transformation matrix
  62610. * @param mesh defines the mesh to bind the material to
  62611. */
  62612. ShaderMaterial.prototype.bind = function (world, mesh) {
  62613. // Std values
  62614. this.bindOnlyWorldMatrix(world);
  62615. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  62616. if (this._options.uniforms.indexOf("view") !== -1) {
  62617. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  62618. }
  62619. if (this._options.uniforms.indexOf("projection") !== -1) {
  62620. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  62621. }
  62622. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  62623. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  62624. }
  62625. // Bones
  62626. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  62627. var name;
  62628. // Texture
  62629. for (name in this._textures) {
  62630. this._effect.setTexture(name, this._textures[name]);
  62631. }
  62632. // Texture arrays
  62633. for (name in this._textureArrays) {
  62634. this._effect.setTextureArray(name, this._textureArrays[name]);
  62635. }
  62636. // Int
  62637. for (name in this._ints) {
  62638. this._effect.setInt(name, this._ints[name]);
  62639. }
  62640. // Float
  62641. for (name in this._floats) {
  62642. this._effect.setFloat(name, this._floats[name]);
  62643. }
  62644. // Floats
  62645. for (name in this._floatsArrays) {
  62646. this._effect.setArray(name, this._floatsArrays[name]);
  62647. }
  62648. // Color3
  62649. for (name in this._colors3) {
  62650. this._effect.setColor3(name, this._colors3[name]);
  62651. }
  62652. for (name in this._colors3Arrays) {
  62653. this._effect.setArray3(name, this._colors3Arrays[name]);
  62654. }
  62655. // Color4
  62656. for (name in this._colors4) {
  62657. var color = this._colors4[name];
  62658. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  62659. }
  62660. // Vector2
  62661. for (name in this._vectors2) {
  62662. this._effect.setVector2(name, this._vectors2[name]);
  62663. }
  62664. // Vector3
  62665. for (name in this._vectors3) {
  62666. this._effect.setVector3(name, this._vectors3[name]);
  62667. }
  62668. // Vector4
  62669. for (name in this._vectors4) {
  62670. this._effect.setVector4(name, this._vectors4[name]);
  62671. }
  62672. // Matrix
  62673. for (name in this._matrices) {
  62674. this._effect.setMatrix(name, this._matrices[name]);
  62675. }
  62676. // Matrix 3x3
  62677. for (name in this._matrices3x3) {
  62678. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  62679. }
  62680. // Matrix 2x2
  62681. for (name in this._matrices2x2) {
  62682. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  62683. }
  62684. // Vector2Array
  62685. for (name in this._vectors2Arrays) {
  62686. this._effect.setArray2(name, this._vectors2Arrays[name]);
  62687. }
  62688. // Vector3Array
  62689. for (name in this._vectors3Arrays) {
  62690. this._effect.setArray3(name, this._vectors3Arrays[name]);
  62691. }
  62692. }
  62693. this._afterBind(mesh);
  62694. };
  62695. /**
  62696. * Gets the active textures from the material
  62697. * @returns an array of textures
  62698. */
  62699. ShaderMaterial.prototype.getActiveTextures = function () {
  62700. var activeTextures = _super.prototype.getActiveTextures.call(this);
  62701. for (var name in this._textures) {
  62702. activeTextures.push(this._textures[name]);
  62703. }
  62704. for (var name in this._textureArrays) {
  62705. var array = this._textureArrays[name];
  62706. for (var index = 0; index < array.length; index++) {
  62707. activeTextures.push(array[index]);
  62708. }
  62709. }
  62710. return activeTextures;
  62711. };
  62712. /**
  62713. * Specifies if the material uses a texture
  62714. * @param texture defines the texture to check against the material
  62715. * @returns a boolean specifying if the material uses the texture
  62716. */
  62717. ShaderMaterial.prototype.hasTexture = function (texture) {
  62718. if (_super.prototype.hasTexture.call(this, texture)) {
  62719. return true;
  62720. }
  62721. for (var name in this._textures) {
  62722. if (this._textures[name] === texture) {
  62723. return true;
  62724. }
  62725. }
  62726. for (var name in this._textureArrays) {
  62727. var array = this._textureArrays[name];
  62728. for (var index = 0; index < array.length; index++) {
  62729. if (array[index] === texture) {
  62730. return true;
  62731. }
  62732. }
  62733. }
  62734. return false;
  62735. };
  62736. /**
  62737. * Makes a duplicate of the material, and gives it a new name
  62738. * @param name defines the new name for the duplicated material
  62739. * @returns the cloned material
  62740. */
  62741. ShaderMaterial.prototype.clone = function (name) {
  62742. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  62743. return newShaderMaterial;
  62744. };
  62745. /**
  62746. * Disposes the material
  62747. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  62748. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  62749. */
  62750. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  62751. if (forceDisposeTextures) {
  62752. var name;
  62753. for (name in this._textures) {
  62754. this._textures[name].dispose();
  62755. }
  62756. for (name in this._textureArrays) {
  62757. var array = this._textureArrays[name];
  62758. for (var index = 0; index < array.length; index++) {
  62759. array[index].dispose();
  62760. }
  62761. }
  62762. }
  62763. this._textures = {};
  62764. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  62765. };
  62766. /**
  62767. * Serializes this material in a JSON representation
  62768. * @returns the serialized material object
  62769. */
  62770. ShaderMaterial.prototype.serialize = function () {
  62771. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  62772. serializationObject.customType = "BABYLON.ShaderMaterial";
  62773. serializationObject.options = this._options;
  62774. serializationObject.shaderPath = this._shaderPath;
  62775. var name;
  62776. // Texture
  62777. serializationObject.textures = {};
  62778. for (name in this._textures) {
  62779. serializationObject.textures[name] = this._textures[name].serialize();
  62780. }
  62781. // Texture arrays
  62782. serializationObject.textureArrays = {};
  62783. for (name in this._textureArrays) {
  62784. serializationObject.textureArrays[name] = [];
  62785. var array = this._textureArrays[name];
  62786. for (var index = 0; index < array.length; index++) {
  62787. serializationObject.textureArrays[name].push(array[index].serialize());
  62788. }
  62789. }
  62790. // Float
  62791. serializationObject.floats = {};
  62792. for (name in this._floats) {
  62793. serializationObject.floats[name] = this._floats[name];
  62794. }
  62795. // Float s
  62796. serializationObject.FloatArrays = {};
  62797. for (name in this._floatsArrays) {
  62798. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  62799. }
  62800. // Color3
  62801. serializationObject.colors3 = {};
  62802. for (name in this._colors3) {
  62803. serializationObject.colors3[name] = this._colors3[name].asArray();
  62804. }
  62805. // Color3 array
  62806. serializationObject.colors3Arrays = {};
  62807. for (name in this._colors3Arrays) {
  62808. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  62809. }
  62810. // Color4
  62811. serializationObject.colors4 = {};
  62812. for (name in this._colors4) {
  62813. serializationObject.colors4[name] = this._colors4[name].asArray();
  62814. }
  62815. // Vector2
  62816. serializationObject.vectors2 = {};
  62817. for (name in this._vectors2) {
  62818. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  62819. }
  62820. // Vector3
  62821. serializationObject.vectors3 = {};
  62822. for (name in this._vectors3) {
  62823. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  62824. }
  62825. // Vector4
  62826. serializationObject.vectors4 = {};
  62827. for (name in this._vectors4) {
  62828. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  62829. }
  62830. // Matrix
  62831. serializationObject.matrices = {};
  62832. for (name in this._matrices) {
  62833. serializationObject.matrices[name] = this._matrices[name].asArray();
  62834. }
  62835. // Matrix 3x3
  62836. serializationObject.matrices3x3 = {};
  62837. for (name in this._matrices3x3) {
  62838. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  62839. }
  62840. // Matrix 2x2
  62841. serializationObject.matrices2x2 = {};
  62842. for (name in this._matrices2x2) {
  62843. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  62844. }
  62845. // Vector2Array
  62846. serializationObject.vectors2Arrays = {};
  62847. for (name in this._vectors2Arrays) {
  62848. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  62849. }
  62850. // Vector3Array
  62851. serializationObject.vectors3Arrays = {};
  62852. for (name in this._vectors3Arrays) {
  62853. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  62854. }
  62855. return serializationObject;
  62856. };
  62857. /**
  62858. * Creates a shader material from parsed shader material data
  62859. * @param source defines the JSON represnetation of the material
  62860. * @param scene defines the hosting scene
  62861. * @param rootUrl defines the root URL to use to load textures and relative dependencies
  62862. * @returns a new material
  62863. */
  62864. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  62865. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  62866. var name;
  62867. // Texture
  62868. for (name in source.textures) {
  62869. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  62870. }
  62871. // Texture arrays
  62872. for (name in source.textureArrays) {
  62873. var array = source.textureArrays[name];
  62874. var textureArray = new Array();
  62875. for (var index = 0; index < array.length; index++) {
  62876. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  62877. }
  62878. material.setTextureArray(name, textureArray);
  62879. }
  62880. // Float
  62881. for (name in source.floats) {
  62882. material.setFloat(name, source.floats[name]);
  62883. }
  62884. // Float s
  62885. for (name in source.floatsArrays) {
  62886. material.setFloats(name, source.floatsArrays[name]);
  62887. }
  62888. // Color3
  62889. for (name in source.colors3) {
  62890. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  62891. }
  62892. // Color3 arrays
  62893. for (name in source.colors3Arrays) {
  62894. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  62895. if (i % 3 === 0) {
  62896. arr.push([num]);
  62897. }
  62898. else {
  62899. arr[arr.length - 1].push(num);
  62900. }
  62901. return arr;
  62902. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  62903. material.setColor3Array(name, colors);
  62904. }
  62905. // Color4
  62906. for (name in source.colors4) {
  62907. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  62908. }
  62909. // Vector2
  62910. for (name in source.vectors2) {
  62911. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  62912. }
  62913. // Vector3
  62914. for (name in source.vectors3) {
  62915. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  62916. }
  62917. // Vector4
  62918. for (name in source.vectors4) {
  62919. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  62920. }
  62921. // Matrix
  62922. for (name in source.matrices) {
  62923. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  62924. }
  62925. // Matrix 3x3
  62926. for (name in source.matrices3x3) {
  62927. material.setMatrix3x3(name, source.matrices3x3[name]);
  62928. }
  62929. // Matrix 2x2
  62930. for (name in source.matrices2x2) {
  62931. material.setMatrix2x2(name, source.matrices2x2[name]);
  62932. }
  62933. // Vector2Array
  62934. for (name in source.vectors2Arrays) {
  62935. material.setArray2(name, source.vectors2Arrays[name]);
  62936. }
  62937. // Vector3Array
  62938. for (name in source.vectors3Arrays) {
  62939. material.setArray3(name, source.vectors3Arrays[name]);
  62940. }
  62941. return material;
  62942. };
  62943. return ShaderMaterial;
  62944. }(BABYLON.Material));
  62945. BABYLON.ShaderMaterial = ShaderMaterial;
  62946. })(BABYLON || (BABYLON = {}));
  62947. //# sourceMappingURL=babylon.shaderMaterial.js.map
  62948. var BABYLON;
  62949. (function (BABYLON) {
  62950. /**
  62951. * Mesh representing the gorund
  62952. */
  62953. var GroundMesh = /** @class */ (function (_super) {
  62954. __extends(GroundMesh, _super);
  62955. function GroundMesh(name, scene) {
  62956. var _this = _super.call(this, name, scene) || this;
  62957. /** If octree should be generated */
  62958. _this.generateOctree = false;
  62959. return _this;
  62960. }
  62961. /**
  62962. * "GroundMesh"
  62963. * @returns "GroundMesh"
  62964. */
  62965. GroundMesh.prototype.getClassName = function () {
  62966. return "GroundMesh";
  62967. };
  62968. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  62969. /**
  62970. * The minimum of x and y subdivisions
  62971. */
  62972. get: function () {
  62973. return Math.min(this._subdivisionsX, this._subdivisionsY);
  62974. },
  62975. enumerable: true,
  62976. configurable: true
  62977. });
  62978. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  62979. /**
  62980. * X subdivisions
  62981. */
  62982. get: function () {
  62983. return this._subdivisionsX;
  62984. },
  62985. enumerable: true,
  62986. configurable: true
  62987. });
  62988. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  62989. /**
  62990. * Y subdivisions
  62991. */
  62992. get: function () {
  62993. return this._subdivisionsY;
  62994. },
  62995. enumerable: true,
  62996. configurable: true
  62997. });
  62998. /**
  62999. * This function will update an octree to help to select the right submeshes for rendering, picking and collision computations.
  63000. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  63001. * @param chunksCount the number of subdivisions for x and y
  63002. * @param octreeBlocksSize (Default: 32)
  63003. */
  63004. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  63005. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  63006. this._subdivisionsX = chunksCount;
  63007. this._subdivisionsY = chunksCount;
  63008. this.subdivide(chunksCount);
  63009. // Call the octree system optimization if it is defined.
  63010. var thisAsAny = this;
  63011. if (thisAsAny.createOrUpdateSubmeshesOctree) {
  63012. thisAsAny.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  63013. }
  63014. };
  63015. /**
  63016. * Returns a height (y) value in the Worl system :
  63017. * the ground altitude at the coordinates (x, z) expressed in the World system.
  63018. * @param x x coordinate
  63019. * @param z z coordinate
  63020. * @returns the ground y position if (x, z) are outside the ground surface.
  63021. */
  63022. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  63023. var world = this.getWorldMatrix();
  63024. var invMat = BABYLON.Tmp.Matrix[5];
  63025. world.invertToRef(invMat);
  63026. var tmpVect = BABYLON.Tmp.Vector3[8];
  63027. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  63028. x = tmpVect.x;
  63029. z = tmpVect.z;
  63030. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  63031. return this.position.y;
  63032. }
  63033. if (!this._heightQuads || this._heightQuads.length == 0) {
  63034. this._initHeightQuads();
  63035. this._computeHeightQuads();
  63036. }
  63037. var facet = this._getFacetAt(x, z);
  63038. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  63039. // return y in the World system
  63040. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  63041. return tmpVect.y;
  63042. };
  63043. /**
  63044. * Returns a normalized vector (Vector3) orthogonal to the ground
  63045. * at the ground coordinates (x, z) expressed in the World system.
  63046. * @param x x coordinate
  63047. * @param z z coordinate
  63048. * @returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  63049. */
  63050. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  63051. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  63052. this.getNormalAtCoordinatesToRef(x, z, normal);
  63053. return normal;
  63054. };
  63055. /**
  63056. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  63057. * at the ground coordinates (x, z) expressed in the World system.
  63058. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  63059. * @param x x coordinate
  63060. * @param z z coordinate
  63061. * @param ref vector to store the result
  63062. * @returns the GroundMesh.
  63063. */
  63064. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  63065. var world = this.getWorldMatrix();
  63066. var tmpMat = BABYLON.Tmp.Matrix[5];
  63067. world.invertToRef(tmpMat);
  63068. var tmpVect = BABYLON.Tmp.Vector3[8];
  63069. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  63070. x = tmpVect.x;
  63071. z = tmpVect.z;
  63072. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  63073. return this;
  63074. }
  63075. if (!this._heightQuads || this._heightQuads.length == 0) {
  63076. this._initHeightQuads();
  63077. this._computeHeightQuads();
  63078. }
  63079. var facet = this._getFacetAt(x, z);
  63080. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  63081. return this;
  63082. };
  63083. /**
  63084. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  63085. * if the ground has been updated.
  63086. * This can be used in the render loop.
  63087. * @returns the GroundMesh.
  63088. */
  63089. GroundMesh.prototype.updateCoordinateHeights = function () {
  63090. if (!this._heightQuads || this._heightQuads.length == 0) {
  63091. this._initHeightQuads();
  63092. }
  63093. this._computeHeightQuads();
  63094. return this;
  63095. };
  63096. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  63097. GroundMesh.prototype._getFacetAt = function (x, z) {
  63098. // retrieve col and row from x, z coordinates in the ground local system
  63099. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  63100. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  63101. var quad = this._heightQuads[row * this._subdivisionsX + col];
  63102. var facet;
  63103. if (z < quad.slope.x * x + quad.slope.y) {
  63104. facet = quad.facet1;
  63105. }
  63106. else {
  63107. facet = quad.facet2;
  63108. }
  63109. return facet;
  63110. };
  63111. // Creates and populates the heightMap array with "facet" elements :
  63112. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  63113. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  63114. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  63115. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  63116. // Returns the GroundMesh.
  63117. GroundMesh.prototype._initHeightQuads = function () {
  63118. var subdivisionsX = this._subdivisionsX;
  63119. var subdivisionsY = this._subdivisionsY;
  63120. this._heightQuads = new Array();
  63121. for (var row = 0; row < subdivisionsY; row++) {
  63122. for (var col = 0; col < subdivisionsX; col++) {
  63123. 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) };
  63124. this._heightQuads[row * subdivisionsX + col] = quad;
  63125. }
  63126. }
  63127. return this;
  63128. };
  63129. // Compute each quad element values and update the the heightMap array :
  63130. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  63131. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  63132. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  63133. // Returns the GroundMesh.
  63134. GroundMesh.prototype._computeHeightQuads = function () {
  63135. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  63136. if (!positions) {
  63137. return this;
  63138. }
  63139. var v1 = BABYLON.Tmp.Vector3[3];
  63140. var v2 = BABYLON.Tmp.Vector3[2];
  63141. var v3 = BABYLON.Tmp.Vector3[1];
  63142. var v4 = BABYLON.Tmp.Vector3[0];
  63143. var v1v2 = BABYLON.Tmp.Vector3[4];
  63144. var v1v3 = BABYLON.Tmp.Vector3[5];
  63145. var v1v4 = BABYLON.Tmp.Vector3[6];
  63146. var norm1 = BABYLON.Tmp.Vector3[7];
  63147. var norm2 = BABYLON.Tmp.Vector3[8];
  63148. var i = 0;
  63149. var j = 0;
  63150. var k = 0;
  63151. var cd = 0; // 2D slope coefficient : z = cd * x + h
  63152. var h = 0;
  63153. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  63154. var d2 = 0;
  63155. var subdivisionsX = this._subdivisionsX;
  63156. var subdivisionsY = this._subdivisionsY;
  63157. for (var row = 0; row < subdivisionsY; row++) {
  63158. for (var col = 0; col < subdivisionsX; col++) {
  63159. i = col * 3;
  63160. j = row * (subdivisionsX + 1) * 3;
  63161. k = (row + 1) * (subdivisionsX + 1) * 3;
  63162. v1.x = positions[j + i];
  63163. v1.y = positions[j + i + 1];
  63164. v1.z = positions[j + i + 2];
  63165. v2.x = positions[j + i + 3];
  63166. v2.y = positions[j + i + 4];
  63167. v2.z = positions[j + i + 5];
  63168. v3.x = positions[k + i];
  63169. v3.y = positions[k + i + 1];
  63170. v3.z = positions[k + i + 2];
  63171. v4.x = positions[k + i + 3];
  63172. v4.y = positions[k + i + 4];
  63173. v4.z = positions[k + i + 5];
  63174. // 2D slope V1V4
  63175. cd = (v4.z - v1.z) / (v4.x - v1.x);
  63176. h = v1.z - cd * v1.x; // v1 belongs to the slope
  63177. // facet equations :
  63178. // we compute each facet normal vector
  63179. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  63180. // we compute the value d by applying the equation to v1 which belongs to the plane
  63181. // then we store the facet equation in a Vector4
  63182. v2.subtractToRef(v1, v1v2);
  63183. v3.subtractToRef(v1, v1v3);
  63184. v4.subtractToRef(v1, v1v4);
  63185. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  63186. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  63187. norm1.normalize();
  63188. norm2.normalize();
  63189. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  63190. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  63191. var quad = this._heightQuads[row * subdivisionsX + col];
  63192. quad.slope.copyFromFloats(cd, h);
  63193. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  63194. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  63195. }
  63196. }
  63197. return this;
  63198. };
  63199. /**
  63200. * Serializes this ground mesh
  63201. * @param serializationObject object to write serialization to
  63202. */
  63203. GroundMesh.prototype.serialize = function (serializationObject) {
  63204. _super.prototype.serialize.call(this, serializationObject);
  63205. serializationObject.subdivisionsX = this._subdivisionsX;
  63206. serializationObject.subdivisionsY = this._subdivisionsY;
  63207. serializationObject.minX = this._minX;
  63208. serializationObject.maxX = this._maxX;
  63209. serializationObject.minZ = this._minZ;
  63210. serializationObject.maxZ = this._maxZ;
  63211. serializationObject.width = this._width;
  63212. serializationObject.height = this._height;
  63213. };
  63214. /**
  63215. * Parses a serialized ground mesh
  63216. * @param parsedMesh the serialized mesh
  63217. * @param scene the scene to create the ground mesh in
  63218. * @returns the created ground mesh
  63219. */
  63220. GroundMesh.Parse = function (parsedMesh, scene) {
  63221. var result = new GroundMesh(parsedMesh.name, scene);
  63222. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  63223. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  63224. result._minX = parsedMesh.minX;
  63225. result._maxX = parsedMesh.maxX;
  63226. result._minZ = parsedMesh.minZ;
  63227. result._maxZ = parsedMesh.maxZ;
  63228. result._width = parsedMesh.width;
  63229. result._height = parsedMesh.height;
  63230. return result;
  63231. };
  63232. return GroundMesh;
  63233. }(BABYLON.Mesh));
  63234. BABYLON.GroundMesh = GroundMesh;
  63235. })(BABYLON || (BABYLON = {}));
  63236. //# sourceMappingURL=babylon.groundMesh.js.map
  63237. var BABYLON;
  63238. (function (BABYLON) {
  63239. /**
  63240. * Creates an instance based on a source mesh.
  63241. */
  63242. var InstancedMesh = /** @class */ (function (_super) {
  63243. __extends(InstancedMesh, _super);
  63244. function InstancedMesh(name, source) {
  63245. var _this = _super.call(this, name, source.getScene()) || this;
  63246. source.instances.push(_this);
  63247. _this._sourceMesh = source;
  63248. _this.position.copyFrom(source.position);
  63249. _this.rotation.copyFrom(source.rotation);
  63250. _this.scaling.copyFrom(source.scaling);
  63251. if (source.rotationQuaternion) {
  63252. _this.rotationQuaternion = source.rotationQuaternion.clone();
  63253. }
  63254. _this.infiniteDistance = source.infiniteDistance;
  63255. _this.setPivotMatrix(source.getPivotMatrix());
  63256. _this.refreshBoundingInfo();
  63257. _this._syncSubMeshes();
  63258. return _this;
  63259. }
  63260. /**
  63261. * Returns the string "InstancedMesh".
  63262. */
  63263. InstancedMesh.prototype.getClassName = function () {
  63264. return "InstancedMesh";
  63265. };
  63266. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  63267. // Methods
  63268. /**
  63269. * If the source mesh receives shadows
  63270. */
  63271. get: function () {
  63272. return this._sourceMesh.receiveShadows;
  63273. },
  63274. enumerable: true,
  63275. configurable: true
  63276. });
  63277. Object.defineProperty(InstancedMesh.prototype, "material", {
  63278. /**
  63279. * The material of the source mesh
  63280. */
  63281. get: function () {
  63282. return this._sourceMesh.material;
  63283. },
  63284. enumerable: true,
  63285. configurable: true
  63286. });
  63287. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  63288. /**
  63289. * Visibility of the source mesh
  63290. */
  63291. get: function () {
  63292. return this._sourceMesh.visibility;
  63293. },
  63294. enumerable: true,
  63295. configurable: true
  63296. });
  63297. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  63298. /**
  63299. * Skeleton of the source mesh
  63300. */
  63301. get: function () {
  63302. return this._sourceMesh.skeleton;
  63303. },
  63304. enumerable: true,
  63305. configurable: true
  63306. });
  63307. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  63308. /**
  63309. * Rendering ground id of the source mesh
  63310. */
  63311. get: function () {
  63312. return this._sourceMesh.renderingGroupId;
  63313. },
  63314. set: function (value) {
  63315. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  63316. return;
  63317. }
  63318. //no-op with warning
  63319. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  63320. },
  63321. enumerable: true,
  63322. configurable: true
  63323. });
  63324. /**
  63325. * Returns the total number of vertices (integer).
  63326. */
  63327. InstancedMesh.prototype.getTotalVertices = function () {
  63328. return this._sourceMesh.getTotalVertices();
  63329. };
  63330. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  63331. /**
  63332. * The source mesh of the instance
  63333. */
  63334. get: function () {
  63335. return this._sourceMesh;
  63336. },
  63337. enumerable: true,
  63338. configurable: true
  63339. });
  63340. /**
  63341. * Is this node ready to be used/rendered
  63342. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  63343. * @return {boolean} is it ready
  63344. */
  63345. InstancedMesh.prototype.isReady = function (completeCheck) {
  63346. if (completeCheck === void 0) { completeCheck = false; }
  63347. return this._sourceMesh.isReady(completeCheck, true);
  63348. };
  63349. /**
  63350. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  63351. * @param kind kind of verticies to retreive (eg. positons, normals, uvs, etc.)
  63352. * @param copyWhenShared If true (default false) and and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.
  63353. * @returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  63354. */
  63355. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  63356. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  63357. };
  63358. /**
  63359. * Sets the vertex data of the mesh geometry for the requested `kind`.
  63360. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  63361. * The `data` are either a numeric array either a Float32Array.
  63362. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  63363. * 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).
  63364. * Note that a new underlying VertexBuffer object is created each call.
  63365. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  63366. *
  63367. * Possible `kind` values :
  63368. * - BABYLON.VertexBuffer.PositionKind
  63369. * - BABYLON.VertexBuffer.UVKind
  63370. * - BABYLON.VertexBuffer.UV2Kind
  63371. * - BABYLON.VertexBuffer.UV3Kind
  63372. * - BABYLON.VertexBuffer.UV4Kind
  63373. * - BABYLON.VertexBuffer.UV5Kind
  63374. * - BABYLON.VertexBuffer.UV6Kind
  63375. * - BABYLON.VertexBuffer.ColorKind
  63376. * - BABYLON.VertexBuffer.MatricesIndicesKind
  63377. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  63378. * - BABYLON.VertexBuffer.MatricesWeightsKind
  63379. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  63380. *
  63381. * Returns the Mesh.
  63382. */
  63383. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  63384. if (this.sourceMesh) {
  63385. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  63386. }
  63387. return this.sourceMesh;
  63388. };
  63389. /**
  63390. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  63391. * If the mesh has no geometry, it is simply returned as it is.
  63392. * The `data` are either a numeric array either a Float32Array.
  63393. * No new underlying VertexBuffer object is created.
  63394. * 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.
  63395. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  63396. *
  63397. * Possible `kind` values :
  63398. * - BABYLON.VertexBuffer.PositionKind
  63399. * - BABYLON.VertexBuffer.UVKind
  63400. * - BABYLON.VertexBuffer.UV2Kind
  63401. * - BABYLON.VertexBuffer.UV3Kind
  63402. * - BABYLON.VertexBuffer.UV4Kind
  63403. * - BABYLON.VertexBuffer.UV5Kind
  63404. * - BABYLON.VertexBuffer.UV6Kind
  63405. * - BABYLON.VertexBuffer.ColorKind
  63406. * - BABYLON.VertexBuffer.MatricesIndicesKind
  63407. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  63408. * - BABYLON.VertexBuffer.MatricesWeightsKind
  63409. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  63410. *
  63411. * Returns the Mesh.
  63412. */
  63413. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  63414. if (this.sourceMesh) {
  63415. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  63416. }
  63417. return this.sourceMesh;
  63418. };
  63419. /**
  63420. * Sets the mesh indices.
  63421. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  63422. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  63423. * This method creates a new index buffer each call.
  63424. * Returns the Mesh.
  63425. */
  63426. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  63427. if (totalVertices === void 0) { totalVertices = null; }
  63428. if (this.sourceMesh) {
  63429. this.sourceMesh.setIndices(indices, totalVertices);
  63430. }
  63431. return this.sourceMesh;
  63432. };
  63433. /**
  63434. * Boolean : True if the mesh owns the requested kind of data.
  63435. */
  63436. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  63437. return this._sourceMesh.isVerticesDataPresent(kind);
  63438. };
  63439. /**
  63440. * Returns an array of indices (IndicesArray).
  63441. */
  63442. InstancedMesh.prototype.getIndices = function () {
  63443. return this._sourceMesh.getIndices();
  63444. };
  63445. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  63446. get: function () {
  63447. return this._sourceMesh._positions;
  63448. },
  63449. enumerable: true,
  63450. configurable: true
  63451. });
  63452. /**
  63453. * Sets a new updated BoundingInfo to the mesh.
  63454. * @returns the mesh.
  63455. */
  63456. InstancedMesh.prototype.refreshBoundingInfo = function () {
  63457. var meshBB = this._sourceMesh.getBoundingInfo();
  63458. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  63459. this._updateBoundingInfo();
  63460. return this;
  63461. };
  63462. /** @hidden */
  63463. InstancedMesh.prototype._preActivate = function () {
  63464. if (this._currentLOD) {
  63465. this._currentLOD._preActivate();
  63466. }
  63467. return this;
  63468. };
  63469. /** @hidden */
  63470. InstancedMesh.prototype._activate = function (renderId) {
  63471. if (this._currentLOD) {
  63472. this._currentLOD._registerInstanceForRenderId(this, renderId);
  63473. }
  63474. return this;
  63475. };
  63476. /**
  63477. * Returns the current associated LOD AbstractMesh.
  63478. */
  63479. InstancedMesh.prototype.getLOD = function (camera) {
  63480. if (!camera) {
  63481. return this;
  63482. }
  63483. var boundingInfo = this.getBoundingInfo();
  63484. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  63485. if (this._currentLOD === this.sourceMesh) {
  63486. return this;
  63487. }
  63488. return this._currentLOD;
  63489. };
  63490. /** @hidden */
  63491. InstancedMesh.prototype._syncSubMeshes = function () {
  63492. this.releaseSubMeshes();
  63493. if (this._sourceMesh.subMeshes) {
  63494. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  63495. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  63496. }
  63497. }
  63498. return this;
  63499. };
  63500. /** @hidden */
  63501. InstancedMesh.prototype._generatePointsArray = function () {
  63502. return this._sourceMesh._generatePointsArray();
  63503. };
  63504. /**
  63505. * Creates a new InstancedMesh from the current mesh.
  63506. * - name (string) : the cloned mesh name
  63507. * - newParent (optional Node) : the optional Node to parent the clone to.
  63508. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  63509. *
  63510. * Returns the clone.
  63511. */
  63512. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  63513. var result = this._sourceMesh.createInstance(name);
  63514. // Deep copy
  63515. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  63516. // Bounding info
  63517. this.refreshBoundingInfo();
  63518. // Parent
  63519. if (newParent) {
  63520. result.parent = newParent;
  63521. }
  63522. if (!doNotCloneChildren) {
  63523. // Children
  63524. for (var index = 0; index < this.getScene().meshes.length; index++) {
  63525. var mesh = this.getScene().meshes[index];
  63526. if (mesh.parent === this) {
  63527. mesh.clone(mesh.name, result);
  63528. }
  63529. }
  63530. }
  63531. result.computeWorldMatrix(true);
  63532. return result;
  63533. };
  63534. /**
  63535. * Disposes the InstancedMesh.
  63536. * Returns nothing.
  63537. */
  63538. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  63539. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  63540. // Remove from mesh
  63541. var index = this._sourceMesh.instances.indexOf(this);
  63542. this._sourceMesh.instances.splice(index, 1);
  63543. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  63544. };
  63545. return InstancedMesh;
  63546. }(BABYLON.AbstractMesh));
  63547. BABYLON.InstancedMesh = InstancedMesh;
  63548. })(BABYLON || (BABYLON = {}));
  63549. //# sourceMappingURL=babylon.instancedMesh.js.map
  63550. var BABYLON;
  63551. (function (BABYLON) {
  63552. /**
  63553. * Line mesh
  63554. * @see https://doc.babylonjs.com/babylon101/parametric_shapes
  63555. */
  63556. var LinesMesh = /** @class */ (function (_super) {
  63557. __extends(LinesMesh, _super);
  63558. function LinesMesh(name, scene, parent, source, doNotCloneChildren,
  63559. /**
  63560. * If vertex color should be applied to the mesh
  63561. */
  63562. useVertexColor,
  63563. /**
  63564. * If vertex alpha should be applied to the mesh
  63565. */
  63566. useVertexAlpha) {
  63567. if (scene === void 0) { scene = null; }
  63568. if (parent === void 0) { parent = null; }
  63569. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  63570. _this.useVertexColor = useVertexColor;
  63571. _this.useVertexAlpha = useVertexAlpha;
  63572. /**
  63573. * Color of the line (Default: White)
  63574. */
  63575. _this.color = new BABYLON.Color3(1, 1, 1);
  63576. /**
  63577. * Alpha of the line (Default: 1)
  63578. */
  63579. _this.alpha = 1;
  63580. if (source) {
  63581. _this.color = source.color.clone();
  63582. _this.alpha = source.alpha;
  63583. _this.useVertexColor = source.useVertexColor;
  63584. _this.useVertexAlpha = source.useVertexAlpha;
  63585. }
  63586. _this._intersectionThreshold = 0.1;
  63587. var defines = [];
  63588. var options = {
  63589. attributes: [BABYLON.VertexBuffer.PositionKind, "world0", "world1", "world2", "world3"],
  63590. uniforms: ["world", "viewProjection"],
  63591. needAlphaBlending: true,
  63592. defines: defines
  63593. };
  63594. if (useVertexAlpha === false) {
  63595. options.needAlphaBlending = false;
  63596. }
  63597. if (!useVertexColor) {
  63598. options.uniforms.push("color");
  63599. }
  63600. else {
  63601. options.defines.push("#define VERTEXCOLOR");
  63602. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  63603. }
  63604. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  63605. return _this;
  63606. }
  63607. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  63608. /**
  63609. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  63610. * This margin is expressed in world space coordinates, so its value may vary.
  63611. * Default value is 0.1
  63612. * @returns the intersection Threshold value.
  63613. */
  63614. get: function () {
  63615. return this._intersectionThreshold;
  63616. },
  63617. /**
  63618. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  63619. * This margin is expressed in world space coordinates, so its value may vary.
  63620. */
  63621. set: function (value) {
  63622. if (this._intersectionThreshold === value) {
  63623. return;
  63624. }
  63625. this._intersectionThreshold = value;
  63626. if (this.geometry) {
  63627. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  63628. }
  63629. },
  63630. enumerable: true,
  63631. configurable: true
  63632. });
  63633. /**
  63634. * Returns the string "LineMesh"
  63635. */
  63636. LinesMesh.prototype.getClassName = function () {
  63637. return "LinesMesh";
  63638. };
  63639. Object.defineProperty(LinesMesh.prototype, "material", {
  63640. /**
  63641. * @hidden
  63642. */
  63643. get: function () {
  63644. return this._colorShader;
  63645. },
  63646. /**
  63647. * @hidden
  63648. */
  63649. set: function (value) {
  63650. // Do nothing
  63651. },
  63652. enumerable: true,
  63653. configurable: true
  63654. });
  63655. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  63656. /**
  63657. * @hidden
  63658. */
  63659. get: function () {
  63660. return false;
  63661. },
  63662. enumerable: true,
  63663. configurable: true
  63664. });
  63665. /** @hidden */
  63666. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  63667. if (!this._geometry) {
  63668. return this;
  63669. }
  63670. // VBOs
  63671. this._geometry._bind(this._colorShader.getEffect());
  63672. // Color
  63673. if (!this.useVertexColor) {
  63674. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  63675. }
  63676. return this;
  63677. };
  63678. /** @hidden */
  63679. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  63680. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  63681. return this;
  63682. }
  63683. var engine = this.getScene().getEngine();
  63684. // Draw order
  63685. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  63686. return this;
  63687. };
  63688. /**
  63689. * Disposes of the line mesh
  63690. * @param doNotRecurse If children should be disposed
  63691. */
  63692. LinesMesh.prototype.dispose = function (doNotRecurse) {
  63693. this._colorShader.dispose();
  63694. _super.prototype.dispose.call(this, doNotRecurse);
  63695. };
  63696. /**
  63697. * Returns a new LineMesh object cloned from the current one.
  63698. */
  63699. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  63700. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  63701. };
  63702. return LinesMesh;
  63703. }(BABYLON.Mesh));
  63704. BABYLON.LinesMesh = LinesMesh;
  63705. })(BABYLON || (BABYLON = {}));
  63706. //# sourceMappingURL=babylon.linesMesh.js.map
  63707. var BABYLON;
  63708. (function (BABYLON) {
  63709. /**
  63710. * This class implement a typical dictionary using a string as key and the generic type T as value.
  63711. * The underlying implementation relies on an associative array to ensure the best performances.
  63712. * The value can be anything including 'null' but except 'undefined'
  63713. */
  63714. var StringDictionary = /** @class */ (function () {
  63715. function StringDictionary() {
  63716. this._count = 0;
  63717. this._data = {};
  63718. }
  63719. /**
  63720. * This will clear this dictionary and copy the content from the 'source' one.
  63721. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  63722. * @param source the dictionary to take the content from and copy to this dictionary
  63723. */
  63724. StringDictionary.prototype.copyFrom = function (source) {
  63725. var _this = this;
  63726. this.clear();
  63727. source.forEach(function (t, v) { return _this.add(t, v); });
  63728. };
  63729. /**
  63730. * Get a value based from its key
  63731. * @param key the given key to get the matching value from
  63732. * @return the value if found, otherwise undefined is returned
  63733. */
  63734. StringDictionary.prototype.get = function (key) {
  63735. var val = this._data[key];
  63736. if (val !== undefined) {
  63737. return val;
  63738. }
  63739. return undefined;
  63740. };
  63741. /**
  63742. * Get a value from its key or add it if it doesn't exist.
  63743. * This method will ensure you that a given key/data will be present in the dictionary.
  63744. * @param key the given key to get the matching value from
  63745. * @param factory the factory that will create the value if the key is not present in the dictionary.
  63746. * The factory will only be invoked if there's no data for the given key.
  63747. * @return the value corresponding to the key.
  63748. */
  63749. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  63750. var val = this.get(key);
  63751. if (val !== undefined) {
  63752. return val;
  63753. }
  63754. val = factory(key);
  63755. if (val) {
  63756. this.add(key, val);
  63757. }
  63758. return val;
  63759. };
  63760. /**
  63761. * Get a value from its key if present in the dictionary otherwise add it
  63762. * @param key the key to get the value from
  63763. * @param val if there's no such key/value pair in the dictionary add it with this value
  63764. * @return the value corresponding to the key
  63765. */
  63766. StringDictionary.prototype.getOrAdd = function (key, val) {
  63767. var curVal = this.get(key);
  63768. if (curVal !== undefined) {
  63769. return curVal;
  63770. }
  63771. this.add(key, val);
  63772. return val;
  63773. };
  63774. /**
  63775. * Check if there's a given key in the dictionary
  63776. * @param key the key to check for
  63777. * @return true if the key is present, false otherwise
  63778. */
  63779. StringDictionary.prototype.contains = function (key) {
  63780. return this._data[key] !== undefined;
  63781. };
  63782. /**
  63783. * Add a new key and its corresponding value
  63784. * @param key the key to add
  63785. * @param value the value corresponding to the key
  63786. * @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
  63787. */
  63788. StringDictionary.prototype.add = function (key, value) {
  63789. if (this._data[key] !== undefined) {
  63790. return false;
  63791. }
  63792. this._data[key] = value;
  63793. ++this._count;
  63794. return true;
  63795. };
  63796. /**
  63797. * Update a specific value associated to a key
  63798. * @param key defines the key to use
  63799. * @param value defines the value to store
  63800. * @returns true if the value was updated (or false if the key was not found)
  63801. */
  63802. StringDictionary.prototype.set = function (key, value) {
  63803. if (this._data[key] === undefined) {
  63804. return false;
  63805. }
  63806. this._data[key] = value;
  63807. return true;
  63808. };
  63809. /**
  63810. * Get the element of the given key and remove it from the dictionary
  63811. * @param key defines the key to search
  63812. * @returns the value associated with the key or null if not found
  63813. */
  63814. StringDictionary.prototype.getAndRemove = function (key) {
  63815. var val = this.get(key);
  63816. if (val !== undefined) {
  63817. delete this._data[key];
  63818. --this._count;
  63819. return val;
  63820. }
  63821. return null;
  63822. };
  63823. /**
  63824. * Remove a key/value from the dictionary.
  63825. * @param key the key to remove
  63826. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  63827. */
  63828. StringDictionary.prototype.remove = function (key) {
  63829. if (this.contains(key)) {
  63830. delete this._data[key];
  63831. --this._count;
  63832. return true;
  63833. }
  63834. return false;
  63835. };
  63836. /**
  63837. * Clear the whole content of the dictionary
  63838. */
  63839. StringDictionary.prototype.clear = function () {
  63840. this._data = {};
  63841. this._count = 0;
  63842. };
  63843. Object.defineProperty(StringDictionary.prototype, "count", {
  63844. /**
  63845. * Gets the current count
  63846. */
  63847. get: function () {
  63848. return this._count;
  63849. },
  63850. enumerable: true,
  63851. configurable: true
  63852. });
  63853. /**
  63854. * Execute a callback on each key/val of the dictionary.
  63855. * Note that you can remove any element in this dictionary in the callback implementation
  63856. * @param callback the callback to execute on a given key/value pair
  63857. */
  63858. StringDictionary.prototype.forEach = function (callback) {
  63859. for (var cur in this._data) {
  63860. var val = this._data[cur];
  63861. callback(cur, val);
  63862. }
  63863. };
  63864. /**
  63865. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  63866. * If the callback returns null or undefined the method will iterate to the next key/value pair
  63867. * Note that you can remove any element in this dictionary in the callback implementation
  63868. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  63869. * @returns the first item
  63870. */
  63871. StringDictionary.prototype.first = function (callback) {
  63872. for (var cur in this._data) {
  63873. var val = this._data[cur];
  63874. var res = callback(cur, val);
  63875. if (res) {
  63876. return res;
  63877. }
  63878. }
  63879. return null;
  63880. };
  63881. return StringDictionary;
  63882. }());
  63883. BABYLON.StringDictionary = StringDictionary;
  63884. })(BABYLON || (BABYLON = {}));
  63885. //# sourceMappingURL=babylon.stringDictionary.js.map
  63886. var BABYLON;
  63887. (function (BABYLON) {
  63888. var Debug;
  63889. (function (Debug) {
  63890. /**
  63891. * Class used to render a debug view of a given skeleton
  63892. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  63893. */
  63894. var SkeletonViewer = /** @class */ (function () {
  63895. /**
  63896. * Creates a new SkeletonViewer
  63897. * @param skeleton defines the skeleton to render
  63898. * @param mesh defines the mesh attached to the skeleton
  63899. * @param scene defines the hosting scene
  63900. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  63901. * @param renderingGroupId defines the rendering group id to use with the viewer
  63902. */
  63903. function SkeletonViewer(
  63904. /** defines the skeleton to render */
  63905. skeleton,
  63906. /** defines the mesh attached to the skeleton */
  63907. mesh, scene,
  63908. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  63909. autoUpdateBonesMatrices,
  63910. /** defines the rendering group id to use with the viewer */
  63911. renderingGroupId) {
  63912. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  63913. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  63914. this.skeleton = skeleton;
  63915. this.mesh = mesh;
  63916. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  63917. this.renderingGroupId = renderingGroupId;
  63918. /** Gets or sets the color used to render the skeleton */
  63919. this.color = BABYLON.Color3.White();
  63920. this._debugLines = new Array();
  63921. this._isEnabled = false;
  63922. this._scene = scene;
  63923. this.update();
  63924. this._renderFunction = this.update.bind(this);
  63925. }
  63926. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  63927. get: function () {
  63928. return this._isEnabled;
  63929. },
  63930. /** Gets or sets a boolean indicating if the viewer is enabled */
  63931. set: function (value) {
  63932. if (this._isEnabled === value) {
  63933. return;
  63934. }
  63935. this._isEnabled = value;
  63936. if (value) {
  63937. this._scene.registerBeforeRender(this._renderFunction);
  63938. }
  63939. else {
  63940. this._scene.unregisterBeforeRender(this._renderFunction);
  63941. }
  63942. },
  63943. enumerable: true,
  63944. configurable: true
  63945. });
  63946. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  63947. if (x === void 0) { x = 0; }
  63948. if (y === void 0) { y = 0; }
  63949. if (z === void 0) { z = 0; }
  63950. var tmat = BABYLON.Tmp.Matrix[0];
  63951. var parentBone = bone.getParent();
  63952. tmat.copyFrom(bone.getLocalMatrix());
  63953. if (x !== 0 || y !== 0 || z !== 0) {
  63954. var tmat2 = BABYLON.Tmp.Matrix[1];
  63955. BABYLON.Matrix.IdentityToRef(tmat2);
  63956. tmat2.m[12] = x;
  63957. tmat2.m[13] = y;
  63958. tmat2.m[14] = z;
  63959. tmat2.multiplyToRef(tmat, tmat);
  63960. }
  63961. if (parentBone) {
  63962. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  63963. }
  63964. tmat.multiplyToRef(meshMat, tmat);
  63965. position.x = tmat.m[12];
  63966. position.y = tmat.m[13];
  63967. position.z = tmat.m[14];
  63968. };
  63969. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  63970. var len = bones.length;
  63971. var meshPos = this.mesh.position;
  63972. for (var i = 0; i < len; i++) {
  63973. var bone = bones[i];
  63974. var points = this._debugLines[i];
  63975. if (!points) {
  63976. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  63977. this._debugLines[i] = points;
  63978. }
  63979. this._getBonePosition(points[0], bone, meshMat);
  63980. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  63981. points[0].subtractInPlace(meshPos);
  63982. points[1].subtractInPlace(meshPos);
  63983. }
  63984. };
  63985. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  63986. var len = bones.length;
  63987. var boneNum = 0;
  63988. var meshPos = this.mesh.position;
  63989. for (var i = len - 1; i >= 0; i--) {
  63990. var childBone = bones[i];
  63991. var parentBone = childBone.getParent();
  63992. if (!parentBone) {
  63993. continue;
  63994. }
  63995. var points = this._debugLines[boneNum];
  63996. if (!points) {
  63997. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  63998. this._debugLines[boneNum] = points;
  63999. }
  64000. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  64001. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  64002. points[0].subtractInPlace(meshPos);
  64003. points[1].subtractInPlace(meshPos);
  64004. boneNum++;
  64005. }
  64006. };
  64007. /** Update the viewer to sync with current skeleton state */
  64008. SkeletonViewer.prototype.update = function () {
  64009. if (this.autoUpdateBonesMatrices) {
  64010. this.skeleton.computeAbsoluteTransforms();
  64011. }
  64012. if (this.skeleton.bones[0].length === undefined) {
  64013. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  64014. }
  64015. else {
  64016. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  64017. }
  64018. if (!this._debugMesh) {
  64019. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  64020. this._debugMesh.renderingGroupId = this.renderingGroupId;
  64021. }
  64022. else {
  64023. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  64024. }
  64025. this._debugMesh.position.copyFrom(this.mesh.position);
  64026. this._debugMesh.color = this.color;
  64027. };
  64028. /** Release associated resources */
  64029. SkeletonViewer.prototype.dispose = function () {
  64030. if (this._debugMesh) {
  64031. this.isEnabled = false;
  64032. this._debugMesh.dispose();
  64033. this._debugMesh = null;
  64034. }
  64035. };
  64036. return SkeletonViewer;
  64037. }());
  64038. Debug.SkeletonViewer = SkeletonViewer;
  64039. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  64040. })(BABYLON || (BABYLON = {}));
  64041. //# sourceMappingURL=babylon.skeletonViewer.js.map
  64042. /**
  64043. * Module Debug contains the (visual) components to debug a scene correctly
  64044. */
  64045. var BABYLON;
  64046. (function (BABYLON) {
  64047. var Debug;
  64048. (function (Debug) {
  64049. /**
  64050. * The Axes viewer will show 3 axes in a specific point in space
  64051. */
  64052. var AxesViewer = /** @class */ (function () {
  64053. /**
  64054. * Creates a new AxesViewer
  64055. * @param scene defines the hosting scene
  64056. * @param scaleLines defines a number used to scale line length (1 by default)
  64057. */
  64058. function AxesViewer(scene, scaleLines) {
  64059. if (scaleLines === void 0) { scaleLines = 1; }
  64060. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  64061. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  64062. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  64063. /**
  64064. * Gets or sets a number used to scale line length
  64065. */
  64066. this.scaleLines = 1;
  64067. this.scaleLines = scaleLines;
  64068. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  64069. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  64070. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  64071. this._xmesh.renderingGroupId = 2;
  64072. this._ymesh.renderingGroupId = 2;
  64073. this._zmesh.renderingGroupId = 2;
  64074. this._xmesh.material.checkReadyOnlyOnce = true;
  64075. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  64076. this._ymesh.material.checkReadyOnlyOnce = true;
  64077. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  64078. this._zmesh.material.checkReadyOnlyOnce = true;
  64079. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  64080. this.scene = scene;
  64081. }
  64082. /**
  64083. * Force the viewer to update
  64084. * @param position defines the position of the viewer
  64085. * @param xaxis defines the x axis of the viewer
  64086. * @param yaxis defines the y axis of the viewer
  64087. * @param zaxis defines the z axis of the viewer
  64088. */
  64089. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  64090. var scaleLines = this.scaleLines;
  64091. if (this._xmesh) {
  64092. this._xmesh.position.copyFrom(position);
  64093. }
  64094. if (this._ymesh) {
  64095. this._ymesh.position.copyFrom(position);
  64096. }
  64097. if (this._zmesh) {
  64098. this._zmesh.position.copyFrom(position);
  64099. }
  64100. var point2 = this._xline[1];
  64101. point2.x = xaxis.x * scaleLines;
  64102. point2.y = xaxis.y * scaleLines;
  64103. point2.z = xaxis.z * scaleLines;
  64104. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  64105. point2 = this._yline[1];
  64106. point2.x = yaxis.x * scaleLines;
  64107. point2.y = yaxis.y * scaleLines;
  64108. point2.z = yaxis.z * scaleLines;
  64109. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  64110. point2 = this._zline[1];
  64111. point2.x = zaxis.x * scaleLines;
  64112. point2.y = zaxis.y * scaleLines;
  64113. point2.z = zaxis.z * scaleLines;
  64114. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  64115. };
  64116. /** Releases resources */
  64117. AxesViewer.prototype.dispose = function () {
  64118. if (this._xmesh) {
  64119. this._xmesh.dispose();
  64120. }
  64121. if (this._ymesh) {
  64122. this._ymesh.dispose();
  64123. }
  64124. if (this._zmesh) {
  64125. this._zmesh.dispose();
  64126. }
  64127. this._xmesh = null;
  64128. this._ymesh = null;
  64129. this._zmesh = null;
  64130. this.scene = null;
  64131. };
  64132. return AxesViewer;
  64133. }());
  64134. Debug.AxesViewer = AxesViewer;
  64135. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  64136. })(BABYLON || (BABYLON = {}));
  64137. //# sourceMappingURL=babylon.axesViewer.js.map
  64138. var BABYLON;
  64139. (function (BABYLON) {
  64140. var Debug;
  64141. (function (Debug) {
  64142. /**
  64143. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  64144. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  64145. */
  64146. var BoneAxesViewer = /** @class */ (function (_super) {
  64147. __extends(BoneAxesViewer, _super);
  64148. /**
  64149. * Creates a new BoneAxesViewer
  64150. * @param scene defines the hosting scene
  64151. * @param bone defines the target bone
  64152. * @param mesh defines the target mesh
  64153. * @param scaleLines defines a scaling factor for line length (1 by default)
  64154. */
  64155. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  64156. if (scaleLines === void 0) { scaleLines = 1; }
  64157. var _this = _super.call(this, scene, scaleLines) || this;
  64158. /** Gets current position */
  64159. _this.pos = BABYLON.Vector3.Zero();
  64160. /** Gets direction of X axis */
  64161. _this.xaxis = BABYLON.Vector3.Zero();
  64162. /** Gets direction of Y axis */
  64163. _this.yaxis = BABYLON.Vector3.Zero();
  64164. /** Gets direction of Z axis */
  64165. _this.zaxis = BABYLON.Vector3.Zero();
  64166. _this.mesh = mesh;
  64167. _this.bone = bone;
  64168. return _this;
  64169. }
  64170. /**
  64171. * Force the viewer to update
  64172. */
  64173. BoneAxesViewer.prototype.update = function () {
  64174. if (!this.mesh || !this.bone) {
  64175. return;
  64176. }
  64177. var bone = this.bone;
  64178. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  64179. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  64180. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  64181. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  64182. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  64183. };
  64184. /** Releases resources */
  64185. BoneAxesViewer.prototype.dispose = function () {
  64186. if (this.mesh) {
  64187. this.mesh = null;
  64188. this.bone = null;
  64189. _super.prototype.dispose.call(this);
  64190. }
  64191. };
  64192. return BoneAxesViewer;
  64193. }(Debug.AxesViewer));
  64194. Debug.BoneAxesViewer = BoneAxesViewer;
  64195. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  64196. })(BABYLON || (BABYLON = {}));
  64197. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  64198. var BABYLON;
  64199. (function (BABYLON) {
  64200. /**
  64201. * As raycast might be hard to debug, the RayHelper can help rendering the different rays
  64202. * in order to better appreciate the issue one might have.
  64203. * @see http://doc.babylonjs.com/babylon101/raycasts#debugging
  64204. */
  64205. var RayHelper = /** @class */ (function () {
  64206. /**
  64207. * Instantiate a new ray helper.
  64208. * As raycast might be hard to debug, the RayHelper can help rendering the different rays
  64209. * in order to better appreciate the issue one might have.
  64210. * @see http://doc.babylonjs.com/babylon101/raycasts#debugging
  64211. * @param ray Defines the ray we are currently tryin to visualize
  64212. */
  64213. function RayHelper(ray) {
  64214. this.ray = ray;
  64215. }
  64216. /**
  64217. * Helper function to create a colored helper in a scene in one line.
  64218. * @param ray Defines the ray we are currently tryin to visualize
  64219. * @param scene Defines the scene the ray is used in
  64220. * @param color Defines the color we want to see the ray in
  64221. * @returns The newly created ray helper.
  64222. */
  64223. RayHelper.CreateAndShow = function (ray, scene, color) {
  64224. var helper = new RayHelper(ray);
  64225. helper.show(scene, color);
  64226. return helper;
  64227. };
  64228. /**
  64229. * Shows the ray we are willing to debug.
  64230. * @param scene Defines the scene the ray needs to be rendered in
  64231. * @param color Defines the color the ray needs to be rendered in
  64232. */
  64233. RayHelper.prototype.show = function (scene, color) {
  64234. if (!this._renderFunction && this.ray) {
  64235. var ray = this.ray;
  64236. this._renderFunction = this._render.bind(this);
  64237. this._scene = scene;
  64238. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  64239. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  64240. if (this._renderFunction) {
  64241. this._scene.registerBeforeRender(this._renderFunction);
  64242. }
  64243. }
  64244. if (color && this._renderLine) {
  64245. this._renderLine.color.copyFrom(color);
  64246. }
  64247. };
  64248. /**
  64249. * Hides the ray we are debugging.
  64250. */
  64251. RayHelper.prototype.hide = function () {
  64252. if (this._renderFunction && this._scene) {
  64253. this._scene.unregisterBeforeRender(this._renderFunction);
  64254. this._scene = null;
  64255. this._renderFunction = null;
  64256. if (this._renderLine) {
  64257. this._renderLine.dispose();
  64258. this._renderLine = null;
  64259. }
  64260. this._renderPoints = [];
  64261. }
  64262. };
  64263. RayHelper.prototype._render = function () {
  64264. var ray = this.ray;
  64265. if (!ray) {
  64266. return;
  64267. }
  64268. var point = this._renderPoints[1];
  64269. var len = Math.min(ray.length, 1000000);
  64270. point.copyFrom(ray.direction);
  64271. point.scaleInPlace(len);
  64272. point.addInPlace(ray.origin);
  64273. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  64274. };
  64275. /**
  64276. * Attach a ray helper to a mesh so that we can easily see its orientation for instance or information like its normals.
  64277. * @param mesh Defines the mesh we want the helper attached to
  64278. * @param meshSpaceDirection Defines the direction of the Ray in mesh space (local space of the mesh node)
  64279. * @param meshSpaceOrigin Defines the origin of the Ray in mesh space (local space of the mesh node)
  64280. * @param length Defines the length of the ray
  64281. */
  64282. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  64283. this._attachedToMesh = mesh;
  64284. var ray = this.ray;
  64285. if (!ray) {
  64286. return;
  64287. }
  64288. if (!ray.direction) {
  64289. ray.direction = BABYLON.Vector3.Zero();
  64290. }
  64291. if (!ray.origin) {
  64292. ray.origin = BABYLON.Vector3.Zero();
  64293. }
  64294. if (length) {
  64295. ray.length = length;
  64296. }
  64297. if (!meshSpaceOrigin) {
  64298. meshSpaceOrigin = BABYLON.Vector3.Zero();
  64299. }
  64300. if (!meshSpaceDirection) {
  64301. // -1 so that this will work with Mesh.lookAt
  64302. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  64303. }
  64304. if (!this._meshSpaceDirection) {
  64305. this._meshSpaceDirection = meshSpaceDirection.clone();
  64306. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  64307. }
  64308. else {
  64309. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  64310. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  64311. }
  64312. if (!this._updateToMeshFunction) {
  64313. this._updateToMeshFunction = this._updateToMesh.bind(this);
  64314. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  64315. }
  64316. this._updateToMesh();
  64317. };
  64318. /**
  64319. * Detach the ray helper from the mesh it has previously been attached to.
  64320. */
  64321. RayHelper.prototype.detachFromMesh = function () {
  64322. if (this._attachedToMesh) {
  64323. if (this._updateToMeshFunction) {
  64324. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  64325. }
  64326. this._attachedToMesh = null;
  64327. this._updateToMeshFunction = null;
  64328. }
  64329. };
  64330. RayHelper.prototype._updateToMesh = function () {
  64331. var ray = this.ray;
  64332. if (!this._attachedToMesh || !ray) {
  64333. return;
  64334. }
  64335. if (this._attachedToMesh._isDisposed) {
  64336. this.detachFromMesh();
  64337. return;
  64338. }
  64339. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  64340. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  64341. };
  64342. /**
  64343. * Dispose the helper and release its associated resources.
  64344. */
  64345. RayHelper.prototype.dispose = function () {
  64346. this.hide();
  64347. this.detachFromMesh();
  64348. this.ray = null;
  64349. };
  64350. return RayHelper;
  64351. }());
  64352. BABYLON.RayHelper = RayHelper;
  64353. })(BABYLON || (BABYLON = {}));
  64354. //# sourceMappingURL=babylon.rayHelper.js.map
  64355. var BABYLON;
  64356. (function (BABYLON) {
  64357. Object.defineProperty(BABYLON.Scene.prototype, "debugLayer", {
  64358. get: function () {
  64359. if (!this._debugLayer) {
  64360. this._debugLayer = new DebugLayer(this);
  64361. }
  64362. return this._debugLayer;
  64363. },
  64364. enumerable: true,
  64365. configurable: true
  64366. });
  64367. /**
  64368. * The debug layer (aka Inspector) is the go to tool in order to better understand
  64369. * what is happening in your scene
  64370. * @see http://doc.babylonjs.com/features/playground_debuglayer
  64371. */
  64372. var DebugLayer = /** @class */ (function () {
  64373. /**
  64374. * Instantiates a new debug layer.
  64375. * The debug layer (aka Inspector) is the go to tool in order to better understand
  64376. * what is happening in your scene
  64377. * @see http://doc.babylonjs.com/features/playground_debuglayer
  64378. * @param scene Defines the scene to inspect
  64379. */
  64380. function DebugLayer(scene) {
  64381. var _this = this;
  64382. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  64383. /**
  64384. * Observable triggered when a property is changed through the inspector.
  64385. */
  64386. this.onPropertyChangedObservable = new BABYLON.Observable();
  64387. this._scene = scene;
  64388. this._scene.onDisposeObservable.add(function () {
  64389. // Debug layer
  64390. if (_this._scene._debugLayer) {
  64391. _this._scene._debugLayer.hide();
  64392. }
  64393. });
  64394. }
  64395. /** Creates the inspector window. */
  64396. DebugLayer.prototype._createInspector = function (config) {
  64397. if (config === void 0) { config = {}; }
  64398. var popup = config.popup || false;
  64399. var initialTab = config.initialTab || 0;
  64400. var parentElement = config.parentElement || null;
  64401. if (!this._inspector) {
  64402. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  64403. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  64404. } // else nothing to do as instance is already created
  64405. };
  64406. /**
  64407. * Get if the inspector is visible or not.
  64408. * @returns true if visible otherwise, false
  64409. */
  64410. DebugLayer.prototype.isVisible = function () {
  64411. if (!this._inspector) {
  64412. return false;
  64413. }
  64414. return true;
  64415. };
  64416. /**
  64417. * Hide the inspector and close its window.
  64418. */
  64419. DebugLayer.prototype.hide = function () {
  64420. if (this._inspector) {
  64421. try {
  64422. this._inspector.dispose();
  64423. }
  64424. catch (e) {
  64425. // If the inspector has been removed directly from the inspector tool
  64426. }
  64427. this.onPropertyChangedObservable.clear();
  64428. this._inspector = null;
  64429. }
  64430. };
  64431. /**
  64432. *
  64433. * Launch the debugLayer.
  64434. *
  64435. * initialTab:
  64436. * | Value | Tab Name |
  64437. * | --- | --- |
  64438. * | 0 | Scene |
  64439. * | 1 | Console |
  64440. * | 2 | Stats |
  64441. * | 3 | Textures |
  64442. * | 4 | Mesh |
  64443. * | 5 | Light |
  64444. * | 6 | Material |
  64445. * | 7 | GLTF |
  64446. * | 8 | GUI |
  64447. * | 9 | Physics |
  64448. * | 10 | Camera |
  64449. * | 11 | Audio |
  64450. *
  64451. * @param config Define the configuration of the inspector
  64452. */
  64453. DebugLayer.prototype.show = function (config) {
  64454. if (config === void 0) { config = {}; }
  64455. if (typeof this.BJSINSPECTOR == 'undefined') {
  64456. // Load inspector and add it to the DOM
  64457. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  64458. }
  64459. else {
  64460. // Otherwise creates the inspector
  64461. this._createInspector(config);
  64462. }
  64463. };
  64464. /**
  64465. * Gets the active tab
  64466. * @return the index of the active tab or -1 if the inspector is hidden
  64467. */
  64468. DebugLayer.prototype.getActiveTab = function () {
  64469. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  64470. };
  64471. /**
  64472. * Define the url to get the inspector script from.
  64473. * By default it uses the babylonjs CDN.
  64474. * @ignoreNaming
  64475. */
  64476. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  64477. return DebugLayer;
  64478. }());
  64479. BABYLON.DebugLayer = DebugLayer;
  64480. })(BABYLON || (BABYLON = {}));
  64481. //# sourceMappingURL=babylon.debugLayer.js.map
  64482. var BABYLON;
  64483. (function (BABYLON) {
  64484. var Debug;
  64485. (function (Debug) {
  64486. /**
  64487. * Used to show the physics impostor around the specific mesh
  64488. */
  64489. var PhysicsViewer = /** @class */ (function () {
  64490. /**
  64491. * Creates a new PhysicsViewer
  64492. * @param scene defines the hosting scene
  64493. */
  64494. function PhysicsViewer(scene) {
  64495. /** @hidden */
  64496. this._impostors = [];
  64497. /** @hidden */
  64498. this._meshes = [];
  64499. /** @hidden */
  64500. this._numMeshes = 0;
  64501. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  64502. var physicEngine = this._scene.getPhysicsEngine();
  64503. if (physicEngine) {
  64504. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  64505. }
  64506. }
  64507. /** @hidden */
  64508. PhysicsViewer.prototype._updateDebugMeshes = function () {
  64509. var plugin = this._physicsEnginePlugin;
  64510. for (var i = 0; i < this._numMeshes; i++) {
  64511. var impostor = this._impostors[i];
  64512. if (!impostor) {
  64513. continue;
  64514. }
  64515. if (impostor.isDisposed) {
  64516. this.hideImpostor(this._impostors[i--]);
  64517. }
  64518. else {
  64519. var mesh = this._meshes[i];
  64520. if (mesh && plugin) {
  64521. plugin.syncMeshWithImpostor(mesh, impostor);
  64522. }
  64523. }
  64524. }
  64525. };
  64526. /**
  64527. * Renders a specified physic impostor
  64528. * @param impostor defines the impostor to render
  64529. */
  64530. PhysicsViewer.prototype.showImpostor = function (impostor) {
  64531. if (!this._scene) {
  64532. return;
  64533. }
  64534. for (var i = 0; i < this._numMeshes; i++) {
  64535. if (this._impostors[i] == impostor) {
  64536. return;
  64537. }
  64538. }
  64539. var debugMesh = this._getDebugMesh(impostor, this._scene);
  64540. if (debugMesh) {
  64541. this._impostors[this._numMeshes] = impostor;
  64542. this._meshes[this._numMeshes] = debugMesh;
  64543. if (this._numMeshes === 0) {
  64544. this._renderFunction = this._updateDebugMeshes.bind(this);
  64545. this._scene.registerBeforeRender(this._renderFunction);
  64546. }
  64547. this._numMeshes++;
  64548. }
  64549. };
  64550. /**
  64551. * Hides a specified physic impostor
  64552. * @param impostor defines the impostor to hide
  64553. */
  64554. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  64555. if (!impostor || !this._scene) {
  64556. return;
  64557. }
  64558. var removed = false;
  64559. for (var i = 0; i < this._numMeshes; i++) {
  64560. if (this._impostors[i] == impostor) {
  64561. var mesh = this._meshes[i];
  64562. if (!mesh) {
  64563. continue;
  64564. }
  64565. this._scene.removeMesh(mesh);
  64566. mesh.dispose();
  64567. this._numMeshes--;
  64568. if (this._numMeshes > 0) {
  64569. this._meshes[i] = this._meshes[this._numMeshes];
  64570. this._impostors[i] = this._impostors[this._numMeshes];
  64571. this._meshes[this._numMeshes] = null;
  64572. this._impostors[this._numMeshes] = null;
  64573. }
  64574. else {
  64575. this._meshes[0] = null;
  64576. this._impostors[0] = null;
  64577. }
  64578. removed = true;
  64579. break;
  64580. }
  64581. }
  64582. if (removed && this._numMeshes === 0) {
  64583. this._scene.unregisterBeforeRender(this._renderFunction);
  64584. }
  64585. };
  64586. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  64587. if (!this._debugMaterial) {
  64588. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  64589. this._debugMaterial.wireframe = true;
  64590. }
  64591. return this._debugMaterial;
  64592. };
  64593. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  64594. if (!this._debugBoxMesh) {
  64595. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  64596. this._debugBoxMesh.renderingGroupId = 1;
  64597. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  64598. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  64599. scene.removeMesh(this._debugBoxMesh);
  64600. }
  64601. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  64602. };
  64603. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  64604. if (!this._debugSphereMesh) {
  64605. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  64606. this._debugSphereMesh.renderingGroupId = 1;
  64607. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  64608. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  64609. scene.removeMesh(this._debugSphereMesh);
  64610. }
  64611. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  64612. };
  64613. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  64614. var mesh = null;
  64615. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  64616. mesh = this._getDebugBoxMesh(scene);
  64617. impostor.getBoxSizeToRef(mesh.scaling);
  64618. }
  64619. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  64620. mesh = this._getDebugSphereMesh(scene);
  64621. var radius = impostor.getRadius();
  64622. mesh.scaling.x = radius * 2;
  64623. mesh.scaling.y = radius * 2;
  64624. mesh.scaling.z = radius * 2;
  64625. }
  64626. return mesh;
  64627. };
  64628. /** Releases all resources */
  64629. PhysicsViewer.prototype.dispose = function () {
  64630. for (var i = 0; i < this._numMeshes; i++) {
  64631. this.hideImpostor(this._impostors[i]);
  64632. }
  64633. if (this._debugBoxMesh) {
  64634. this._debugBoxMesh.dispose();
  64635. }
  64636. if (this._debugSphereMesh) {
  64637. this._debugSphereMesh.dispose();
  64638. }
  64639. if (this._debugMaterial) {
  64640. this._debugMaterial.dispose();
  64641. }
  64642. this._impostors.length = 0;
  64643. this._scene = null;
  64644. this._physicsEnginePlugin = null;
  64645. };
  64646. return PhysicsViewer;
  64647. }());
  64648. Debug.PhysicsViewer = PhysicsViewer;
  64649. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  64650. })(BABYLON || (BABYLON = {}));
  64651. //# sourceMappingURL=babylon.physicsViewer.js.map
  64652. var BABYLON;
  64653. (function (BABYLON) {
  64654. Object.defineProperty(BABYLON.Scene.prototype, "forceShowBoundingBoxes", {
  64655. get: function () {
  64656. return this._forceShowBoundingBoxes || false;
  64657. },
  64658. set: function (value) {
  64659. this._forceShowBoundingBoxes = value;
  64660. // Lazyly creates a BB renderer if needed.
  64661. if (value) {
  64662. this.getBoundingBoxRenderer();
  64663. }
  64664. },
  64665. enumerable: true,
  64666. configurable: true
  64667. });
  64668. BABYLON.Scene.prototype.getBoundingBoxRenderer = function () {
  64669. if (!this._boundingBoxRenderer) {
  64670. this._boundingBoxRenderer = new BoundingBoxRenderer(this);
  64671. }
  64672. return this._boundingBoxRenderer;
  64673. };
  64674. Object.defineProperty(BABYLON.AbstractMesh.prototype, "showBoundingBox", {
  64675. get: function () {
  64676. return this._showBoundingBox || false;
  64677. },
  64678. set: function (value) {
  64679. this._showBoundingBox = value;
  64680. // Lazyly creates a BB renderer if needed.
  64681. if (value) {
  64682. this.getScene().getBoundingBoxRenderer();
  64683. }
  64684. },
  64685. enumerable: true,
  64686. configurable: true
  64687. });
  64688. /**
  64689. * Component responsible of rendering the bounding box of the meshes in a scene.
  64690. * This is usually used through the mesh.showBoundingBox or the scene.forceShowBoundingBoxes properties
  64691. */
  64692. var BoundingBoxRenderer = /** @class */ (function () {
  64693. /**
  64694. * Instantiates a new bounding box renderer in a scene.
  64695. * @param scene the scene the renderer renders in
  64696. */
  64697. function BoundingBoxRenderer(scene) {
  64698. /**
  64699. * The component name helpfull to identify the component in the list of scene components.
  64700. */
  64701. this.name = BABYLON.SceneComponentConstants.NAME_BOUNDINGBOXRENDERER;
  64702. /**
  64703. * Color of the bounding box lines placed in front of an object
  64704. */
  64705. this.frontColor = new BABYLON.Color3(1, 1, 1);
  64706. /**
  64707. * Color of the bounding box lines placed behind an object
  64708. */
  64709. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  64710. /**
  64711. * Defines if the renderer should show the back lines or not
  64712. */
  64713. this.showBackLines = true;
  64714. /**
  64715. * @hidden
  64716. */
  64717. this.renderList = new BABYLON.SmartArray(32);
  64718. this._vertexBuffers = {};
  64719. this.scene = scene;
  64720. scene._addComponent(this);
  64721. }
  64722. /**
  64723. * Registers the component in a given scene
  64724. */
  64725. BoundingBoxRenderer.prototype.register = function () {
  64726. this.scene._beforeEvaluateActiveMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER, this, this.reset);
  64727. this.scene._activeMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER, this, this._activeMesh);
  64728. this.scene._evaluateSubMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER, this, this._evaluateSubMesh);
  64729. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER, this, this.render);
  64730. };
  64731. BoundingBoxRenderer.prototype._evaluateSubMesh = function (mesh, subMesh) {
  64732. if (mesh.showSubMeshesBoundingBox) {
  64733. var boundingInfo = subMesh.getBoundingInfo();
  64734. if (boundingInfo !== null && boundingInfo !== undefined) {
  64735. boundingInfo.boundingBox._tag = mesh.renderingGroupId;
  64736. this.renderList.push(boundingInfo.boundingBox);
  64737. }
  64738. }
  64739. };
  64740. BoundingBoxRenderer.prototype._activeMesh = function (sourceMesh, mesh) {
  64741. if (sourceMesh.showBoundingBox || this.scene.forceShowBoundingBoxes) {
  64742. var boundingInfo = sourceMesh.getBoundingInfo();
  64743. boundingInfo.boundingBox._tag = mesh.renderingGroupId;
  64744. this.renderList.push(boundingInfo.boundingBox);
  64745. }
  64746. };
  64747. BoundingBoxRenderer.prototype._prepareRessources = function () {
  64748. if (this._colorShader) {
  64749. return;
  64750. }
  64751. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this.scene, "color", {
  64752. attributes: [BABYLON.VertexBuffer.PositionKind],
  64753. uniforms: ["world", "viewProjection", "color"]
  64754. });
  64755. var engine = this.scene.getEngine();
  64756. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  64757. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  64758. this._createIndexBuffer();
  64759. };
  64760. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  64761. var engine = this.scene.getEngine();
  64762. 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]);
  64763. };
  64764. /**
  64765. * Rebuilds the elements related to this component in case of
  64766. * context lost for instance.
  64767. */
  64768. BoundingBoxRenderer.prototype.rebuild = function () {
  64769. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  64770. if (vb) {
  64771. vb._rebuild();
  64772. }
  64773. this._createIndexBuffer();
  64774. };
  64775. /**
  64776. * @hidden
  64777. */
  64778. BoundingBoxRenderer.prototype.reset = function () {
  64779. this.renderList.reset();
  64780. };
  64781. /**
  64782. * Render the bounding boxes of a specific rendering group
  64783. * @param renderingGroupId defines the rendering group to render
  64784. */
  64785. BoundingBoxRenderer.prototype.render = function (renderingGroupId) {
  64786. if (this.renderList.length === 0) {
  64787. return;
  64788. }
  64789. this._prepareRessources();
  64790. if (!this._colorShader.isReady()) {
  64791. return;
  64792. }
  64793. var engine = this.scene.getEngine();
  64794. engine.setDepthWrite(false);
  64795. this._colorShader._preBind();
  64796. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  64797. var boundingBox = this.renderList.data[boundingBoxIndex];
  64798. if (boundingBox._tag !== renderingGroupId) {
  64799. continue;
  64800. }
  64801. var min = boundingBox.minimum;
  64802. var max = boundingBox.maximum;
  64803. var diff = max.subtract(min);
  64804. var median = min.add(diff.scale(0.5));
  64805. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  64806. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  64807. .multiply(boundingBox.getWorldMatrix());
  64808. // VBOs
  64809. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  64810. if (this.showBackLines) {
  64811. // Back
  64812. engine.setDepthFunctionToGreaterOrEqual();
  64813. this.scene.resetCachedMaterial();
  64814. this._colorShader.setColor4("color", this.backColor.toColor4());
  64815. this._colorShader.bind(worldMatrix);
  64816. // Draw order
  64817. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  64818. }
  64819. // Front
  64820. engine.setDepthFunctionToLess();
  64821. this.scene.resetCachedMaterial();
  64822. this._colorShader.setColor4("color", this.frontColor.toColor4());
  64823. this._colorShader.bind(worldMatrix);
  64824. // Draw order
  64825. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  64826. }
  64827. this._colorShader.unbind();
  64828. engine.setDepthFunctionToLessOrEqual();
  64829. engine.setDepthWrite(true);
  64830. };
  64831. /**
  64832. * In case of occlusion queries, we can render the occlusion bounding box through this method
  64833. * @param mesh Define the mesh to render the occlusion bounding box for
  64834. */
  64835. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  64836. this._prepareRessources();
  64837. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  64838. return;
  64839. }
  64840. var engine = this.scene.getEngine();
  64841. engine.setDepthWrite(false);
  64842. engine.setColorWrite(false);
  64843. this._colorShader._preBind();
  64844. var boundingBox = mesh._boundingInfo.boundingBox;
  64845. var min = boundingBox.minimum;
  64846. var max = boundingBox.maximum;
  64847. var diff = max.subtract(min);
  64848. var median = min.add(diff.scale(0.5));
  64849. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  64850. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  64851. .multiply(boundingBox.getWorldMatrix());
  64852. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  64853. engine.setDepthFunctionToLess();
  64854. this.scene.resetCachedMaterial();
  64855. this._colorShader.bind(worldMatrix);
  64856. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  64857. this._colorShader.unbind();
  64858. engine.setDepthFunctionToLessOrEqual();
  64859. engine.setDepthWrite(true);
  64860. engine.setColorWrite(true);
  64861. };
  64862. /**
  64863. * Dispose and release the resources attached to this renderer.
  64864. */
  64865. BoundingBoxRenderer.prototype.dispose = function () {
  64866. if (!this._colorShader) {
  64867. return;
  64868. }
  64869. this.renderList.dispose();
  64870. this._colorShader.dispose();
  64871. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  64872. if (buffer) {
  64873. buffer.dispose();
  64874. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  64875. }
  64876. this.scene.getEngine()._releaseBuffer(this._indexBuffer);
  64877. };
  64878. return BoundingBoxRenderer;
  64879. }());
  64880. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  64881. })(BABYLON || (BABYLON = {}));
  64882. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  64883. var BABYLON;
  64884. (function (BABYLON) {
  64885. BABYLON.Engine.prototype.createTransformFeedback = function () {
  64886. return this._gl.createTransformFeedback();
  64887. };
  64888. BABYLON.Engine.prototype.deleteTransformFeedback = function (value) {
  64889. this._gl.deleteTransformFeedback(value);
  64890. };
  64891. BABYLON.Engine.prototype.bindTransformFeedback = function (value) {
  64892. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  64893. };
  64894. BABYLON.Engine.prototype.beginTransformFeedback = function (usePoints) {
  64895. if (usePoints === void 0) { usePoints = true; }
  64896. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  64897. };
  64898. BABYLON.Engine.prototype.endTransformFeedback = function () {
  64899. this._gl.endTransformFeedback();
  64900. };
  64901. BABYLON.Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  64902. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  64903. };
  64904. BABYLON.Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  64905. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  64906. };
  64907. })(BABYLON || (BABYLON = {}));
  64908. //# sourceMappingURL=babylon.engine.transformFeedback.js.map
  64909. var BABYLON;
  64910. (function (BABYLON) {
  64911. /**
  64912. * This represents a GPU particle system in Babylon
  64913. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  64914. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  64915. */
  64916. var GPUParticleSystem = /** @class */ (function (_super) {
  64917. __extends(GPUParticleSystem, _super);
  64918. /**
  64919. * Instantiates a GPU particle system.
  64920. * 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.
  64921. * @param name The name of the particle system
  64922. * @param options The options used to create the system
  64923. * @param scene The scene the particle system belongs to
  64924. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  64925. */
  64926. function GPUParticleSystem(name, options, scene, isAnimationSheetEnabled) {
  64927. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  64928. var _this = _super.call(this, name) || this;
  64929. /**
  64930. * The layer mask we are rendering the particles through.
  64931. */
  64932. _this.layerMask = 0x0FFFFFFF;
  64933. _this._accumulatedCount = 0;
  64934. _this._targetIndex = 0;
  64935. _this._currentRenderId = -1;
  64936. _this._started = false;
  64937. _this._stopped = false;
  64938. _this._timeDelta = 0;
  64939. _this._attributesStrideSize = 21;
  64940. _this._actualFrame = 0;
  64941. _this._rawTextureWidth = 256;
  64942. /**
  64943. * An event triggered when the system is disposed.
  64944. */
  64945. _this.onDisposeObservable = new BABYLON.Observable();
  64946. /**
  64947. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  64948. * to override the particles.
  64949. */
  64950. _this.forceDepthWrite = false;
  64951. _this._preWarmDone = false;
  64952. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  64953. // Setup the default processing configuration to the scene.
  64954. _this._attachImageProcessingConfiguration(null);
  64955. _this._engine = _this._scene.getEngine();
  64956. if (!options.randomTextureSize) {
  64957. delete options.randomTextureSize;
  64958. }
  64959. var fullOptions = __assign({ capacity: 50000, randomTextureSize: _this._engine.getCaps().maxTextureSize }, options);
  64960. var optionsAsNumber = options;
  64961. if (isFinite(optionsAsNumber)) {
  64962. fullOptions.capacity = optionsAsNumber;
  64963. }
  64964. _this._capacity = fullOptions.capacity;
  64965. _this._activeCount = fullOptions.capacity;
  64966. _this._currentActiveCount = 0;
  64967. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  64968. _this._scene.particleSystems.push(_this);
  64969. _this._updateEffectOptions = {
  64970. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "initialDirection", "angle", "cellIndex", "cellStartOffset", "noiseCoordinates1", "noiseCoordinates2"],
  64971. uniformsNames: ["currentCount", "timeDelta", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange", "gravity", "emitPower",
  64972. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  64973. "angleRange", "radiusRange", "cellInfos", "noiseStrength", "limitVelocityDamping"],
  64974. uniformBuffersNames: [],
  64975. samplers: ["randomSampler", "randomSampler2", "sizeGradientSampler", "angularSpeedGradientSampler", "velocityGradientSampler", "limitVelocityGradientSampler", "noiseSampler", "dragGradientSampler"],
  64976. defines: "",
  64977. fallbacks: null,
  64978. onCompiled: null,
  64979. onError: null,
  64980. indexParameters: null,
  64981. maxSimultaneousLights: 0,
  64982. transformFeedbackVaryings: []
  64983. };
  64984. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  64985. // Random data
  64986. var maxTextureSize = Math.min(_this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  64987. var d = [];
  64988. for (var i = 0; i < maxTextureSize; ++i) {
  64989. d.push(Math.random());
  64990. d.push(Math.random());
  64991. d.push(Math.random());
  64992. d.push(Math.random());
  64993. }
  64994. _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);
  64995. _this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  64996. _this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  64997. d = [];
  64998. for (var i = 0; i < maxTextureSize; ++i) {
  64999. d.push(Math.random());
  65000. d.push(Math.random());
  65001. d.push(Math.random());
  65002. d.push(Math.random());
  65003. }
  65004. _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);
  65005. _this._randomTexture2.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  65006. _this._randomTexture2.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  65007. _this._randomTextureSize = maxTextureSize;
  65008. return _this;
  65009. }
  65010. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  65011. /**
  65012. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  65013. */
  65014. get: function () {
  65015. if (!BABYLON.Engine.LastCreatedEngine) {
  65016. return false;
  65017. }
  65018. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  65019. },
  65020. enumerable: true,
  65021. configurable: true
  65022. });
  65023. /**
  65024. * Gets the maximum number of particles active at the same time.
  65025. * @returns The max number of active particles.
  65026. */
  65027. GPUParticleSystem.prototype.getCapacity = function () {
  65028. return this._capacity;
  65029. };
  65030. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  65031. /**
  65032. * Gets or set the number of active particles
  65033. */
  65034. get: function () {
  65035. return this._activeCount;
  65036. },
  65037. set: function (value) {
  65038. this._activeCount = Math.min(value, this._capacity);
  65039. },
  65040. enumerable: true,
  65041. configurable: true
  65042. });
  65043. /**
  65044. * Is this system ready to be used/rendered
  65045. * @return true if the system is ready
  65046. */
  65047. GPUParticleSystem.prototype.isReady = function () {
  65048. if (!this._updateEffect) {
  65049. this._recreateUpdateEffect();
  65050. this._recreateRenderEffect();
  65051. return false;
  65052. }
  65053. if (!this.emitter || !this._updateEffect.isReady() || !this._imageProcessingConfiguration.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  65054. return false;
  65055. }
  65056. return true;
  65057. };
  65058. /**
  65059. * Gets if the system has been started. (Note: this will still be true after stop is called)
  65060. * @returns True if it has been started, otherwise false.
  65061. */
  65062. GPUParticleSystem.prototype.isStarted = function () {
  65063. return this._started;
  65064. };
  65065. /**
  65066. * Starts the particle system and begins to emit
  65067. * @param delay defines the delay in milliseconds before starting the system (this.startDelay by default)
  65068. */
  65069. GPUParticleSystem.prototype.start = function (delay) {
  65070. var _this = this;
  65071. if (delay === void 0) { delay = this.startDelay; }
  65072. if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) {
  65073. throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";
  65074. }
  65075. if (delay) {
  65076. setTimeout(function () {
  65077. _this.start(0);
  65078. }, delay);
  65079. return;
  65080. }
  65081. this._started = true;
  65082. this._stopped = false;
  65083. this._preWarmDone = false;
  65084. // Animations
  65085. if (this.beginAnimationOnStart && this.animations && this.animations.length > 0) {
  65086. this.getScene().beginAnimation(this, this.beginAnimationFrom, this.beginAnimationTo, this.beginAnimationLoop);
  65087. }
  65088. };
  65089. /**
  65090. * Stops the particle system.
  65091. */
  65092. GPUParticleSystem.prototype.stop = function () {
  65093. this._stopped = true;
  65094. };
  65095. /**
  65096. * Remove all active particles
  65097. */
  65098. GPUParticleSystem.prototype.reset = function () {
  65099. this._releaseBuffers();
  65100. this._releaseVAOs();
  65101. this._currentActiveCount = 0;
  65102. this._targetIndex = 0;
  65103. };
  65104. /**
  65105. * Returns the string "GPUParticleSystem"
  65106. * @returns a string containing the class name
  65107. */
  65108. GPUParticleSystem.prototype.getClassName = function () {
  65109. return "GPUParticleSystem";
  65110. };
  65111. GPUParticleSystem.prototype._removeGradientAndTexture = function (gradient, gradients, texture) {
  65112. _super.prototype._removeGradientAndTexture.call(this, gradient, gradients, texture);
  65113. this._releaseBuffers();
  65114. return this;
  65115. };
  65116. /**
  65117. * Adds a new color gradient
  65118. * @param gradient defines the gradient to use (between 0 and 1)
  65119. * @param color1 defines the color to affect to the specified gradient
  65120. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  65121. * @returns the current particle system
  65122. */
  65123. GPUParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  65124. if (!this._colorGradients) {
  65125. this._colorGradients = [];
  65126. }
  65127. var colorGradient = new BABYLON.ColorGradient();
  65128. colorGradient.gradient = gradient;
  65129. colorGradient.color1 = color1;
  65130. this._colorGradients.push(colorGradient);
  65131. this._colorGradients.sort(function (a, b) {
  65132. if (a.gradient < b.gradient) {
  65133. return -1;
  65134. }
  65135. else if (a.gradient > b.gradient) {
  65136. return 1;
  65137. }
  65138. return 0;
  65139. });
  65140. if (this._colorGradientsTexture) {
  65141. this._colorGradientsTexture.dispose();
  65142. this._colorGradientsTexture = null;
  65143. }
  65144. this._releaseBuffers();
  65145. return this;
  65146. };
  65147. /**
  65148. * Remove a specific color gradient
  65149. * @param gradient defines the gradient to remove
  65150. * @returns the current particle system
  65151. */
  65152. GPUParticleSystem.prototype.removeColorGradient = function (gradient) {
  65153. this._removeGradientAndTexture(gradient, this._colorGradients, this._colorGradientsTexture);
  65154. this._colorGradientsTexture = null;
  65155. return this;
  65156. };
  65157. GPUParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor) {
  65158. var valueGradient = new BABYLON.FactorGradient();
  65159. valueGradient.gradient = gradient;
  65160. valueGradient.factor1 = factor;
  65161. factorGradients.push(valueGradient);
  65162. factorGradients.sort(function (a, b) {
  65163. if (a.gradient < b.gradient) {
  65164. return -1;
  65165. }
  65166. else if (a.gradient > b.gradient) {
  65167. return 1;
  65168. }
  65169. return 0;
  65170. });
  65171. this._releaseBuffers();
  65172. };
  65173. /**
  65174. * Adds a new size gradient
  65175. * @param gradient defines the gradient to use (between 0 and 1)
  65176. * @param factor defines the size factor to affect to the specified gradient
  65177. * @returns the current particle system
  65178. */
  65179. GPUParticleSystem.prototype.addSizeGradient = function (gradient, factor) {
  65180. if (!this._sizeGradients) {
  65181. this._sizeGradients = [];
  65182. }
  65183. this._addFactorGradient(this._sizeGradients, gradient, factor);
  65184. if (this._sizeGradientsTexture) {
  65185. this._sizeGradientsTexture.dispose();
  65186. this._sizeGradientsTexture = null;
  65187. }
  65188. this._releaseBuffers();
  65189. return this;
  65190. };
  65191. /**
  65192. * Remove a specific size gradient
  65193. * @param gradient defines the gradient to remove
  65194. * @returns the current particle system
  65195. */
  65196. GPUParticleSystem.prototype.removeSizeGradient = function (gradient) {
  65197. this._removeGradientAndTexture(gradient, this._sizeGradients, this._sizeGradientsTexture);
  65198. this._sizeGradientsTexture = null;
  65199. return this;
  65200. };
  65201. /**
  65202. * Adds a new angular speed gradient
  65203. * @param gradient defines the gradient to use (between 0 and 1)
  65204. * @param factor defines the angular speed to affect to the specified gradient
  65205. * @returns the current particle system
  65206. */
  65207. GPUParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor) {
  65208. if (!this._angularSpeedGradients) {
  65209. this._angularSpeedGradients = [];
  65210. }
  65211. this._addFactorGradient(this._angularSpeedGradients, gradient, factor);
  65212. if (this._angularSpeedGradientsTexture) {
  65213. this._angularSpeedGradientsTexture.dispose();
  65214. this._angularSpeedGradientsTexture = null;
  65215. }
  65216. this._releaseBuffers();
  65217. return this;
  65218. };
  65219. /**
  65220. * Remove a specific angular speed gradient
  65221. * @param gradient defines the gradient to remove
  65222. * @returns the current particle system
  65223. */
  65224. GPUParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  65225. this._removeGradientAndTexture(gradient, this._angularSpeedGradients, this._angularSpeedGradientsTexture);
  65226. this._angularSpeedGradientsTexture = null;
  65227. return this;
  65228. };
  65229. /**
  65230. * Adds a new velocity gradient
  65231. * @param gradient defines the gradient to use (between 0 and 1)
  65232. * @param factor defines the velocity to affect to the specified gradient
  65233. * @returns the current particle system
  65234. */
  65235. GPUParticleSystem.prototype.addVelocityGradient = function (gradient, factor) {
  65236. if (!this._velocityGradients) {
  65237. this._velocityGradients = [];
  65238. }
  65239. this._addFactorGradient(this._velocityGradients, gradient, factor);
  65240. if (this._velocityGradientsTexture) {
  65241. this._velocityGradientsTexture.dispose();
  65242. this._velocityGradientsTexture = null;
  65243. }
  65244. this._releaseBuffers();
  65245. return this;
  65246. };
  65247. /**
  65248. * Remove a specific velocity gradient
  65249. * @param gradient defines the gradient to remove
  65250. * @returns the current particle system
  65251. */
  65252. GPUParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  65253. this._removeGradientAndTexture(gradient, this._velocityGradients, this._velocityGradientsTexture);
  65254. this._velocityGradientsTexture = null;
  65255. return this;
  65256. };
  65257. /**
  65258. * Adds a new limit velocity gradient
  65259. * @param gradient defines the gradient to use (between 0 and 1)
  65260. * @param factor defines the limit velocity value to affect to the specified gradient
  65261. * @returns the current particle system
  65262. */
  65263. GPUParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor) {
  65264. if (!this._limitVelocityGradients) {
  65265. this._limitVelocityGradients = [];
  65266. }
  65267. this._addFactorGradient(this._limitVelocityGradients, gradient, factor);
  65268. if (this._limitVelocityGradientsTexture) {
  65269. this._limitVelocityGradientsTexture.dispose();
  65270. this._limitVelocityGradientsTexture = null;
  65271. }
  65272. this._releaseBuffers();
  65273. return this;
  65274. };
  65275. /**
  65276. * Remove a specific limit velocity gradient
  65277. * @param gradient defines the gradient to remove
  65278. * @returns the current particle system
  65279. */
  65280. GPUParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  65281. this._removeGradientAndTexture(gradient, this._limitVelocityGradients, this._limitVelocityGradientsTexture);
  65282. this._limitVelocityGradientsTexture = null;
  65283. return this;
  65284. };
  65285. /**
  65286. * Adds a new drag gradient
  65287. * @param gradient defines the gradient to use (between 0 and 1)
  65288. * @param factor defines the drag value to affect to the specified gradient
  65289. * @returns the current particle system
  65290. */
  65291. GPUParticleSystem.prototype.addDragGradient = function (gradient, factor) {
  65292. if (!this._dragGradients) {
  65293. this._dragGradients = [];
  65294. }
  65295. this._addFactorGradient(this._dragGradients, gradient, factor);
  65296. if (this._dragGradientsTexture) {
  65297. this._dragGradientsTexture.dispose();
  65298. this._dragGradientsTexture = null;
  65299. }
  65300. this._releaseBuffers();
  65301. return this;
  65302. };
  65303. /**
  65304. * Remove a specific drag gradient
  65305. * @param gradient defines the gradient to remove
  65306. * @returns the current particle system
  65307. */
  65308. GPUParticleSystem.prototype.removeDragGradient = function (gradient) {
  65309. this._removeGradientAndTexture(gradient, this._dragGradients, this._dragGradientsTexture);
  65310. this._dragGradientsTexture = null;
  65311. return this;
  65312. };
  65313. /**
  65314. * Not supported by GPUParticleSystem
  65315. * @param gradient defines the gradient to use (between 0 and 1)
  65316. * @param factor defines the emit rate value to affect to the specified gradient
  65317. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  65318. * @returns the current particle system
  65319. */
  65320. GPUParticleSystem.prototype.addEmitRateGradient = function (gradient, factor, factor2) {
  65321. // Do nothing as emit rate is not supported by GPUParticleSystem
  65322. return this;
  65323. };
  65324. /**
  65325. * Not supported by GPUParticleSystem
  65326. * @param gradient defines the gradient to remove
  65327. * @returns the current particle system
  65328. */
  65329. GPUParticleSystem.prototype.removeEmitRateGradient = function (gradient) {
  65330. // Do nothing as emit rate is not supported by GPUParticleSystem
  65331. return this;
  65332. };
  65333. /**
  65334. * Not supported by GPUParticleSystem
  65335. * @param gradient defines the gradient to use (between 0 and 1)
  65336. * @param factor defines the start size value to affect to the specified gradient
  65337. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  65338. * @returns the current particle system
  65339. */
  65340. GPUParticleSystem.prototype.addStartSizeGradient = function (gradient, factor, factor2) {
  65341. // Do nothing as start size is not supported by GPUParticleSystem
  65342. return this;
  65343. };
  65344. /**
  65345. * Not supported by GPUParticleSystem
  65346. * @param gradient defines the gradient to remove
  65347. * @returns the current particle system
  65348. */
  65349. GPUParticleSystem.prototype.removeStartSizeGradient = function (gradient) {
  65350. // Do nothing as start size is not supported by GPUParticleSystem
  65351. return this;
  65352. };
  65353. /**
  65354. * Not supported by GPUParticleSystem
  65355. * @param gradient defines the gradient to use (between 0 and 1)
  65356. * @param min defines the color remap minimal range
  65357. * @param max defines the color remap maximal range
  65358. * @returns the current particle system
  65359. */
  65360. GPUParticleSystem.prototype.addColorRemapGradient = function (gradient, min, max) {
  65361. // Do nothing as start size is not supported by GPUParticleSystem
  65362. return this;
  65363. };
  65364. /**
  65365. * Not supported by GPUParticleSystem
  65366. * @param gradient defines the gradient to remove
  65367. * @returns the current particle system
  65368. */
  65369. GPUParticleSystem.prototype.removeColorRemapGradient = function (gradient) {
  65370. // Do nothing as start size is not supported by GPUParticleSystem
  65371. return this;
  65372. };
  65373. /**
  65374. * Not supported by GPUParticleSystem
  65375. * @param gradient defines the gradient to use (between 0 and 1)
  65376. * @param min defines the alpha remap minimal range
  65377. * @param max defines the alpha remap maximal range
  65378. * @returns the current particle system
  65379. */
  65380. GPUParticleSystem.prototype.addAlphaRemapGradient = function (gradient, min, max) {
  65381. // Do nothing as start size is not supported by GPUParticleSystem
  65382. return this;
  65383. };
  65384. /**
  65385. * Not supported by GPUParticleSystem
  65386. * @param gradient defines the gradient to remove
  65387. * @returns the current particle system
  65388. */
  65389. GPUParticleSystem.prototype.removeAlphaRemapGradient = function (gradient) {
  65390. // Do nothing as start size is not supported by GPUParticleSystem
  65391. return this;
  65392. };
  65393. /**
  65394. * Not supported by GPUParticleSystem
  65395. * @param gradient defines the gradient to use (between 0 and 1)
  65396. * @param color defines the color to affect to the specified gradient
  65397. * @returns the current particle system
  65398. */
  65399. GPUParticleSystem.prototype.addRampGradient = function (gradient, color) {
  65400. //Not supported by GPUParticleSystem
  65401. return this;
  65402. };
  65403. /**
  65404. * Not supported by GPUParticleSystem
  65405. * @param gradient defines the gradient to remove
  65406. * @returns the current particle system
  65407. */
  65408. GPUParticleSystem.prototype.removeRampGradient = function (gradient) {
  65409. //Not supported by GPUParticleSystem
  65410. return this;
  65411. };
  65412. /**
  65413. * Not supported by GPUParticleSystem
  65414. * @returns the list of ramp gradients
  65415. */
  65416. GPUParticleSystem.prototype.getRampGradients = function () {
  65417. return null;
  65418. };
  65419. Object.defineProperty(GPUParticleSystem.prototype, "useRampGradients", {
  65420. /**
  65421. * Not supported by GPUParticleSystem
  65422. * Gets or sets a boolean indicating that ramp gradients must be used
  65423. * @see http://doc.babylonjs.com/babylon101/particles#ramp-gradients
  65424. */
  65425. get: function () {
  65426. //Not supported by GPUParticleSystem
  65427. return false;
  65428. },
  65429. set: function (value) {
  65430. //Not supported by GPUParticleSystem
  65431. },
  65432. enumerable: true,
  65433. configurable: true
  65434. });
  65435. /**
  65436. * Not supported by GPUParticleSystem
  65437. * @param gradient defines the gradient to use (between 0 and 1)
  65438. * @param factor defines the life time factor to affect to the specified gradient
  65439. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  65440. * @returns the current particle system
  65441. */
  65442. GPUParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  65443. //Not supported by GPUParticleSystem
  65444. return this;
  65445. };
  65446. /**
  65447. * Not supported by GPUParticleSystem
  65448. * @param gradient defines the gradient to remove
  65449. * @returns the current particle system
  65450. */
  65451. GPUParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  65452. //Not supported by GPUParticleSystem
  65453. return this;
  65454. };
  65455. GPUParticleSystem.prototype._reset = function () {
  65456. this._releaseBuffers();
  65457. };
  65458. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  65459. var updateVertexBuffers = {};
  65460. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  65461. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  65462. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  65463. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 4);
  65464. updateVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3);
  65465. var offset = 12;
  65466. if (!this._colorGradientsTexture) {
  65467. updateVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4);
  65468. offset += 4;
  65469. }
  65470. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3);
  65471. offset += 3;
  65472. if (!this._isBillboardBased) {
  65473. updateVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3);
  65474. offset += 3;
  65475. }
  65476. if (this._angularSpeedGradientsTexture) {
  65477. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1);
  65478. offset += 1;
  65479. }
  65480. else {
  65481. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2);
  65482. offset += 2;
  65483. }
  65484. if (this._isAnimationSheetEnabled) {
  65485. updateVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1);
  65486. offset += 1;
  65487. if (this.spriteRandomStartCell) {
  65488. updateVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1);
  65489. offset += 1;
  65490. }
  65491. }
  65492. if (this.noiseTexture) {
  65493. updateVertexBuffers["noiseCoordinates1"] = source.createVertexBuffer("noiseCoordinates1", offset, 3);
  65494. offset += 3;
  65495. updateVertexBuffers["noiseCoordinates2"] = source.createVertexBuffer("noiseCoordinates2", offset, 3);
  65496. offset += 3;
  65497. }
  65498. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  65499. this._engine.bindArrayBuffer(null);
  65500. return vao;
  65501. };
  65502. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  65503. var renderVertexBuffers = {};
  65504. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  65505. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  65506. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  65507. renderVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3, this._attributesStrideSize, true);
  65508. var offset = 12;
  65509. if (!this._colorGradientsTexture) {
  65510. renderVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true);
  65511. offset += 4;
  65512. }
  65513. if (this.billboardMode === BABYLON.ParticleSystem.BILLBOARDMODE_STRETCHED) {
  65514. renderVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3, this._attributesStrideSize, true);
  65515. }
  65516. offset += 3; // Direction
  65517. if (!this._isBillboardBased) {
  65518. renderVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true);
  65519. offset += 3;
  65520. }
  65521. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1, this._attributesStrideSize, true);
  65522. if (this._angularSpeedGradientsTexture) {
  65523. offset++;
  65524. }
  65525. else {
  65526. offset += 2;
  65527. }
  65528. if (this._isAnimationSheetEnabled) {
  65529. renderVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1, this._attributesStrideSize, true);
  65530. offset += 1;
  65531. if (this.spriteRandomStartCell) {
  65532. renderVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1, this._attributesStrideSize, true);
  65533. offset += 1;
  65534. }
  65535. }
  65536. if (this.noiseTexture) {
  65537. renderVertexBuffers["noiseCoordinates1"] = source.createVertexBuffer("noiseCoordinates1", offset, 3, this._attributesStrideSize, true);
  65538. offset += 3;
  65539. renderVertexBuffers["noiseCoordinates2"] = source.createVertexBuffer("noiseCoordinates2", offset, 3, this._attributesStrideSize, true);
  65540. offset += 3;
  65541. }
  65542. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  65543. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  65544. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  65545. this._engine.bindArrayBuffer(null);
  65546. return vao;
  65547. };
  65548. GPUParticleSystem.prototype._initialize = function (force) {
  65549. if (force === void 0) { force = false; }
  65550. if (this._buffer0 && !force) {
  65551. return;
  65552. }
  65553. var engine = this._scene.getEngine();
  65554. var data = new Array();
  65555. if (!this.isBillboardBased) {
  65556. this._attributesStrideSize += 3;
  65557. }
  65558. if (this._colorGradientsTexture) {
  65559. this._attributesStrideSize -= 4;
  65560. }
  65561. if (this._angularSpeedGradientsTexture) {
  65562. this._attributesStrideSize -= 1;
  65563. }
  65564. if (this._isAnimationSheetEnabled) {
  65565. this._attributesStrideSize += 1;
  65566. if (this.spriteRandomStartCell) {
  65567. this._attributesStrideSize += 1;
  65568. }
  65569. }
  65570. if (this.noiseTexture) {
  65571. this._attributesStrideSize += 6;
  65572. }
  65573. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  65574. // position
  65575. data.push(0.0);
  65576. data.push(0.0);
  65577. data.push(0.0);
  65578. // Age and life
  65579. data.push(0.0); // create the particle as a dead one to create a new one at start
  65580. data.push(0.0);
  65581. // Seed
  65582. data.push(Math.random());
  65583. data.push(Math.random());
  65584. data.push(Math.random());
  65585. data.push(Math.random());
  65586. // Size
  65587. data.push(0.0);
  65588. data.push(0.0);
  65589. data.push(0.0);
  65590. if (!this._colorGradientsTexture) {
  65591. // color
  65592. data.push(0.0);
  65593. data.push(0.0);
  65594. data.push(0.0);
  65595. data.push(0.0);
  65596. }
  65597. // direction
  65598. data.push(0.0);
  65599. data.push(0.0);
  65600. data.push(0.0);
  65601. if (!this.isBillboardBased) {
  65602. // initialDirection
  65603. data.push(0.0);
  65604. data.push(0.0);
  65605. data.push(0.0);
  65606. }
  65607. // angle
  65608. data.push(0.0);
  65609. if (!this._angularSpeedGradientsTexture) {
  65610. data.push(0.0);
  65611. }
  65612. if (this._isAnimationSheetEnabled) {
  65613. data.push(0.0);
  65614. if (this.spriteRandomStartCell) {
  65615. data.push(0.0);
  65616. }
  65617. }
  65618. if (this.noiseTexture) { // Random coordinates for reading into noise texture
  65619. data.push(Math.random());
  65620. data.push(Math.random());
  65621. data.push(Math.random());
  65622. data.push(Math.random());
  65623. data.push(Math.random());
  65624. data.push(Math.random());
  65625. }
  65626. }
  65627. // Sprite data
  65628. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  65629. -0.5, 0.5, 0, 1,
  65630. -0.5, -0.5, 0, 0,
  65631. 0.5, -0.5, 1, 0]);
  65632. // Buffers
  65633. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  65634. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  65635. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  65636. // Update VAO
  65637. this._updateVAO = [];
  65638. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  65639. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  65640. // Render VAO
  65641. this._renderVAO = [];
  65642. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  65643. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  65644. // Links
  65645. this._sourceBuffer = this._buffer0;
  65646. this._targetBuffer = this._buffer1;
  65647. };
  65648. /** @hidden */
  65649. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  65650. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  65651. if (this._isBillboardBased) {
  65652. defines += "\n#define BILLBOARD";
  65653. }
  65654. if (this._colorGradientsTexture) {
  65655. defines += "\n#define COLORGRADIENTS";
  65656. }
  65657. if (this._sizeGradientsTexture) {
  65658. defines += "\n#define SIZEGRADIENTS";
  65659. }
  65660. if (this._angularSpeedGradientsTexture) {
  65661. defines += "\n#define ANGULARSPEEDGRADIENTS";
  65662. }
  65663. if (this._velocityGradientsTexture) {
  65664. defines += "\n#define VELOCITYGRADIENTS";
  65665. }
  65666. if (this._limitVelocityGradientsTexture) {
  65667. defines += "\n#define LIMITVELOCITYGRADIENTS";
  65668. }
  65669. if (this._dragGradientsTexture) {
  65670. defines += "\n#define DRAGGRADIENTS";
  65671. }
  65672. if (this.isAnimationSheetEnabled) {
  65673. defines += "\n#define ANIMATESHEET";
  65674. if (this.spriteRandomStartCell) {
  65675. defines += "\n#define ANIMATESHEETRANDOMSTART";
  65676. }
  65677. }
  65678. if (this.noiseTexture) {
  65679. defines += "\n#define NOISE";
  65680. }
  65681. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  65682. return;
  65683. }
  65684. this._updateEffectOptions.transformFeedbackVaryings = ["outPosition", "outAge", "outLife", "outSeed", "outSize"];
  65685. if (!this._colorGradientsTexture) {
  65686. this._updateEffectOptions.transformFeedbackVaryings.push("outColor");
  65687. }
  65688. this._updateEffectOptions.transformFeedbackVaryings.push("outDirection");
  65689. if (!this._isBillboardBased) {
  65690. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection");
  65691. }
  65692. this._updateEffectOptions.transformFeedbackVaryings.push("outAngle");
  65693. if (this.isAnimationSheetEnabled) {
  65694. this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex");
  65695. if (this.spriteRandomStartCell) {
  65696. this._updateEffectOptions.transformFeedbackVaryings.push("outCellStartOffset");
  65697. }
  65698. }
  65699. if (this.noiseTexture) {
  65700. this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates1");
  65701. this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates2");
  65702. }
  65703. this._updateEffectOptions.defines = defines;
  65704. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  65705. };
  65706. /** @hidden */
  65707. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  65708. var defines = "";
  65709. if (this._scene.clipPlane) {
  65710. defines = "\n#define CLIPPLANE";
  65711. }
  65712. if (this._scene.clipPlane2) {
  65713. defines = "\n#define CLIPPLANE2";
  65714. }
  65715. if (this._scene.clipPlane3) {
  65716. defines = "\n#define CLIPPLANE3";
  65717. }
  65718. if (this._scene.clipPlane4) {
  65719. defines = "\n#define CLIPPLANE4";
  65720. }
  65721. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_MULTIPLY) {
  65722. defines = "\n#define BLENDMULTIPLYMODE";
  65723. }
  65724. if (this._isBillboardBased) {
  65725. defines += "\n#define BILLBOARD";
  65726. switch (this.billboardMode) {
  65727. case BABYLON.ParticleSystem.BILLBOARDMODE_Y:
  65728. defines += "\n#define BILLBOARDY";
  65729. break;
  65730. case BABYLON.ParticleSystem.BILLBOARDMODE_STRETCHED:
  65731. defines += "\n#define BILLBOARDSTRETCHED";
  65732. break;
  65733. case BABYLON.ParticleSystem.BILLBOARDMODE_ALL:
  65734. default:
  65735. break;
  65736. }
  65737. }
  65738. if (this._colorGradientsTexture) {
  65739. defines += "\n#define COLORGRADIENTS";
  65740. }
  65741. if (this.isAnimationSheetEnabled) {
  65742. defines += "\n#define ANIMATESHEET";
  65743. }
  65744. if (this._imageProcessingConfiguration) {
  65745. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  65746. defines += "\n" + this._imageProcessingConfigurationDefines.toString();
  65747. }
  65748. if (this._renderEffect && this._renderEffect.defines === defines) {
  65749. return;
  65750. }
  65751. var uniforms = ["view", "projection", "colorDead", "invView", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "sheetInfos", "translationPivot", "eyePosition"];
  65752. var samplers = ["textureSampler", "colorGradientSampler"];
  65753. if (BABYLON.ImageProcessingConfiguration) {
  65754. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._imageProcessingConfigurationDefines);
  65755. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  65756. }
  65757. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "direction", "initialDirection", "angle", "cellIndex"], uniforms, samplers, this._scene.getEngine(), defines);
  65758. };
  65759. /**
  65760. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  65761. * @param preWarm defines if we are in the pre-warmimg phase
  65762. */
  65763. GPUParticleSystem.prototype.animate = function (preWarm) {
  65764. if (preWarm === void 0) { preWarm = false; }
  65765. this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  65766. this._actualFrame += this._timeDelta;
  65767. if (!this._stopped) {
  65768. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  65769. this.stop();
  65770. }
  65771. }
  65772. };
  65773. GPUParticleSystem.prototype._createFactorGradientTexture = function (factorGradients, textureName) {
  65774. var texture = this[textureName];
  65775. if (!factorGradients || !factorGradients.length || texture) {
  65776. return;
  65777. }
  65778. var data = new Float32Array(this._rawTextureWidth);
  65779. for (var x = 0; x < this._rawTextureWidth; x++) {
  65780. var ratio = x / this._rawTextureWidth;
  65781. BABYLON.Tools.GetCurrentGradient(ratio, factorGradients, function (currentGradient, nextGradient, scale) {
  65782. data[x] = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  65783. });
  65784. }
  65785. this[textureName] = BABYLON.RawTexture.CreateRTexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  65786. };
  65787. GPUParticleSystem.prototype._createSizeGradientTexture = function () {
  65788. this._createFactorGradientTexture(this._sizeGradients, "_sizeGradientsTexture");
  65789. };
  65790. GPUParticleSystem.prototype._createAngularSpeedGradientTexture = function () {
  65791. this._createFactorGradientTexture(this._angularSpeedGradients, "_angularSpeedGradientsTexture");
  65792. };
  65793. GPUParticleSystem.prototype._createVelocityGradientTexture = function () {
  65794. this._createFactorGradientTexture(this._velocityGradients, "_velocityGradientsTexture");
  65795. };
  65796. GPUParticleSystem.prototype._createLimitVelocityGradientTexture = function () {
  65797. this._createFactorGradientTexture(this._limitVelocityGradients, "_limitVelocityGradientsTexture");
  65798. };
  65799. GPUParticleSystem.prototype._createDragGradientTexture = function () {
  65800. this._createFactorGradientTexture(this._dragGradients, "_dragGradientsTexture");
  65801. };
  65802. GPUParticleSystem.prototype._createColorGradientTexture = function () {
  65803. if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {
  65804. return;
  65805. }
  65806. var data = new Uint8Array(this._rawTextureWidth * 4);
  65807. var tmpColor = BABYLON.Tmp.Color4[0];
  65808. for (var x = 0; x < this._rawTextureWidth; x++) {
  65809. var ratio = x / this._rawTextureWidth;
  65810. BABYLON.Tools.GetCurrentGradient(ratio, this._colorGradients, function (currentGradient, nextGradient, scale) {
  65811. BABYLON.Color4.LerpToRef(currentGradient.color1, nextGradient.color1, scale, tmpColor);
  65812. data[x * 4] = tmpColor.r * 255;
  65813. data[x * 4 + 1] = tmpColor.g * 255;
  65814. data[x * 4 + 2] = tmpColor.b * 255;
  65815. data[x * 4 + 3] = tmpColor.a * 255;
  65816. });
  65817. }
  65818. this._colorGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  65819. };
  65820. /**
  65821. * Renders the particle system in its current state
  65822. * @param preWarm defines if the system should only update the particles but not render them
  65823. * @returns the current number of particles
  65824. */
  65825. GPUParticleSystem.prototype.render = function (preWarm) {
  65826. if (preWarm === void 0) { preWarm = false; }
  65827. if (!this._started) {
  65828. return 0;
  65829. }
  65830. this._createColorGradientTexture();
  65831. this._createSizeGradientTexture();
  65832. this._createAngularSpeedGradientTexture();
  65833. this._createVelocityGradientTexture();
  65834. this._createLimitVelocityGradientTexture();
  65835. this._createDragGradientTexture();
  65836. this._recreateUpdateEffect();
  65837. this._recreateRenderEffect();
  65838. if (!this.isReady()) {
  65839. return 0;
  65840. }
  65841. if (!preWarm) {
  65842. if (!this._preWarmDone && this.preWarmCycles) {
  65843. for (var index = 0; index < this.preWarmCycles; index++) {
  65844. this.animate(true);
  65845. this.render(true);
  65846. }
  65847. this._preWarmDone = true;
  65848. }
  65849. if (this._currentRenderId === this._scene.getRenderId()) {
  65850. return 0;
  65851. }
  65852. this._currentRenderId = this._scene.getRenderId();
  65853. }
  65854. // Get everything ready to render
  65855. this._initialize();
  65856. this._accumulatedCount += this.emitRate * this._timeDelta;
  65857. if (this._accumulatedCount > 1) {
  65858. var intPart = this._accumulatedCount | 0;
  65859. this._accumulatedCount -= intPart;
  65860. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + intPart);
  65861. }
  65862. if (!this._currentActiveCount) {
  65863. return 0;
  65864. }
  65865. // Enable update effect
  65866. this._engine.enableEffect(this._updateEffect);
  65867. this._engine.setState(false);
  65868. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  65869. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  65870. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  65871. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  65872. this._updateEffect.setTexture("randomSampler2", this._randomTexture2);
  65873. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  65874. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  65875. if (!this._colorGradientsTexture) {
  65876. this._updateEffect.setDirectColor4("color1", this.color1);
  65877. this._updateEffect.setDirectColor4("color2", this.color2);
  65878. }
  65879. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  65880. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  65881. this._updateEffect.setFloat4("angleRange", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);
  65882. this._updateEffect.setVector3("gravity", this.gravity);
  65883. if (this._sizeGradientsTexture) {
  65884. this._updateEffect.setTexture("sizeGradientSampler", this._sizeGradientsTexture);
  65885. }
  65886. if (this._angularSpeedGradientsTexture) {
  65887. this._updateEffect.setTexture("angularSpeedGradientSampler", this._angularSpeedGradientsTexture);
  65888. }
  65889. if (this._velocityGradientsTexture) {
  65890. this._updateEffect.setTexture("velocityGradientSampler", this._velocityGradientsTexture);
  65891. }
  65892. if (this._limitVelocityGradientsTexture) {
  65893. this._updateEffect.setTexture("limitVelocityGradientSampler", this._limitVelocityGradientsTexture);
  65894. this._updateEffect.setFloat("limitVelocityDamping", this.limitVelocityDamping);
  65895. }
  65896. if (this._dragGradientsTexture) {
  65897. this._updateEffect.setTexture("dragGradientSampler", this._dragGradientsTexture);
  65898. }
  65899. if (this.particleEmitterType) {
  65900. this.particleEmitterType.applyToShader(this._updateEffect);
  65901. }
  65902. if (this._isAnimationSheetEnabled) {
  65903. this._updateEffect.setFloat3("cellInfos", this.startSpriteCellID, this.endSpriteCellID, this.spriteCellChangeSpeed);
  65904. }
  65905. if (this.noiseTexture) {
  65906. this._updateEffect.setTexture("noiseSampler", this.noiseTexture);
  65907. this._updateEffect.setVector3("noiseStrength", this.noiseStrength);
  65908. }
  65909. var emitterWM;
  65910. if (this.emitter.position) {
  65911. var emitterMesh = this.emitter;
  65912. emitterWM = emitterMesh.getWorldMatrix();
  65913. }
  65914. else {
  65915. var emitterPosition = this.emitter;
  65916. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  65917. }
  65918. this._updateEffect.setMatrix("emitterWM", emitterWM);
  65919. // Bind source VAO
  65920. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  65921. // Update
  65922. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  65923. this._engine.setRasterizerState(false);
  65924. this._engine.beginTransformFeedback(true);
  65925. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  65926. this._engine.endTransformFeedback();
  65927. this._engine.setRasterizerState(true);
  65928. this._engine.bindTransformFeedbackBuffer(null);
  65929. if (!preWarm) {
  65930. // Enable render effect
  65931. this._engine.enableEffect(this._renderEffect);
  65932. var viewMatrix = this._scene.getViewMatrix();
  65933. this._renderEffect.setMatrix("view", viewMatrix);
  65934. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  65935. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  65936. this._renderEffect.setVector2("translationPivot", this.translationPivot);
  65937. if (this._colorGradientsTexture) {
  65938. this._renderEffect.setTexture("colorGradientSampler", this._colorGradientsTexture);
  65939. }
  65940. else {
  65941. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  65942. }
  65943. if (this._isAnimationSheetEnabled && this.particleTexture) {
  65944. var baseSize = this.particleTexture.getBaseSize();
  65945. this._renderEffect.setFloat3("sheetInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  65946. }
  65947. if (this._isBillboardBased) {
  65948. var camera = this._scene.activeCamera;
  65949. this._renderEffect.setVector3("eyePosition", camera.globalPosition);
  65950. }
  65951. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  65952. var invView = viewMatrix.clone();
  65953. invView.invert();
  65954. this._renderEffect.setMatrix("invView", invView);
  65955. BABYLON.MaterialHelper.BindClipPlane(this._renderEffect, this._scene);
  65956. }
  65957. // image processing
  65958. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  65959. this._imageProcessingConfiguration.bind(this._renderEffect);
  65960. }
  65961. // Draw order
  65962. switch (this.blendMode) {
  65963. case BABYLON.ParticleSystem.BLENDMODE_ADD:
  65964. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  65965. break;
  65966. case BABYLON.ParticleSystem.BLENDMODE_ONEONE:
  65967. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  65968. break;
  65969. case BABYLON.ParticleSystem.BLENDMODE_STANDARD:
  65970. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  65971. break;
  65972. case BABYLON.ParticleSystem.BLENDMODE_MULTIPLY:
  65973. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_MULTIPLY);
  65974. break;
  65975. }
  65976. if (this.forceDepthWrite) {
  65977. this._engine.setDepthWrite(true);
  65978. }
  65979. // Bind source VAO
  65980. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  65981. // Render
  65982. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  65983. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  65984. }
  65985. // Switch VAOs
  65986. this._targetIndex++;
  65987. if (this._targetIndex === 2) {
  65988. this._targetIndex = 0;
  65989. }
  65990. // Switch buffers
  65991. var tmpBuffer = this._sourceBuffer;
  65992. this._sourceBuffer = this._targetBuffer;
  65993. this._targetBuffer = tmpBuffer;
  65994. return this._currentActiveCount;
  65995. };
  65996. /**
  65997. * Rebuilds the particle system
  65998. */
  65999. GPUParticleSystem.prototype.rebuild = function () {
  66000. this._initialize(true);
  66001. };
  66002. GPUParticleSystem.prototype._releaseBuffers = function () {
  66003. if (this._buffer0) {
  66004. this._buffer0.dispose();
  66005. this._buffer0 = null;
  66006. }
  66007. if (this._buffer1) {
  66008. this._buffer1.dispose();
  66009. this._buffer1 = null;
  66010. }
  66011. if (this._spriteBuffer) {
  66012. this._spriteBuffer.dispose();
  66013. this._spriteBuffer = null;
  66014. }
  66015. };
  66016. GPUParticleSystem.prototype._releaseVAOs = function () {
  66017. if (!this._updateVAO) {
  66018. return;
  66019. }
  66020. for (var index = 0; index < this._updateVAO.length; index++) {
  66021. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  66022. }
  66023. this._updateVAO = [];
  66024. for (var index = 0; index < this._renderVAO.length; index++) {
  66025. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  66026. }
  66027. this._renderVAO = [];
  66028. };
  66029. /**
  66030. * Disposes the particle system and free the associated resources
  66031. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  66032. */
  66033. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  66034. if (disposeTexture === void 0) { disposeTexture = true; }
  66035. var index = this._scene.particleSystems.indexOf(this);
  66036. if (index > -1) {
  66037. this._scene.particleSystems.splice(index, 1);
  66038. }
  66039. this._releaseBuffers();
  66040. this._releaseVAOs();
  66041. if (this._colorGradientsTexture) {
  66042. this._colorGradientsTexture.dispose();
  66043. this._colorGradientsTexture = null;
  66044. }
  66045. if (this._sizeGradientsTexture) {
  66046. this._sizeGradientsTexture.dispose();
  66047. this._sizeGradientsTexture = null;
  66048. }
  66049. if (this._angularSpeedGradientsTexture) {
  66050. this._angularSpeedGradientsTexture.dispose();
  66051. this._angularSpeedGradientsTexture = null;
  66052. }
  66053. if (this._velocityGradientsTexture) {
  66054. this._velocityGradientsTexture.dispose();
  66055. this._velocityGradientsTexture = null;
  66056. }
  66057. if (this._limitVelocityGradientsTexture) {
  66058. this._limitVelocityGradientsTexture.dispose();
  66059. this._limitVelocityGradientsTexture = null;
  66060. }
  66061. if (this._dragGradientsTexture) {
  66062. this._dragGradientsTexture.dispose();
  66063. this._dragGradientsTexture = null;
  66064. }
  66065. if (this._randomTexture) {
  66066. this._randomTexture.dispose();
  66067. this._randomTexture = null;
  66068. }
  66069. if (this._randomTexture2) {
  66070. this._randomTexture2.dispose();
  66071. this._randomTexture2 = null;
  66072. }
  66073. if (disposeTexture && this.particleTexture) {
  66074. this.particleTexture.dispose();
  66075. this.particleTexture = null;
  66076. }
  66077. if (disposeTexture && this.noiseTexture) {
  66078. this.noiseTexture.dispose();
  66079. this.noiseTexture = null;
  66080. }
  66081. // Callback
  66082. this.onDisposeObservable.notifyObservers(this);
  66083. this.onDisposeObservable.clear();
  66084. };
  66085. /**
  66086. * Clones the particle system.
  66087. * @param name The name of the cloned object
  66088. * @param newEmitter The new emitter to use
  66089. * @returns the cloned particle system
  66090. */
  66091. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  66092. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  66093. BABYLON.Tools.DeepCopy(this, result);
  66094. if (newEmitter === undefined) {
  66095. newEmitter = this.emitter;
  66096. }
  66097. result.emitter = newEmitter;
  66098. if (this.particleTexture) {
  66099. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  66100. }
  66101. return result;
  66102. };
  66103. /**
  66104. * Serializes the particle system to a JSON object.
  66105. * @returns the JSON object
  66106. */
  66107. GPUParticleSystem.prototype.serialize = function () {
  66108. var serializationObject = {};
  66109. BABYLON.ParticleSystem._Serialize(serializationObject, this);
  66110. serializationObject.activeParticleCount = this.activeParticleCount;
  66111. return serializationObject;
  66112. };
  66113. /**
  66114. * Parses a JSON object to create a GPU particle system.
  66115. * @param parsedParticleSystem The JSON object to parse
  66116. * @param scene The scene to create the particle system in
  66117. * @param rootUrl The root url to use to load external dependencies like texture
  66118. * @param doNotStart Ignore the preventAutoStart attribute and does not start
  66119. * @returns the parsed GPU particle system
  66120. */
  66121. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl, doNotStart) {
  66122. if (doNotStart === void 0) { doNotStart = false; }
  66123. var name = parsedParticleSystem.name;
  66124. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  66125. if (parsedParticleSystem.activeParticleCount) {
  66126. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  66127. }
  66128. BABYLON.ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  66129. // Auto start
  66130. if (parsedParticleSystem.preventAutoStart) {
  66131. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  66132. }
  66133. if (!doNotStart && !particleSystem.preventAutoStart) {
  66134. particleSystem.start();
  66135. }
  66136. return particleSystem;
  66137. };
  66138. return GPUParticleSystem;
  66139. }(BABYLON.BaseParticleSystem));
  66140. BABYLON.GPUParticleSystem = GPUParticleSystem;
  66141. })(BABYLON || (BABYLON = {}));
  66142. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  66143. var BABYLON;
  66144. (function (BABYLON) {
  66145. /**
  66146. * Represents one particle of a solid particle system.
  66147. */
  66148. var SolidParticle = /** @class */ (function () {
  66149. /**
  66150. * Creates a Solid Particle object.
  66151. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  66152. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  66153. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  66154. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  66155. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  66156. * @param shapeId (integer) is the model shape identifier in the SPS.
  66157. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  66158. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  66159. */
  66160. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  66161. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  66162. /**
  66163. * particle global index
  66164. */
  66165. this.idx = 0;
  66166. /**
  66167. * The color of the particle
  66168. */
  66169. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  66170. /**
  66171. * The world space position of the particle.
  66172. */
  66173. this.position = BABYLON.Vector3.Zero();
  66174. /**
  66175. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  66176. */
  66177. this.rotation = BABYLON.Vector3.Zero();
  66178. /**
  66179. * The scaling of the particle.
  66180. */
  66181. this.scaling = BABYLON.Vector3.One();
  66182. /**
  66183. * The uvs of the particle.
  66184. */
  66185. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  66186. /**
  66187. * The current speed of the particle.
  66188. */
  66189. this.velocity = BABYLON.Vector3.Zero();
  66190. /**
  66191. * The pivot point in the particle local space.
  66192. */
  66193. this.pivot = BABYLON.Vector3.Zero();
  66194. /**
  66195. * Must the particle be translated from its pivot point in its local space ?
  66196. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  66197. * Default : false
  66198. */
  66199. this.translateFromPivot = false;
  66200. /**
  66201. * Is the particle active or not ?
  66202. */
  66203. this.alive = true;
  66204. /**
  66205. * Is the particle visible or not ?
  66206. */
  66207. this.isVisible = true;
  66208. /**
  66209. * Index of this particle in the global "positions" array (Internal use)
  66210. * @hidden
  66211. */
  66212. this._pos = 0;
  66213. /**
  66214. * @hidden Index of this particle in the global "indices" array (Internal use)
  66215. */
  66216. this._ind = 0;
  66217. /**
  66218. * ModelShape id of this particle
  66219. */
  66220. this.shapeId = 0;
  66221. /**
  66222. * Index of the particle in its shape id (Internal use)
  66223. */
  66224. this.idxInShape = 0;
  66225. /**
  66226. * @hidden Still set as invisible in order to skip useless computations (Internal use)
  66227. */
  66228. this._stillInvisible = false;
  66229. /**
  66230. * @hidden Last computed particle rotation matrix
  66231. */
  66232. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  66233. /**
  66234. * Parent particle Id, if any.
  66235. * Default null.
  66236. */
  66237. this.parentId = null;
  66238. /**
  66239. * @hidden Internal global position in the SPS.
  66240. */
  66241. this._globalPosition = BABYLON.Vector3.Zero();
  66242. this.idx = particleIndex;
  66243. this._pos = positionIndex;
  66244. this._ind = indiceIndex;
  66245. this._model = model;
  66246. this.shapeId = shapeId;
  66247. this.idxInShape = idxInShape;
  66248. this._sps = sps;
  66249. if (modelBoundingInfo) {
  66250. this._modelBoundingInfo = modelBoundingInfo;
  66251. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  66252. }
  66253. }
  66254. Object.defineProperty(SolidParticle.prototype, "scale", {
  66255. /**
  66256. * Legacy support, changed scale to scaling
  66257. */
  66258. get: function () {
  66259. return this.scaling;
  66260. },
  66261. /**
  66262. * Legacy support, changed scale to scaling
  66263. */
  66264. set: function (scale) {
  66265. this.scaling = scale;
  66266. },
  66267. enumerable: true,
  66268. configurable: true
  66269. });
  66270. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  66271. /**
  66272. * Legacy support, changed quaternion to rotationQuaternion
  66273. */
  66274. get: function () {
  66275. return this.rotationQuaternion;
  66276. },
  66277. /**
  66278. * Legacy support, changed quaternion to rotationQuaternion
  66279. */
  66280. set: function (q) {
  66281. this.rotationQuaternion = q;
  66282. },
  66283. enumerable: true,
  66284. configurable: true
  66285. });
  66286. /**
  66287. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  66288. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  66289. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  66290. * @returns true if it intersects
  66291. */
  66292. SolidParticle.prototype.intersectsMesh = function (target) {
  66293. if (!this._boundingInfo || !target._boundingInfo) {
  66294. return false;
  66295. }
  66296. if (this._sps._bSphereOnly) {
  66297. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  66298. }
  66299. return this._boundingInfo.intersects(target._boundingInfo, false);
  66300. };
  66301. return SolidParticle;
  66302. }());
  66303. BABYLON.SolidParticle = SolidParticle;
  66304. /**
  66305. * Represents the shape of the model used by one particle of a solid particle system.
  66306. * SPS internal tool, don't use it manually.
  66307. */
  66308. var ModelShape = /** @class */ (function () {
  66309. /**
  66310. * 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.
  66311. * SPS internal tool, don't use it manually.
  66312. * @hidden
  66313. */
  66314. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  66315. /**
  66316. * length of the shape in the model indices array (internal use)
  66317. * @hidden
  66318. */
  66319. this._indicesLength = 0;
  66320. this.shapeID = id;
  66321. this._shape = shape;
  66322. this._indicesLength = indicesLength;
  66323. this._shapeUV = shapeUV;
  66324. this._positionFunction = posFunction;
  66325. this._vertexFunction = vtxFunction;
  66326. }
  66327. return ModelShape;
  66328. }());
  66329. BABYLON.ModelShape = ModelShape;
  66330. /**
  66331. * Represents a Depth Sorted Particle in the solid particle system.
  66332. */
  66333. var DepthSortedParticle = /** @class */ (function () {
  66334. function DepthSortedParticle() {
  66335. /**
  66336. * Index of the particle in the "indices" array
  66337. */
  66338. this.ind = 0;
  66339. /**
  66340. * Length of the particle shape in the "indices" array
  66341. */
  66342. this.indicesLength = 0;
  66343. /**
  66344. * Squared distance from the particle to the camera
  66345. */
  66346. this.sqDistance = 0.0;
  66347. }
  66348. return DepthSortedParticle;
  66349. }());
  66350. BABYLON.DepthSortedParticle = DepthSortedParticle;
  66351. })(BABYLON || (BABYLON = {}));
  66352. //# sourceMappingURL=babylon.solidParticle.js.map
  66353. var BABYLON;
  66354. (function (BABYLON) {
  66355. /**
  66356. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  66357. *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.
  66358. * The SPS is also a particle system. It provides some methods to manage the particles.
  66359. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  66360. *
  66361. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  66362. */
  66363. var SolidParticleSystem = /** @class */ (function () {
  66364. /**
  66365. * Creates a SPS (Solid Particle System) object.
  66366. * @param name (String) is the SPS name, this will be the underlying mesh name.
  66367. * @param scene (Scene) is the scene in which the SPS is added.
  66368. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  66369. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  66370. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  66371. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  66372. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  66373. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  66374. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  66375. */
  66376. function SolidParticleSystem(name, scene, options) {
  66377. /**
  66378. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  66379. * Example : var p = SPS.particles[i];
  66380. */
  66381. this.particles = new Array();
  66382. /**
  66383. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  66384. */
  66385. this.nbParticles = 0;
  66386. /**
  66387. * If the particles must ever face the camera (default false). Useful for planar particles.
  66388. */
  66389. this.billboard = false;
  66390. /**
  66391. * Recompute normals when adding a shape
  66392. */
  66393. this.recomputeNormals = true;
  66394. /**
  66395. * This a counter ofr your own usage. It's not set by any SPS functions.
  66396. */
  66397. this.counter = 0;
  66398. /**
  66399. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  66400. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  66401. */
  66402. this.vars = {};
  66403. /**
  66404. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  66405. * @hidden
  66406. */
  66407. this._bSphereOnly = false;
  66408. /**
  66409. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  66410. * @hidden
  66411. */
  66412. this._bSphereRadiusFactor = 1.0;
  66413. this._positions = new Array();
  66414. this._indices = new Array();
  66415. this._normals = new Array();
  66416. this._colors = new Array();
  66417. this._uvs = new Array();
  66418. this._index = 0; // indices index
  66419. this._updatable = true;
  66420. this._pickable = false;
  66421. this._isVisibilityBoxLocked = false;
  66422. this._alwaysVisible = false;
  66423. this._depthSort = false;
  66424. this._shapeCounter = 0;
  66425. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  66426. this._color = new BABYLON.Color4(0, 0, 0, 0);
  66427. this._computeParticleColor = true;
  66428. this._computeParticleTexture = true;
  66429. this._computeParticleRotation = true;
  66430. this._computeParticleVertex = false;
  66431. this._computeBoundingBox = false;
  66432. this._depthSortParticles = true;
  66433. this._cam_axisZ = BABYLON.Vector3.Zero();
  66434. this._cam_axisY = BABYLON.Vector3.Zero();
  66435. this._cam_axisX = BABYLON.Vector3.Zero();
  66436. this._axisZ = BABYLON.Axis.Z;
  66437. this._camDir = BABYLON.Vector3.Zero();
  66438. this._camInvertedPosition = BABYLON.Vector3.Zero();
  66439. this._rotMatrix = new BABYLON.Matrix();
  66440. this._invertMatrix = new BABYLON.Matrix();
  66441. this._rotated = BABYLON.Vector3.Zero();
  66442. this._quaternion = new BABYLON.Quaternion();
  66443. this._vertex = BABYLON.Vector3.Zero();
  66444. this._normal = BABYLON.Vector3.Zero();
  66445. this._yaw = 0.0;
  66446. this._pitch = 0.0;
  66447. this._roll = 0.0;
  66448. this._halfroll = 0.0;
  66449. this._halfpitch = 0.0;
  66450. this._halfyaw = 0.0;
  66451. this._sinRoll = 0.0;
  66452. this._cosRoll = 0.0;
  66453. this._sinPitch = 0.0;
  66454. this._cosPitch = 0.0;
  66455. this._sinYaw = 0.0;
  66456. this._cosYaw = 0.0;
  66457. this._mustUnrotateFixedNormals = false;
  66458. this._minimum = BABYLON.Vector3.Zero();
  66459. this._maximum = BABYLON.Vector3.Zero();
  66460. this._minBbox = BABYLON.Vector3.Zero();
  66461. this._maxBbox = BABYLON.Vector3.Zero();
  66462. this._particlesIntersect = false;
  66463. this._depthSortFunction = function (p1, p2) {
  66464. return (p2.sqDistance - p1.sqDistance);
  66465. };
  66466. this._needs32Bits = false;
  66467. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  66468. this._scaledPivot = BABYLON.Vector3.Zero();
  66469. this._particleHasParent = false;
  66470. this.name = name;
  66471. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  66472. this._camera = scene.activeCamera;
  66473. this._pickable = options ? options.isPickable : false;
  66474. this._depthSort = options ? options.enableDepthSort : false;
  66475. this._particlesIntersect = options ? options.particleIntersection : false;
  66476. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  66477. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  66478. if (options && options.updatable !== undefined) {
  66479. this._updatable = options.updatable;
  66480. }
  66481. else {
  66482. this._updatable = true;
  66483. }
  66484. if (this._pickable) {
  66485. this.pickedParticles = [];
  66486. }
  66487. if (this._depthSort) {
  66488. this.depthSortedParticles = [];
  66489. }
  66490. }
  66491. /**
  66492. * Builds the SPS underlying mesh. Returns a standard Mesh.
  66493. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  66494. * @returns the created mesh
  66495. */
  66496. SolidParticleSystem.prototype.buildMesh = function () {
  66497. if (this.nbParticles === 0) {
  66498. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  66499. this.addShape(triangle, 1);
  66500. triangle.dispose();
  66501. }
  66502. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  66503. this._positions32 = new Float32Array(this._positions);
  66504. this._uvs32 = new Float32Array(this._uvs);
  66505. this._colors32 = new Float32Array(this._colors);
  66506. if (this.recomputeNormals) {
  66507. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  66508. }
  66509. this._normals32 = new Float32Array(this._normals);
  66510. this._fixedNormal32 = new Float32Array(this._normals);
  66511. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  66512. this._unrotateFixedNormals();
  66513. }
  66514. var vertexData = new BABYLON.VertexData();
  66515. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  66516. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  66517. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  66518. if (this._uvs32.length > 0) {
  66519. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  66520. }
  66521. if (this._colors32.length > 0) {
  66522. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  66523. }
  66524. var mesh = new BABYLON.Mesh(this.name, this._scene);
  66525. vertexData.applyToMesh(mesh, this._updatable);
  66526. this.mesh = mesh;
  66527. this.mesh.isPickable = this._pickable;
  66528. // free memory
  66529. if (!this._depthSort) {
  66530. this._indices = null;
  66531. }
  66532. this._positions = null;
  66533. this._normals = null;
  66534. this._uvs = null;
  66535. this._colors = null;
  66536. if (!this._updatable) {
  66537. this.particles.length = 0;
  66538. }
  66539. return mesh;
  66540. };
  66541. /**
  66542. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  66543. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  66544. * Thus the particles generated from `digest()` have their property `position` set yet.
  66545. * @param mesh ( Mesh ) is the mesh to be digested
  66546. * @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
  66547. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  66548. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  66549. * @returns the current SPS
  66550. */
  66551. SolidParticleSystem.prototype.digest = function (mesh, options) {
  66552. var size = (options && options.facetNb) || 1;
  66553. var number = (options && options.number) || 0;
  66554. var delta = (options && options.delta) || 0;
  66555. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  66556. var meshInd = mesh.getIndices();
  66557. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  66558. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  66559. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  66560. var f = 0; // facet counter
  66561. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  66562. // compute size from number
  66563. if (number) {
  66564. number = (number > totalFacets) ? totalFacets : number;
  66565. size = Math.round(totalFacets / number);
  66566. delta = 0;
  66567. }
  66568. else {
  66569. size = (size > totalFacets) ? totalFacets : size;
  66570. }
  66571. var facetPos = []; // submesh positions
  66572. var facetInd = []; // submesh indices
  66573. var facetUV = []; // submesh UV
  66574. var facetCol = []; // submesh colors
  66575. var barycenter = BABYLON.Vector3.Zero();
  66576. var sizeO = size;
  66577. while (f < totalFacets) {
  66578. size = sizeO + Math.floor((1 + delta) * Math.random());
  66579. if (f > totalFacets - size) {
  66580. size = totalFacets - f;
  66581. }
  66582. // reset temp arrays
  66583. facetPos.length = 0;
  66584. facetInd.length = 0;
  66585. facetUV.length = 0;
  66586. facetCol.length = 0;
  66587. // iterate over "size" facets
  66588. var fi = 0;
  66589. for (var j = f * 3; j < (f + size) * 3; j++) {
  66590. facetInd.push(fi);
  66591. var i = meshInd[j];
  66592. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  66593. if (meshUV) {
  66594. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  66595. }
  66596. if (meshCol) {
  66597. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  66598. }
  66599. fi++;
  66600. }
  66601. // create a model shape for each single particle
  66602. var idx = this.nbParticles;
  66603. var shape = this._posToShape(facetPos);
  66604. var shapeUV = this._uvsToShapeUV(facetUV);
  66605. // compute the barycenter of the shape
  66606. var v;
  66607. for (v = 0; v < shape.length; v++) {
  66608. barycenter.addInPlace(shape[v]);
  66609. }
  66610. barycenter.scaleInPlace(1 / shape.length);
  66611. // shift the shape from its barycenter to the origin
  66612. for (v = 0; v < shape.length; v++) {
  66613. shape[v].subtractInPlace(barycenter);
  66614. }
  66615. var bInfo;
  66616. if (this._particlesIntersect) {
  66617. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  66618. }
  66619. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  66620. // add the particle in the SPS
  66621. var currentPos = this._positions.length;
  66622. var currentInd = this._indices.length;
  66623. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  66624. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  66625. // initialize the particle position
  66626. this.particles[this.nbParticles].position.addInPlace(barycenter);
  66627. this._index += shape.length;
  66628. idx++;
  66629. this.nbParticles++;
  66630. this._shapeCounter++;
  66631. f += size;
  66632. }
  66633. return this;
  66634. };
  66635. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  66636. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  66637. var index = 0;
  66638. var idx = 0;
  66639. for (var p = 0; p < this.particles.length; p++) {
  66640. this._particle = this.particles[p];
  66641. this._shape = this._particle._model._shape;
  66642. if (this._particle.rotationQuaternion) {
  66643. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  66644. }
  66645. else {
  66646. this._yaw = this._particle.rotation.y;
  66647. this._pitch = this._particle.rotation.x;
  66648. this._roll = this._particle.rotation.z;
  66649. this._quaternionRotationYPR();
  66650. }
  66651. this._quaternionToRotationMatrix();
  66652. this._rotMatrix.invertToRef(this._invertMatrix);
  66653. for (var pt = 0; pt < this._shape.length; pt++) {
  66654. idx = index + pt * 3;
  66655. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  66656. this._fixedNormal32[idx] = this._normal.x;
  66657. this._fixedNormal32[idx + 1] = this._normal.y;
  66658. this._fixedNormal32[idx + 2] = this._normal.z;
  66659. }
  66660. index = idx + 3;
  66661. }
  66662. };
  66663. //reset copy
  66664. SolidParticleSystem.prototype._resetCopy = function () {
  66665. this._copy.position.x = 0;
  66666. this._copy.position.y = 0;
  66667. this._copy.position.z = 0;
  66668. this._copy.rotation.x = 0;
  66669. this._copy.rotation.y = 0;
  66670. this._copy.rotation.z = 0;
  66671. this._copy.rotationQuaternion = null;
  66672. this._copy.scaling.x = 1.0;
  66673. this._copy.scaling.y = 1.0;
  66674. this._copy.scaling.z = 1.0;
  66675. this._copy.uvs.x = 0;
  66676. this._copy.uvs.y = 0;
  66677. this._copy.uvs.z = 1.0;
  66678. this._copy.uvs.w = 1.0;
  66679. this._copy.color = null;
  66680. this._copy.translateFromPivot = false;
  66681. };
  66682. // _meshBuilder : inserts the shape model in the global SPS mesh
  66683. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  66684. var i;
  66685. var u = 0;
  66686. var c = 0;
  66687. var n = 0;
  66688. this._resetCopy();
  66689. if (options && options.positionFunction) { // call to custom positionFunction
  66690. options.positionFunction(this._copy, idx, idxInShape);
  66691. this._mustUnrotateFixedNormals = true;
  66692. }
  66693. if (this._copy.rotationQuaternion) {
  66694. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  66695. }
  66696. else {
  66697. this._yaw = this._copy.rotation.y;
  66698. this._pitch = this._copy.rotation.x;
  66699. this._roll = this._copy.rotation.z;
  66700. this._quaternionRotationYPR();
  66701. }
  66702. this._quaternionToRotationMatrix();
  66703. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  66704. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  66705. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  66706. if (this._copy.translateFromPivot) {
  66707. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  66708. }
  66709. else {
  66710. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  66711. }
  66712. for (i = 0; i < shape.length; i++) {
  66713. this._vertex.x = shape[i].x;
  66714. this._vertex.y = shape[i].y;
  66715. this._vertex.z = shape[i].z;
  66716. if (options && options.vertexFunction) {
  66717. options.vertexFunction(this._copy, this._vertex, i);
  66718. }
  66719. this._vertex.x *= this._copy.scaling.x;
  66720. this._vertex.y *= this._copy.scaling.y;
  66721. this._vertex.z *= this._copy.scaling.z;
  66722. this._vertex.x -= this._scaledPivot.x;
  66723. this._vertex.y -= this._scaledPivot.y;
  66724. this._vertex.z -= this._scaledPivot.z;
  66725. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  66726. this._rotated.addInPlace(this._pivotBackTranslation);
  66727. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  66728. if (meshUV) {
  66729. 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);
  66730. u += 2;
  66731. }
  66732. if (this._copy.color) {
  66733. this._color = this._copy.color;
  66734. }
  66735. else if (meshCol && meshCol[c] !== undefined) {
  66736. this._color.r = meshCol[c];
  66737. this._color.g = meshCol[c + 1];
  66738. this._color.b = meshCol[c + 2];
  66739. this._color.a = meshCol[c + 3];
  66740. }
  66741. else {
  66742. this._color.r = 1.0;
  66743. this._color.g = 1.0;
  66744. this._color.b = 1.0;
  66745. this._color.a = 1.0;
  66746. }
  66747. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  66748. c += 4;
  66749. if (!this.recomputeNormals && meshNor) {
  66750. this._normal.x = meshNor[n];
  66751. this._normal.y = meshNor[n + 1];
  66752. this._normal.z = meshNor[n + 2];
  66753. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  66754. normals.push(this._normal.x, this._normal.y, this._normal.z);
  66755. n += 3;
  66756. }
  66757. }
  66758. for (i = 0; i < meshInd.length; i++) {
  66759. var current_ind = p + meshInd[i];
  66760. indices.push(current_ind);
  66761. if (current_ind > 65535) {
  66762. this._needs32Bits = true;
  66763. }
  66764. }
  66765. if (this._pickable) {
  66766. var nbfaces = meshInd.length / 3;
  66767. for (i = 0; i < nbfaces; i++) {
  66768. this.pickedParticles.push({ idx: idx, faceId: i });
  66769. }
  66770. }
  66771. if (this._depthSort) {
  66772. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  66773. }
  66774. return this._copy;
  66775. };
  66776. // returns a shape array from positions array
  66777. SolidParticleSystem.prototype._posToShape = function (positions) {
  66778. var shape = [];
  66779. for (var i = 0; i < positions.length; i += 3) {
  66780. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  66781. }
  66782. return shape;
  66783. };
  66784. // returns a shapeUV array from a Vector4 uvs
  66785. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  66786. var shapeUV = [];
  66787. if (uvs) {
  66788. for (var i = 0; i < uvs.length; i++)
  66789. shapeUV.push(uvs[i]);
  66790. }
  66791. return shapeUV;
  66792. };
  66793. // adds a new particle object in the particles array
  66794. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  66795. if (bInfo === void 0) { bInfo = null; }
  66796. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  66797. this.particles.push(sp);
  66798. return sp;
  66799. };
  66800. /**
  66801. * Adds some particles to the SPS from the model shape. Returns the shape id.
  66802. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  66803. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  66804. * @param nb (positive integer) the number of particles to be created from this model
  66805. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  66806. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  66807. * @returns the number of shapes in the system
  66808. */
  66809. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  66810. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  66811. var meshInd = mesh.getIndices();
  66812. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  66813. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  66814. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  66815. var bbInfo;
  66816. if (this._particlesIntersect) {
  66817. bbInfo = mesh.getBoundingInfo();
  66818. }
  66819. var shape = this._posToShape(meshPos);
  66820. var shapeUV = this._uvsToShapeUV(meshUV);
  66821. var posfunc = options ? options.positionFunction : null;
  66822. var vtxfunc = options ? options.vertexFunction : null;
  66823. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  66824. // particles
  66825. var sp;
  66826. var currentCopy;
  66827. var idx = this.nbParticles;
  66828. for (var i = 0; i < nb; i++) {
  66829. var currentPos = this._positions.length;
  66830. var currentInd = this._indices.length;
  66831. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  66832. if (this._updatable) {
  66833. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  66834. sp.position.copyFrom(currentCopy.position);
  66835. sp.rotation.copyFrom(currentCopy.rotation);
  66836. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  66837. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  66838. }
  66839. if (currentCopy.color && sp.color) {
  66840. sp.color.copyFrom(currentCopy.color);
  66841. }
  66842. sp.scaling.copyFrom(currentCopy.scaling);
  66843. sp.uvs.copyFrom(currentCopy.uvs);
  66844. }
  66845. this._index += shape.length;
  66846. idx++;
  66847. }
  66848. this.nbParticles += nb;
  66849. this._shapeCounter++;
  66850. return this._shapeCounter - 1;
  66851. };
  66852. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  66853. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  66854. this._resetCopy();
  66855. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  66856. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  66857. }
  66858. if (this._copy.rotationQuaternion) {
  66859. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  66860. }
  66861. else {
  66862. this._yaw = this._copy.rotation.y;
  66863. this._pitch = this._copy.rotation.x;
  66864. this._roll = this._copy.rotation.z;
  66865. this._quaternionRotationYPR();
  66866. }
  66867. this._quaternionToRotationMatrix();
  66868. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  66869. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  66870. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  66871. if (this._copy.translateFromPivot) {
  66872. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  66873. }
  66874. else {
  66875. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  66876. }
  66877. this._shape = particle._model._shape;
  66878. for (var pt = 0; pt < this._shape.length; pt++) {
  66879. this._vertex.x = this._shape[pt].x;
  66880. this._vertex.y = this._shape[pt].y;
  66881. this._vertex.z = this._shape[pt].z;
  66882. if (particle._model._vertexFunction) {
  66883. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  66884. }
  66885. this._vertex.x *= this._copy.scaling.x;
  66886. this._vertex.y *= this._copy.scaling.y;
  66887. this._vertex.z *= this._copy.scaling.z;
  66888. this._vertex.x -= this._scaledPivot.x;
  66889. this._vertex.y -= this._scaledPivot.y;
  66890. this._vertex.z -= this._scaledPivot.z;
  66891. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  66892. this._rotated.addInPlace(this._pivotBackTranslation);
  66893. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  66894. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  66895. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  66896. }
  66897. particle.position.x = 0.0;
  66898. particle.position.y = 0.0;
  66899. particle.position.z = 0.0;
  66900. particle.rotation.x = 0.0;
  66901. particle.rotation.y = 0.0;
  66902. particle.rotation.z = 0.0;
  66903. particle.rotationQuaternion = null;
  66904. particle.scaling.x = 1.0;
  66905. particle.scaling.y = 1.0;
  66906. particle.scaling.z = 1.0;
  66907. particle.uvs.x = 0.0;
  66908. particle.uvs.y = 0.0;
  66909. particle.uvs.z = 1.0;
  66910. particle.uvs.w = 1.0;
  66911. particle.pivot.x = 0.0;
  66912. particle.pivot.y = 0.0;
  66913. particle.pivot.z = 0.0;
  66914. particle.translateFromPivot = false;
  66915. particle.parentId = null;
  66916. };
  66917. /**
  66918. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  66919. * @returns the SPS.
  66920. */
  66921. SolidParticleSystem.prototype.rebuildMesh = function () {
  66922. for (var p = 0; p < this.particles.length; p++) {
  66923. this._rebuildParticle(this.particles[p]);
  66924. }
  66925. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  66926. return this;
  66927. };
  66928. /**
  66929. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  66930. * This method calls `updateParticle()` for each particle of the SPS.
  66931. * For an animated SPS, it is usually called within the render loop.
  66932. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  66933. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  66934. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  66935. * @returns the SPS.
  66936. */
  66937. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  66938. if (start === void 0) { start = 0; }
  66939. if (end === void 0) { end = this.nbParticles - 1; }
  66940. if (update === void 0) { update = true; }
  66941. if (!this._updatable) {
  66942. return this;
  66943. }
  66944. // custom beforeUpdate
  66945. this.beforeUpdateParticles(start, end, update);
  66946. this._cam_axisX.x = 1.0;
  66947. this._cam_axisX.y = 0.0;
  66948. this._cam_axisX.z = 0.0;
  66949. this._cam_axisY.x = 0.0;
  66950. this._cam_axisY.y = 1.0;
  66951. this._cam_axisY.z = 0.0;
  66952. this._cam_axisZ.x = 0.0;
  66953. this._cam_axisZ.y = 0.0;
  66954. this._cam_axisZ.z = 1.0;
  66955. // cases when the World Matrix is to be computed first
  66956. if (this.billboard || this._depthSort) {
  66957. this.mesh.computeWorldMatrix(true);
  66958. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  66959. }
  66960. // if the particles will always face the camera
  66961. if (this.billboard) {
  66962. // compute the camera position and un-rotate it by the current mesh rotation
  66963. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  66964. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  66965. this._cam_axisZ.normalize();
  66966. // same for camera up vector extracted from the cam view matrix
  66967. var view = this._camera.getViewMatrix(true);
  66968. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  66969. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  66970. this._cam_axisY.normalize();
  66971. this._cam_axisX.normalize();
  66972. }
  66973. // if depthSort, compute the camera global position in the mesh local system
  66974. if (this._depthSort) {
  66975. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  66976. }
  66977. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  66978. var idx = 0; // current position index in the global array positions32
  66979. var index = 0; // position start index in the global array positions32 of the current particle
  66980. var colidx = 0; // current color index in the global array colors32
  66981. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  66982. var uvidx = 0; // current uv index in the global array uvs32
  66983. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  66984. var pt = 0; // current index in the particle model shape
  66985. if (this.mesh.isFacetDataEnabled) {
  66986. this._computeBoundingBox = true;
  66987. }
  66988. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  66989. if (this._computeBoundingBox) {
  66990. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  66991. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  66992. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  66993. }
  66994. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  66995. if (this.mesh._boundingInfo) {
  66996. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  66997. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  66998. }
  66999. }
  67000. }
  67001. // particle loop
  67002. index = this.particles[start]._pos;
  67003. var vpos = (index / 3) | 0;
  67004. colorIndex = vpos * 4;
  67005. uvIndex = vpos * 2;
  67006. for (var p = start; p <= end; p++) {
  67007. this._particle = this.particles[p];
  67008. this._shape = this._particle._model._shape;
  67009. this._shapeUV = this._particle._model._shapeUV;
  67010. // call to custom user function to update the particle properties
  67011. this.updateParticle(this._particle);
  67012. // camera-particle distance for depth sorting
  67013. if (this._depthSort && this._depthSortParticles) {
  67014. var dsp = this.depthSortedParticles[p];
  67015. dsp.ind = this._particle._ind;
  67016. dsp.indicesLength = this._particle._model._indicesLength;
  67017. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  67018. }
  67019. // skip the computations for inactive or already invisible particles
  67020. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  67021. // increment indexes for the next particle
  67022. pt = this._shape.length;
  67023. index += pt * 3;
  67024. colorIndex += pt * 4;
  67025. uvIndex += pt * 2;
  67026. continue;
  67027. }
  67028. if (this._particle.isVisible) {
  67029. this._particle._stillInvisible = false; // un-mark permanent invisibility
  67030. this._particleHasParent = (this._particle.parentId !== null);
  67031. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  67032. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  67033. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  67034. // particle rotation matrix
  67035. if (this.billboard) {
  67036. this._particle.rotation.x = 0.0;
  67037. this._particle.rotation.y = 0.0;
  67038. }
  67039. if (this._computeParticleRotation || this.billboard) {
  67040. if (this._particle.rotationQuaternion) {
  67041. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  67042. }
  67043. else {
  67044. this._yaw = this._particle.rotation.y;
  67045. this._pitch = this._particle.rotation.x;
  67046. this._roll = this._particle.rotation.z;
  67047. this._quaternionRotationYPR();
  67048. }
  67049. this._quaternionToRotationMatrix();
  67050. }
  67051. if (this._particleHasParent) {
  67052. this._parent = this.particles[this._particle.parentId];
  67053. 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];
  67054. 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];
  67055. 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];
  67056. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  67057. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  67058. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  67059. if (this._computeParticleRotation || this.billboard) {
  67060. 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];
  67061. 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];
  67062. 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];
  67063. 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];
  67064. 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];
  67065. 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];
  67066. 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];
  67067. 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];
  67068. 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];
  67069. }
  67070. }
  67071. else {
  67072. this._particle._globalPosition.x = this._particle.position.x;
  67073. this._particle._globalPosition.y = this._particle.position.y;
  67074. this._particle._globalPosition.z = this._particle.position.z;
  67075. if (this._computeParticleRotation || this.billboard) {
  67076. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  67077. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  67078. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  67079. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  67080. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  67081. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  67082. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  67083. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  67084. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  67085. }
  67086. }
  67087. if (this._particle.translateFromPivot) {
  67088. this._pivotBackTranslation.x = 0.0;
  67089. this._pivotBackTranslation.y = 0.0;
  67090. this._pivotBackTranslation.z = 0.0;
  67091. }
  67092. else {
  67093. this._pivotBackTranslation.x = this._scaledPivot.x;
  67094. this._pivotBackTranslation.y = this._scaledPivot.y;
  67095. this._pivotBackTranslation.z = this._scaledPivot.z;
  67096. }
  67097. // particle vertex loop
  67098. for (pt = 0; pt < this._shape.length; pt++) {
  67099. idx = index + pt * 3;
  67100. colidx = colorIndex + pt * 4;
  67101. uvidx = uvIndex + pt * 2;
  67102. this._vertex.x = this._shape[pt].x;
  67103. this._vertex.y = this._shape[pt].y;
  67104. this._vertex.z = this._shape[pt].z;
  67105. if (this._computeParticleVertex) {
  67106. this.updateParticleVertex(this._particle, this._vertex, pt);
  67107. }
  67108. // positions
  67109. this._vertex.x *= this._particle.scaling.x;
  67110. this._vertex.y *= this._particle.scaling.y;
  67111. this._vertex.z *= this._particle.scaling.z;
  67112. this._vertex.x -= this._scaledPivot.x;
  67113. this._vertex.y -= this._scaledPivot.y;
  67114. this._vertex.z -= this._scaledPivot.z;
  67115. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  67116. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  67117. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  67118. this._rotated.x += this._pivotBackTranslation.x;
  67119. this._rotated.y += this._pivotBackTranslation.y;
  67120. this._rotated.z += this._pivotBackTranslation.z;
  67121. 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;
  67122. 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;
  67123. 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;
  67124. if (this._computeBoundingBox) {
  67125. if (this._positions32[idx] < this._minimum.x) {
  67126. this._minimum.x = this._positions32[idx];
  67127. }
  67128. if (this._positions32[idx] > this._maximum.x) {
  67129. this._maximum.x = this._positions32[idx];
  67130. }
  67131. if (this._positions32[idx + 1] < this._minimum.y) {
  67132. this._minimum.y = this._positions32[idx + 1];
  67133. }
  67134. if (this._positions32[idx + 1] > this._maximum.y) {
  67135. this._maximum.y = this._positions32[idx + 1];
  67136. }
  67137. if (this._positions32[idx + 2] < this._minimum.z) {
  67138. this._minimum.z = this._positions32[idx + 2];
  67139. }
  67140. if (this._positions32[idx + 2] > this._maximum.z) {
  67141. this._maximum.z = this._positions32[idx + 2];
  67142. }
  67143. }
  67144. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  67145. if (!this._computeParticleVertex) {
  67146. this._normal.x = this._fixedNormal32[idx];
  67147. this._normal.y = this._fixedNormal32[idx + 1];
  67148. this._normal.z = this._fixedNormal32[idx + 2];
  67149. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  67150. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  67151. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  67152. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  67153. 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;
  67154. 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;
  67155. }
  67156. if (this._computeParticleColor && this._particle.color) {
  67157. this._colors32[colidx] = this._particle.color.r;
  67158. this._colors32[colidx + 1] = this._particle.color.g;
  67159. this._colors32[colidx + 2] = this._particle.color.b;
  67160. this._colors32[colidx + 3] = this._particle.color.a;
  67161. }
  67162. if (this._computeParticleTexture) {
  67163. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  67164. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  67165. }
  67166. }
  67167. }
  67168. // particle just set invisible : scaled to zero and positioned at the origin
  67169. else {
  67170. this._particle._stillInvisible = true; // mark the particle as invisible
  67171. for (pt = 0; pt < this._shape.length; pt++) {
  67172. idx = index + pt * 3;
  67173. colidx = colorIndex + pt * 4;
  67174. uvidx = uvIndex + pt * 2;
  67175. this._positions32[idx] = 0.0;
  67176. this._positions32[idx + 1] = 0.0;
  67177. this._positions32[idx + 2] = 0.0;
  67178. this._normals32[idx] = 0.0;
  67179. this._normals32[idx + 1] = 0.0;
  67180. this._normals32[idx + 2] = 0.0;
  67181. if (this._computeParticleColor && this._particle.color) {
  67182. this._colors32[colidx] = this._particle.color.r;
  67183. this._colors32[colidx + 1] = this._particle.color.g;
  67184. this._colors32[colidx + 2] = this._particle.color.b;
  67185. this._colors32[colidx + 3] = this._particle.color.a;
  67186. }
  67187. if (this._computeParticleTexture) {
  67188. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  67189. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  67190. }
  67191. }
  67192. }
  67193. // if the particle intersections must be computed : update the bbInfo
  67194. if (this._particlesIntersect) {
  67195. var bInfo = this._particle._boundingInfo;
  67196. var bBox = bInfo.boundingBox;
  67197. var bSphere = bInfo.boundingSphere;
  67198. if (!this._bSphereOnly) {
  67199. // place, scale and rotate the particle bbox within the SPS local system, then update it
  67200. for (var b = 0; b < bBox.vectors.length; b++) {
  67201. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  67202. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  67203. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  67204. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  67205. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  67206. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  67207. 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;
  67208. 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;
  67209. 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;
  67210. }
  67211. bBox._update(this.mesh._worldMatrix);
  67212. }
  67213. // place and scale the particle bouding sphere in the SPS local system, then update it
  67214. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  67215. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  67216. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  67217. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  67218. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  67219. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  67220. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  67221. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  67222. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  67223. 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));
  67224. bSphere._update(this.mesh._worldMatrix);
  67225. }
  67226. // increment indexes for the next particle
  67227. index = idx + 3;
  67228. colorIndex = colidx + 4;
  67229. uvIndex = uvidx + 2;
  67230. }
  67231. // if the VBO must be updated
  67232. if (update) {
  67233. if (this._computeParticleColor) {
  67234. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  67235. }
  67236. if (this._computeParticleTexture) {
  67237. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  67238. }
  67239. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  67240. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  67241. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  67242. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  67243. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  67244. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  67245. for (var i = 0; i < this._normals32.length; i++) {
  67246. this._fixedNormal32[i] = this._normals32[i];
  67247. }
  67248. }
  67249. if (!this.mesh.areNormalsFrozen) {
  67250. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  67251. }
  67252. }
  67253. if (this._depthSort && this._depthSortParticles) {
  67254. this.depthSortedParticles.sort(this._depthSortFunction);
  67255. var dspl = this.depthSortedParticles.length;
  67256. var sorted = 0;
  67257. var lind = 0;
  67258. var sind = 0;
  67259. var sid = 0;
  67260. for (sorted = 0; sorted < dspl; sorted++) {
  67261. lind = this.depthSortedParticles[sorted].indicesLength;
  67262. sind = this.depthSortedParticles[sorted].ind;
  67263. for (var i = 0; i < lind; i++) {
  67264. this._indices32[sid] = this._indices[sind + i];
  67265. sid++;
  67266. }
  67267. }
  67268. this.mesh.updateIndices(this._indices32);
  67269. }
  67270. }
  67271. if (this._computeBoundingBox) {
  67272. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  67273. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  67274. }
  67275. this.afterUpdateParticles(start, end, update);
  67276. return this;
  67277. };
  67278. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  67279. this._halfroll = this._roll * 0.5;
  67280. this._halfpitch = this._pitch * 0.5;
  67281. this._halfyaw = this._yaw * 0.5;
  67282. this._sinRoll = Math.sin(this._halfroll);
  67283. this._cosRoll = Math.cos(this._halfroll);
  67284. this._sinPitch = Math.sin(this._halfpitch);
  67285. this._cosPitch = Math.cos(this._halfpitch);
  67286. this._sinYaw = Math.sin(this._halfyaw);
  67287. this._cosYaw = Math.cos(this._halfyaw);
  67288. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  67289. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  67290. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  67291. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  67292. };
  67293. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  67294. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  67295. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  67296. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  67297. this._rotMatrix.m[3] = 0;
  67298. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  67299. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  67300. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  67301. this._rotMatrix.m[7] = 0;
  67302. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  67303. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  67304. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  67305. this._rotMatrix.m[11] = 0;
  67306. this._rotMatrix.m[12] = 0;
  67307. this._rotMatrix.m[13] = 0;
  67308. this._rotMatrix.m[14] = 0;
  67309. this._rotMatrix.m[15] = 1.0;
  67310. };
  67311. /**
  67312. * Disposes the SPS.
  67313. */
  67314. SolidParticleSystem.prototype.dispose = function () {
  67315. this.mesh.dispose();
  67316. this.vars = null;
  67317. // drop references to internal big arrays for the GC
  67318. this._positions = null;
  67319. this._indices = null;
  67320. this._normals = null;
  67321. this._uvs = null;
  67322. this._colors = null;
  67323. this._indices32 = null;
  67324. this._positions32 = null;
  67325. this._normals32 = null;
  67326. this._fixedNormal32 = null;
  67327. this._uvs32 = null;
  67328. this._colors32 = null;
  67329. this.pickedParticles = null;
  67330. };
  67331. /**
  67332. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  67333. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  67334. * @returns the SPS.
  67335. */
  67336. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  67337. if (!this._isVisibilityBoxLocked) {
  67338. this.mesh.refreshBoundingInfo();
  67339. }
  67340. return this;
  67341. };
  67342. /**
  67343. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  67344. * @param size the size (float) of the visibility box
  67345. * note : this doesn't lock the SPS mesh bounding box.
  67346. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  67347. */
  67348. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  67349. var vis = size / 2;
  67350. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  67351. };
  67352. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  67353. /**
  67354. * Gets whether the SPS as always visible or not
  67355. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  67356. */
  67357. get: function () {
  67358. return this._alwaysVisible;
  67359. },
  67360. /**
  67361. * Sets the SPS as always visible or not
  67362. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  67363. */
  67364. set: function (val) {
  67365. this._alwaysVisible = val;
  67366. this.mesh.alwaysSelectAsActiveMesh = val;
  67367. },
  67368. enumerable: true,
  67369. configurable: true
  67370. });
  67371. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  67372. /**
  67373. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  67374. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  67375. */
  67376. get: function () {
  67377. return this._isVisibilityBoxLocked;
  67378. },
  67379. /**
  67380. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  67381. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  67382. */
  67383. set: function (val) {
  67384. this._isVisibilityBoxLocked = val;
  67385. var boundingInfo = this.mesh.getBoundingInfo();
  67386. boundingInfo.isLocked = val;
  67387. },
  67388. enumerable: true,
  67389. configurable: true
  67390. });
  67391. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  67392. /**
  67393. * Gets if `setParticles()` computes the particle rotations or not.
  67394. * Default value : true. The SPS is faster when it's set to false.
  67395. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  67396. */
  67397. get: function () {
  67398. return this._computeParticleRotation;
  67399. },
  67400. /**
  67401. * Tells to `setParticles()` to compute the particle rotations or not.
  67402. * Default value : true. The SPS is faster when it's set to false.
  67403. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  67404. */
  67405. set: function (val) {
  67406. this._computeParticleRotation = val;
  67407. },
  67408. enumerable: true,
  67409. configurable: true
  67410. });
  67411. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  67412. /**
  67413. * Gets if `setParticles()` computes the particle colors or not.
  67414. * Default value : true. The SPS is faster when it's set to false.
  67415. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  67416. */
  67417. get: function () {
  67418. return this._computeParticleColor;
  67419. },
  67420. /**
  67421. * Tells to `setParticles()` to compute the particle colors or not.
  67422. * Default value : true. The SPS is faster when it's set to false.
  67423. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  67424. */
  67425. set: function (val) {
  67426. this._computeParticleColor = val;
  67427. },
  67428. enumerable: true,
  67429. configurable: true
  67430. });
  67431. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  67432. /**
  67433. * Gets if `setParticles()` computes the particle textures or not.
  67434. * Default value : true. The SPS is faster when it's set to false.
  67435. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  67436. */
  67437. get: function () {
  67438. return this._computeParticleTexture;
  67439. },
  67440. set: function (val) {
  67441. this._computeParticleTexture = val;
  67442. },
  67443. enumerable: true,
  67444. configurable: true
  67445. });
  67446. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  67447. /**
  67448. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  67449. * Default value : false. The SPS is faster when it's set to false.
  67450. * Note : the particle custom vertex positions aren't stored values.
  67451. */
  67452. get: function () {
  67453. return this._computeParticleVertex;
  67454. },
  67455. /**
  67456. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  67457. * Default value : false. The SPS is faster when it's set to false.
  67458. * Note : the particle custom vertex positions aren't stored values.
  67459. */
  67460. set: function (val) {
  67461. this._computeParticleVertex = val;
  67462. },
  67463. enumerable: true,
  67464. configurable: true
  67465. });
  67466. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  67467. /**
  67468. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  67469. */
  67470. get: function () {
  67471. return this._computeBoundingBox;
  67472. },
  67473. /**
  67474. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  67475. */
  67476. set: function (val) {
  67477. this._computeBoundingBox = val;
  67478. },
  67479. enumerable: true,
  67480. configurable: true
  67481. });
  67482. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  67483. /**
  67484. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  67485. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  67486. * Default : `true`
  67487. */
  67488. get: function () {
  67489. return this._depthSortParticles;
  67490. },
  67491. /**
  67492. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  67493. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  67494. * Default : `true`
  67495. */
  67496. set: function (val) {
  67497. this._depthSortParticles = val;
  67498. },
  67499. enumerable: true,
  67500. configurable: true
  67501. });
  67502. // =======================================================================
  67503. // Particle behavior logic
  67504. // these following methods may be overwritten by the user to fit his needs
  67505. /**
  67506. * This function does nothing. It may be overwritten to set all the particle first values.
  67507. * The SPS doesn't call this function, you may have to call it by your own.
  67508. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  67509. */
  67510. SolidParticleSystem.prototype.initParticles = function () {
  67511. };
  67512. /**
  67513. * This function does nothing. It may be overwritten to recycle a particle.
  67514. * The SPS doesn't call this function, you may have to call it by your own.
  67515. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  67516. * @param particle The particle to recycle
  67517. * @returns the recycled particle
  67518. */
  67519. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  67520. return particle;
  67521. };
  67522. /**
  67523. * Updates a particle : this function should be overwritten by the user.
  67524. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  67525. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  67526. * @example : just set a particle position or velocity and recycle conditions
  67527. * @param particle The particle to update
  67528. * @returns the updated particle
  67529. */
  67530. SolidParticleSystem.prototype.updateParticle = function (particle) {
  67531. return particle;
  67532. };
  67533. /**
  67534. * Updates a vertex of a particle : it can be overwritten by the user.
  67535. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  67536. * @param particle the current particle
  67537. * @param vertex the current index of the current particle
  67538. * @param pt the index of the current vertex in the particle shape
  67539. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  67540. * @example : just set a vertex particle position
  67541. * @returns the updated vertex
  67542. */
  67543. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  67544. return vertex;
  67545. };
  67546. /**
  67547. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  67548. * This does nothing and may be overwritten by the user.
  67549. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  67550. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  67551. * @param update the boolean update value actually passed to setParticles()
  67552. */
  67553. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  67554. };
  67555. /**
  67556. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  67557. * This will be passed three parameters.
  67558. * This does nothing and may be overwritten by the user.
  67559. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  67560. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  67561. * @param update the boolean update value actually passed to setParticles()
  67562. */
  67563. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  67564. };
  67565. return SolidParticleSystem;
  67566. }());
  67567. BABYLON.SolidParticleSystem = SolidParticleSystem;
  67568. })(BABYLON || (BABYLON = {}));
  67569. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  67570. var BABYLON;
  67571. (function (BABYLON) {
  67572. /**
  67573. * Class containing static functions to help procedurally build meshes
  67574. */
  67575. var MeshBuilder = /** @class */ (function () {
  67576. function MeshBuilder() {
  67577. }
  67578. MeshBuilder.updateSideOrientation = function (orientation) {
  67579. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  67580. return BABYLON.Mesh.DOUBLESIDE;
  67581. }
  67582. if (orientation === undefined || orientation === null) {
  67583. return BABYLON.Mesh.FRONTSIDE;
  67584. }
  67585. return orientation;
  67586. };
  67587. /**
  67588. * Creates a box mesh
  67589. * * The parameter `size` sets the size (float) of each box side (default 1)
  67590. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value of `size`)
  67591. * * 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)
  67592. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  67593. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67594. * * 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
  67595. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67596. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  67597. * @param name defines the name of the mesh
  67598. * @param options defines the options used to create the mesh
  67599. * @param scene defines the hosting scene
  67600. * @returns the box mesh
  67601. */
  67602. MeshBuilder.CreateBox = function (name, options, scene) {
  67603. if (scene === void 0) { scene = null; }
  67604. var box = new BABYLON.Mesh(name, scene);
  67605. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67606. box._originalBuilderSideOrientation = options.sideOrientation;
  67607. var vertexData = BABYLON.VertexData.CreateBox(options);
  67608. vertexData.applyToMesh(box, options.updatable);
  67609. return box;
  67610. };
  67611. /**
  67612. * Creates a sphere mesh
  67613. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  67614. * * 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 of `diameter`)
  67615. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  67616. * * 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
  67617. * * 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)
  67618. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67619. * * 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
  67620. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67621. * @param name defines the name of the mesh
  67622. * @param options defines the options used to create the mesh
  67623. * @param scene defines the hosting scene
  67624. * @returns the sphere mesh
  67625. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  67626. */
  67627. MeshBuilder.CreateSphere = function (name, options, scene) {
  67628. var sphere = new BABYLON.Mesh(name, scene);
  67629. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67630. sphere._originalBuilderSideOrientation = options.sideOrientation;
  67631. var vertexData = BABYLON.VertexData.CreateSphere(options);
  67632. vertexData.applyToMesh(sphere, options.updatable);
  67633. return sphere;
  67634. };
  67635. /**
  67636. * Creates a plane polygonal mesh. By default, this is a disc
  67637. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  67638. * * 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
  67639. * * 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
  67640. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67641. * * 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
  67642. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67643. * @param name defines the name of the mesh
  67644. * @param options defines the options used to create the mesh
  67645. * @param scene defines the hosting scene
  67646. * @returns the plane polygonal mesh
  67647. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  67648. */
  67649. MeshBuilder.CreateDisc = function (name, options, scene) {
  67650. if (scene === void 0) { scene = null; }
  67651. var disc = new BABYLON.Mesh(name, scene);
  67652. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67653. disc._originalBuilderSideOrientation = options.sideOrientation;
  67654. var vertexData = BABYLON.VertexData.CreateDisc(options);
  67655. vertexData.applyToMesh(disc, options.updatable);
  67656. return disc;
  67657. };
  67658. /**
  67659. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  67660. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  67661. * * 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 of `radius`)
  67662. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  67663. * * 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
  67664. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67665. * * 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
  67666. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67667. * @param name defines the name of the mesh
  67668. * @param options defines the options used to create the mesh
  67669. * @param scene defines the hosting scene
  67670. * @returns the icosahedron mesh
  67671. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  67672. */
  67673. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  67674. var sphere = new BABYLON.Mesh(name, scene);
  67675. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67676. sphere._originalBuilderSideOrientation = options.sideOrientation;
  67677. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  67678. vertexData.applyToMesh(sphere, options.updatable);
  67679. return sphere;
  67680. };
  67681. ;
  67682. /**
  67683. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  67684. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  67685. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  67686. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  67687. * * 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
  67688. * * 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
  67689. * * 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
  67690. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67691. * * 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
  67692. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  67693. * * 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
  67694. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  67695. * * 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
  67696. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  67697. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67698. * @param name defines the name of the mesh
  67699. * @param options defines the options used to create the mesh
  67700. * @param scene defines the hosting scene
  67701. * @returns the ribbon mesh
  67702. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  67703. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  67704. */
  67705. MeshBuilder.CreateRibbon = function (name, options, scene) {
  67706. if (scene === void 0) { scene = null; }
  67707. var pathArray = options.pathArray;
  67708. var closeArray = options.closeArray;
  67709. var closePath = options.closePath;
  67710. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67711. var instance = options.instance;
  67712. var updatable = options.updatable;
  67713. if (instance) { // existing ribbon instance update
  67714. // positionFunction : ribbon case
  67715. // only pathArray and sideOrientation parameters are taken into account for positions update
  67716. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  67717. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  67718. var positionFunction = function (positions) {
  67719. var minlg = pathArray[0].length;
  67720. var mesh = instance;
  67721. var i = 0;
  67722. var ns = (mesh._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  67723. for (var si = 1; si <= ns; si++) {
  67724. for (var p = 0; p < pathArray.length; p++) {
  67725. var path = pathArray[p];
  67726. var l = path.length;
  67727. minlg = (minlg < l) ? minlg : l;
  67728. var j = 0;
  67729. while (j < minlg) {
  67730. positions[i] = path[j].x;
  67731. positions[i + 1] = path[j].y;
  67732. positions[i + 2] = path[j].z;
  67733. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  67734. BABYLON.Tmp.Vector3[0].x = path[j].x;
  67735. }
  67736. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  67737. BABYLON.Tmp.Vector3[1].x = path[j].x;
  67738. }
  67739. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  67740. BABYLON.Tmp.Vector3[0].y = path[j].y;
  67741. }
  67742. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  67743. BABYLON.Tmp.Vector3[1].y = path[j].y;
  67744. }
  67745. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  67746. BABYLON.Tmp.Vector3[0].z = path[j].z;
  67747. }
  67748. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  67749. BABYLON.Tmp.Vector3[1].z = path[j].z;
  67750. }
  67751. j++;
  67752. i += 3;
  67753. }
  67754. if (mesh._creationDataStorage && mesh._creationDataStorage.closePath) {
  67755. positions[i] = path[0].x;
  67756. positions[i + 1] = path[0].y;
  67757. positions[i + 2] = path[0].z;
  67758. i += 3;
  67759. }
  67760. }
  67761. }
  67762. };
  67763. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  67764. positionFunction(positions);
  67765. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[2], BABYLON.Tmp.Vector3[3]);
  67766. instance._boundingInfo.update(instance._worldMatrix);
  67767. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  67768. if (options.colors) {
  67769. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  67770. for (var c = 0; c < options.colors.length; c++) {
  67771. colors[c * 4] = options.colors[c].r;
  67772. colors[c * 4 + 1] = options.colors[c].g;
  67773. colors[c * 4 + 2] = options.colors[c].b;
  67774. colors[c * 4 + 3] = options.colors[c].a;
  67775. }
  67776. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  67777. }
  67778. if (options.uvs) {
  67779. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  67780. for (var i = 0; i < options.uvs.length; i++) {
  67781. uvs[i * 2] = options.uvs[i].x;
  67782. uvs[i * 2 + 1] = options.uvs[i].y;
  67783. }
  67784. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  67785. }
  67786. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  67787. var indices = instance.getIndices();
  67788. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  67789. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  67790. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  67791. if (instance._creationDataStorage && instance._creationDataStorage.closePath) {
  67792. var indexFirst = 0;
  67793. var indexLast = 0;
  67794. for (var p = 0; p < pathArray.length; p++) {
  67795. indexFirst = instance._creationDataStorage.idx[p] * 3;
  67796. if (p + 1 < pathArray.length) {
  67797. indexLast = (instance._creationDataStorage.idx[p + 1] - 1) * 3;
  67798. }
  67799. else {
  67800. indexLast = normals.length - 3;
  67801. }
  67802. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  67803. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  67804. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  67805. normals[indexLast] = normals[indexFirst];
  67806. normals[indexLast + 1] = normals[indexFirst + 1];
  67807. normals[indexLast + 2] = normals[indexFirst + 2];
  67808. }
  67809. }
  67810. if (!(instance.areNormalsFrozen)) {
  67811. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  67812. }
  67813. }
  67814. return instance;
  67815. }
  67816. else { // new ribbon creation
  67817. var ribbon = new BABYLON.Mesh(name, scene);
  67818. ribbon._originalBuilderSideOrientation = sideOrientation;
  67819. ribbon._creationDataStorage = new BABYLON._CreationDataStorage();
  67820. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  67821. if (closePath) {
  67822. ribbon._creationDataStorage.idx = vertexData._idx;
  67823. }
  67824. ribbon._creationDataStorage.closePath = closePath;
  67825. ribbon._creationDataStorage.closeArray = closeArray;
  67826. vertexData.applyToMesh(ribbon, updatable);
  67827. return ribbon;
  67828. }
  67829. };
  67830. /**
  67831. * Creates a cylinder or a cone mesh
  67832. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  67833. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  67834. * * 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.
  67835. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  67836. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  67837. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  67838. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  67839. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  67840. * * 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).
  67841. * * 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
  67842. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  67843. * * 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
  67844. * * 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.
  67845. * * If `enclose` is false, a ring surface is one element.
  67846. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  67847. * * 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
  67848. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67849. * * 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
  67850. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  67851. * @param name defines the name of the mesh
  67852. * @param options defines the options used to create the mesh
  67853. * @param scene defines the hosting scene
  67854. * @returns the cylinder mesh
  67855. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  67856. */
  67857. MeshBuilder.CreateCylinder = function (name, options, scene) {
  67858. var cylinder = new BABYLON.Mesh(name, scene);
  67859. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67860. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  67861. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  67862. vertexData.applyToMesh(cylinder, options.updatable);
  67863. return cylinder;
  67864. };
  67865. /**
  67866. * Creates a torus mesh
  67867. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  67868. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  67869. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  67870. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67871. * * 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
  67872. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  67873. * @param name defines the name of the mesh
  67874. * @param options defines the options used to create the mesh
  67875. * @param scene defines the hosting scene
  67876. * @returns the torus mesh
  67877. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  67878. */
  67879. MeshBuilder.CreateTorus = function (name, options, scene) {
  67880. var torus = new BABYLON.Mesh(name, scene);
  67881. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67882. torus._originalBuilderSideOrientation = options.sideOrientation;
  67883. var vertexData = BABYLON.VertexData.CreateTorus(options);
  67884. vertexData.applyToMesh(torus, options.updatable);
  67885. return torus;
  67886. };
  67887. /**
  67888. * Creates a torus knot mesh
  67889. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  67890. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  67891. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  67892. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  67893. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67894. * * 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
  67895. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  67896. * @param name defines the name of the mesh
  67897. * @param options defines the options used to create the mesh
  67898. * @param scene defines the hosting scene
  67899. * @returns the torus knot mesh
  67900. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  67901. */
  67902. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  67903. var torusKnot = new BABYLON.Mesh(name, scene);
  67904. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67905. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  67906. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  67907. vertexData.applyToMesh(torusKnot, options.updatable);
  67908. return torusKnot;
  67909. };
  67910. /**
  67911. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  67912. * * 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
  67913. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  67914. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  67915. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  67916. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  67917. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  67918. * * 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
  67919. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  67920. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67921. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  67922. * @param name defines the name of the new line system
  67923. * @param options defines the options used to create the line system
  67924. * @param scene defines the hosting scene
  67925. * @returns a new line system mesh
  67926. */
  67927. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  67928. var instance = options.instance;
  67929. var lines = options.lines;
  67930. var colors = options.colors;
  67931. if (instance) { // lines update
  67932. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  67933. var vertexColor;
  67934. var lineColors;
  67935. if (colors) {
  67936. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  67937. }
  67938. var i = 0;
  67939. var c = 0;
  67940. for (var l = 0; l < lines.length; l++) {
  67941. var points = lines[l];
  67942. for (var p = 0; p < points.length; p++) {
  67943. positions[i] = points[p].x;
  67944. positions[i + 1] = points[p].y;
  67945. positions[i + 2] = points[p].z;
  67946. if (colors && vertexColor) {
  67947. lineColors = colors[l];
  67948. vertexColor[c] = lineColors[p].r;
  67949. vertexColor[c + 1] = lineColors[p].g;
  67950. vertexColor[c + 2] = lineColors[p].b;
  67951. vertexColor[c + 3] = lineColors[p].a;
  67952. c += 4;
  67953. }
  67954. i += 3;
  67955. }
  67956. }
  67957. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  67958. if (colors && vertexColor) {
  67959. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  67960. }
  67961. return instance;
  67962. }
  67963. // line system creation
  67964. var useVertexColor = (colors) ? true : false;
  67965. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  67966. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  67967. vertexData.applyToMesh(lineSystem, options.updatable);
  67968. return lineSystem;
  67969. };
  67970. /**
  67971. * Creates a line mesh
  67972. * 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
  67973. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  67974. * * The parameter `points` is an array successive Vector3
  67975. * * 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
  67976. * * The optional parameter `colors` is an array of successive Color4, one per line point
  67977. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  67978. * * When updating an instance, remember that only point positions can change, not the number of points
  67979. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67980. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  67981. * @param name defines the name of the new line system
  67982. * @param options defines the options used to create the line system
  67983. * @param scene defines the hosting scene
  67984. * @returns a new line mesh
  67985. */
  67986. MeshBuilder.CreateLines = function (name, options, scene) {
  67987. if (scene === void 0) { scene = null; }
  67988. var colors = (options.colors) ? [options.colors] : null;
  67989. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  67990. return lines;
  67991. };
  67992. /**
  67993. * Creates a dashed line mesh
  67994. * * 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
  67995. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  67996. * * The parameter `points` is an array successive Vector3
  67997. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  67998. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  67999. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  68000. * * 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
  68001. * * When updating an instance, remember that only point positions can change, not the number of points
  68002. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  68003. * @param name defines the name of the mesh
  68004. * @param options defines the options used to create the mesh
  68005. * @param scene defines the hosting scene
  68006. * @returns the dashed line mesh
  68007. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  68008. */
  68009. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  68010. if (scene === void 0) { scene = null; }
  68011. var points = options.points;
  68012. var instance = options.instance;
  68013. var gapSize = options.gapSize || 1;
  68014. var dashSize = options.dashSize || 3;
  68015. if (instance) { // dashed lines update
  68016. var positionFunction = function (positions) {
  68017. var curvect = BABYLON.Vector3.Zero();
  68018. var nbSeg = positions.length / 6;
  68019. var lg = 0;
  68020. var nb = 0;
  68021. var shft = 0;
  68022. var dashshft = 0;
  68023. var curshft = 0;
  68024. var p = 0;
  68025. var i = 0;
  68026. var j = 0;
  68027. for (i = 0; i < points.length - 1; i++) {
  68028. points[i + 1].subtractToRef(points[i], curvect);
  68029. lg += curvect.length();
  68030. }
  68031. shft = lg / nbSeg;
  68032. var dashSize = instance._creationDataStorage.dashSize;
  68033. var gapSize = instance._creationDataStorage.gapSize;
  68034. dashshft = dashSize * shft / (dashSize + gapSize);
  68035. for (i = 0; i < points.length - 1; i++) {
  68036. points[i + 1].subtractToRef(points[i], curvect);
  68037. nb = Math.floor(curvect.length() / shft);
  68038. curvect.normalize();
  68039. j = 0;
  68040. while (j < nb && p < positions.length) {
  68041. curshft = shft * j;
  68042. positions[p] = points[i].x + curshft * curvect.x;
  68043. positions[p + 1] = points[i].y + curshft * curvect.y;
  68044. positions[p + 2] = points[i].z + curshft * curvect.z;
  68045. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  68046. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  68047. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  68048. p += 6;
  68049. j++;
  68050. }
  68051. }
  68052. while (p < positions.length) {
  68053. positions[p] = points[i].x;
  68054. positions[p + 1] = points[i].y;
  68055. positions[p + 2] = points[i].z;
  68056. p += 3;
  68057. }
  68058. };
  68059. instance.updateMeshPositions(positionFunction, false);
  68060. return instance;
  68061. }
  68062. // dashed lines creation
  68063. var dashedLines = new BABYLON.LinesMesh(name, scene);
  68064. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  68065. vertexData.applyToMesh(dashedLines, options.updatable);
  68066. dashedLines._creationDataStorage = new BABYLON._CreationDataStorage();
  68067. dashedLines._creationDataStorage.dashSize = dashSize;
  68068. dashedLines._creationDataStorage.gapSize = gapSize;
  68069. return dashedLines;
  68070. };
  68071. /**
  68072. * 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.
  68073. * * 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.
  68074. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  68075. * * 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.
  68076. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  68077. * * 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
  68078. * * 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
  68079. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  68080. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  68081. * * 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
  68082. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  68083. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  68084. * @param name defines the name of the mesh
  68085. * @param options defines the options used to create the mesh
  68086. * @param scene defines the hosting scene
  68087. * @returns the extruded shape mesh
  68088. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  68089. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  68090. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  68091. */
  68092. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  68093. if (scene === void 0) { scene = null; }
  68094. var path = options.path;
  68095. var shape = options.shape;
  68096. var scale = options.scale || 1;
  68097. var rotation = options.rotation || 0;
  68098. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  68099. var updatable = options.updatable;
  68100. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  68101. var instance = options.instance || null;
  68102. var invertUV = options.invertUV || false;
  68103. 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);
  68104. };
  68105. /**
  68106. * Creates an custom extruded shape mesh.
  68107. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  68108. * * 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.
  68109. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  68110. * * 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
  68111. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  68112. * * 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
  68113. * * It must returns a float value that will be the scale value applied to the shape on each path point
  68114. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  68115. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  68116. * * 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
  68117. * * 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
  68118. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  68119. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  68120. * * 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
  68121. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  68122. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  68123. * @param name defines the name of the mesh
  68124. * @param options defines the options used to create the mesh
  68125. * @param scene defines the hosting scene
  68126. * @returns the custom extruded shape mesh
  68127. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  68128. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  68129. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  68130. */
  68131. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  68132. var path = options.path;
  68133. var shape = options.shape;
  68134. var scaleFunction = options.scaleFunction || (function () { return 1; });
  68135. var rotationFunction = options.rotationFunction || (function () { return 0; });
  68136. var ribbonCloseArray = options.ribbonCloseArray || false;
  68137. var ribbonClosePath = options.ribbonClosePath || false;
  68138. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  68139. var updatable = options.updatable;
  68140. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  68141. var instance = options.instance;
  68142. var invertUV = options.invertUV || false;
  68143. 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);
  68144. };
  68145. /**
  68146. * Creates lathe mesh.
  68147. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  68148. * * 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
  68149. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  68150. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  68151. * * The parameter `clip` (positive integer, default 0) is the number of sides to not create without effecting the general shape of the sides
  68152. * * 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
  68153. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  68154. * * 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
  68155. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  68156. * * 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
  68157. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  68158. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  68159. * @param name defines the name of the mesh
  68160. * @param options defines the options used to create the mesh
  68161. * @param scene defines the hosting scene
  68162. * @returns the lathe mesh
  68163. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  68164. */
  68165. MeshBuilder.CreateLathe = function (name, options, scene) {
  68166. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  68167. var closed = (options.closed === undefined) ? true : options.closed;
  68168. var shape = options.shape;
  68169. var radius = options.radius || 1;
  68170. var tessellation = options.tessellation || 64;
  68171. var clip = options.clip || 0;
  68172. var updatable = options.updatable;
  68173. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  68174. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  68175. var pi2 = Math.PI * 2;
  68176. var paths = new Array();
  68177. var invertUV = options.invertUV || false;
  68178. var i = 0;
  68179. var p = 0;
  68180. var step = pi2 / tessellation * arc;
  68181. var rotated;
  68182. var path = new Array();
  68183. for (i = 0; i <= tessellation - clip; i++) {
  68184. var path = [];
  68185. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  68186. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  68187. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  68188. }
  68189. for (p = 0; p < shape.length; p++) {
  68190. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  68191. path.push(rotated);
  68192. }
  68193. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  68194. 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));
  68195. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  68196. }
  68197. paths.push(path);
  68198. }
  68199. // lathe ribbon
  68200. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  68201. return lathe;
  68202. };
  68203. /**
  68204. * Creates a plane mesh
  68205. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  68206. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value of `size`)
  68207. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  68208. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  68209. * * 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
  68210. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  68211. * @param name defines the name of the mesh
  68212. * @param options defines the options used to create the mesh
  68213. * @param scene defines the hosting scene
  68214. * @returns the plane mesh
  68215. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  68216. */
  68217. MeshBuilder.CreatePlane = function (name, options, scene) {
  68218. var plane = new BABYLON.Mesh(name, scene);
  68219. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  68220. plane._originalBuilderSideOrientation = options.sideOrientation;
  68221. var vertexData = BABYLON.VertexData.CreatePlane(options);
  68222. vertexData.applyToMesh(plane, options.updatable);
  68223. if (options.sourcePlane) {
  68224. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  68225. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  68226. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  68227. if (vectorProduct.lengthSquared() > BABYLON.Epsilon) {
  68228. plane.rotate(vectorProduct, product);
  68229. }
  68230. }
  68231. return plane;
  68232. };
  68233. /**
  68234. * Creates a ground mesh
  68235. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  68236. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  68237. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  68238. * @param name defines the name of the mesh
  68239. * @param options defines the options used to create the mesh
  68240. * @param scene defines the hosting scene
  68241. * @returns the ground mesh
  68242. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  68243. */
  68244. MeshBuilder.CreateGround = function (name, options, scene) {
  68245. var ground = new BABYLON.GroundMesh(name, scene);
  68246. ground._setReady(false);
  68247. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  68248. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  68249. ground._width = options.width || 1;
  68250. ground._height = options.height || 1;
  68251. ground._maxX = ground._width / 2;
  68252. ground._maxZ = ground._height / 2;
  68253. ground._minX = -ground._maxX;
  68254. ground._minZ = -ground._maxZ;
  68255. var vertexData = BABYLON.VertexData.CreateGround(options);
  68256. vertexData.applyToMesh(ground, options.updatable);
  68257. ground._setReady(true);
  68258. return ground;
  68259. };
  68260. /**
  68261. * Creates a tiled ground mesh
  68262. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  68263. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  68264. * * 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
  68265. * * 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
  68266. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  68267. * @param name defines the name of the mesh
  68268. * @param options defines the options used to create the mesh
  68269. * @param scene defines the hosting scene
  68270. * @returns the tiled ground mesh
  68271. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  68272. */
  68273. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  68274. var tiledGround = new BABYLON.Mesh(name, scene);
  68275. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  68276. vertexData.applyToMesh(tiledGround, options.updatable);
  68277. return tiledGround;
  68278. };
  68279. /**
  68280. * Creates a ground mesh from a height map
  68281. * * The parameter `url` sets the URL of the height map image resource.
  68282. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  68283. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  68284. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  68285. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  68286. * * 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.
  68287. * * 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).
  68288. * * The parameter `alphaFilter` will filter any data where the alpha channel is below this value, defaults 0 (all data visible)
  68289. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  68290. * @param name defines the name of the mesh
  68291. * @param url defines the url to the height map
  68292. * @param options defines the options used to create the mesh
  68293. * @param scene defines the hosting scene
  68294. * @returns the ground mesh
  68295. * @see http://doc.babylonjs.com/babylon101/height_map
  68296. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  68297. */
  68298. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  68299. var width = options.width || 10.0;
  68300. var height = options.height || 10.0;
  68301. var subdivisions = options.subdivisions || 1 | 0;
  68302. var minHeight = options.minHeight || 0.0;
  68303. var maxHeight = options.maxHeight || 1.0;
  68304. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  68305. var alphaFilter = options.alphaFilter || 0.0;
  68306. var updatable = options.updatable;
  68307. var onReady = options.onReady;
  68308. var ground = new BABYLON.GroundMesh(name, scene);
  68309. ground._subdivisionsX = subdivisions;
  68310. ground._subdivisionsY = subdivisions;
  68311. ground._width = width;
  68312. ground._height = height;
  68313. ground._maxX = ground._width / 2.0;
  68314. ground._maxZ = ground._height / 2.0;
  68315. ground._minX = -ground._maxX;
  68316. ground._minZ = -ground._maxZ;
  68317. ground._setReady(false);
  68318. var onload = function (img) {
  68319. // Getting height map data
  68320. var canvas = document.createElement("canvas");
  68321. var context = canvas.getContext("2d");
  68322. if (!context) {
  68323. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  68324. }
  68325. if (scene.isDisposed) {
  68326. return;
  68327. }
  68328. var bufferWidth = img.width;
  68329. var bufferHeight = img.height;
  68330. canvas.width = bufferWidth;
  68331. canvas.height = bufferHeight;
  68332. context.drawImage(img, 0, 0);
  68333. // Create VertexData from map data
  68334. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  68335. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  68336. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  68337. width: width, height: height,
  68338. subdivisions: subdivisions,
  68339. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  68340. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight,
  68341. alphaFilter: alphaFilter
  68342. });
  68343. vertexData.applyToMesh(ground, updatable);
  68344. //execute ready callback, if set
  68345. if (onReady) {
  68346. onReady(ground);
  68347. }
  68348. ground._setReady(true);
  68349. };
  68350. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  68351. return ground;
  68352. };
  68353. /**
  68354. * Creates a polygon mesh
  68355. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  68356. * * 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
  68357. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  68358. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  68359. * * 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)
  68360. * * Remember you can only change the shape positions, not their number when updating a polygon
  68361. * @param name defines the name of the mesh
  68362. * @param options defines the options used to create the mesh
  68363. * @param scene defines the hosting scene
  68364. * @returns the polygon mesh
  68365. */
  68366. MeshBuilder.CreatePolygon = function (name, options, scene) {
  68367. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  68368. var shape = options.shape;
  68369. var holes = options.holes || [];
  68370. var depth = options.depth || 0;
  68371. var contours = [];
  68372. var hole = [];
  68373. for (var i = 0; i < shape.length; i++) {
  68374. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  68375. }
  68376. var epsilon = 0.00000001;
  68377. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  68378. contours.pop();
  68379. }
  68380. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  68381. for (var hNb = 0; hNb < holes.length; hNb++) {
  68382. hole = [];
  68383. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  68384. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  68385. }
  68386. polygonTriangulation.addHole(hole);
  68387. }
  68388. var polygon = polygonTriangulation.build(options.updatable, depth);
  68389. polygon._originalBuilderSideOrientation = options.sideOrientation;
  68390. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  68391. vertexData.applyToMesh(polygon, options.updatable);
  68392. return polygon;
  68393. };
  68394. ;
  68395. /**
  68396. * Creates an extruded polygon mesh, with depth in the Y direction.
  68397. * * 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)
  68398. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  68399. * @param name defines the name of the mesh
  68400. * @param options defines the options used to create the mesh
  68401. * @param scene defines the hosting scene
  68402. * @returns the polygon mesh
  68403. */
  68404. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  68405. return MeshBuilder.CreatePolygon(name, options, scene);
  68406. };
  68407. ;
  68408. /**
  68409. * Creates a tube mesh.
  68410. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  68411. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  68412. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  68413. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  68414. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  68415. * * 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)
  68416. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  68417. * * 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
  68418. * * 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
  68419. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  68420. * * 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
  68421. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  68422. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  68423. * @param name defines the name of the mesh
  68424. * @param options defines the options used to create the mesh
  68425. * @param scene defines the hosting scene
  68426. * @returns the tube mesh
  68427. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  68428. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  68429. */
  68430. MeshBuilder.CreateTube = function (name, options, scene) {
  68431. var path = options.path;
  68432. var instance = options.instance;
  68433. var radius = 1.0;
  68434. if (options.radius !== undefined) {
  68435. radius = options.radius;
  68436. }
  68437. else if (instance) {
  68438. radius = instance._creationDataStorage.radius;
  68439. }
  68440. var tessellation = options.tessellation || 64 | 0;
  68441. var radiusFunction = options.radiusFunction || null;
  68442. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  68443. var invertUV = options.invertUV || false;
  68444. var updatable = options.updatable;
  68445. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  68446. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  68447. // tube geometry
  68448. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  68449. var tangents = path3D.getTangents();
  68450. var normals = path3D.getNormals();
  68451. var distances = path3D.getDistances();
  68452. var pi2 = Math.PI * 2;
  68453. var step = pi2 / tessellation * arc;
  68454. var returnRadius = function () { return radius; };
  68455. var radiusFunctionFinal = radiusFunction || returnRadius;
  68456. var circlePath;
  68457. var rad;
  68458. var normal;
  68459. var rotated;
  68460. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  68461. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  68462. for (var i = 0; i < path.length; i++) {
  68463. rad = radiusFunctionFinal(i, distances[i]); // current radius
  68464. circlePath = Array(); // current circle array
  68465. normal = normals[i]; // current normal
  68466. for (var t = 0; t < tessellation; t++) {
  68467. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  68468. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  68469. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  68470. rotated.scaleInPlace(rad).addInPlace(path[i]);
  68471. circlePath[t] = rotated;
  68472. }
  68473. circlePaths[index] = circlePath;
  68474. index++;
  68475. }
  68476. // cap
  68477. var capPath = function (nbPoints, pathIndex) {
  68478. var pointCap = Array();
  68479. for (var i = 0; i < nbPoints; i++) {
  68480. pointCap.push(path[pathIndex]);
  68481. }
  68482. return pointCap;
  68483. };
  68484. switch (cap) {
  68485. case BABYLON.Mesh.NO_CAP:
  68486. break;
  68487. case BABYLON.Mesh.CAP_START:
  68488. circlePaths[0] = capPath(tessellation, 0);
  68489. circlePaths[1] = circlePaths[2].slice(0);
  68490. break;
  68491. case BABYLON.Mesh.CAP_END:
  68492. circlePaths[index] = circlePaths[index - 1].slice(0);
  68493. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  68494. break;
  68495. case BABYLON.Mesh.CAP_ALL:
  68496. circlePaths[0] = capPath(tessellation, 0);
  68497. circlePaths[1] = circlePaths[2].slice(0);
  68498. circlePaths[index] = circlePaths[index - 1].slice(0);
  68499. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  68500. break;
  68501. default:
  68502. break;
  68503. }
  68504. return circlePaths;
  68505. };
  68506. var path3D;
  68507. var pathArray;
  68508. if (instance) { // tube update
  68509. var storage = instance._creationDataStorage;
  68510. var arc = options.arc || storage.arc;
  68511. path3D = storage.path3D.update(path);
  68512. pathArray = tubePathArray(path, path3D, storage.pathArray, radius, storage.tessellation, radiusFunction, storage.cap, arc);
  68513. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  68514. // Update mode, no need to recreate the storage.
  68515. storage.path3D = path3D;
  68516. storage.pathArray = pathArray;
  68517. storage.arc = arc;
  68518. storage.radius = radius;
  68519. return instance;
  68520. }
  68521. // tube creation
  68522. path3D = new BABYLON.Path3D(path);
  68523. var newPathArray = new Array();
  68524. cap = (cap < 0 || cap > 3) ? 0 : cap;
  68525. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  68526. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  68527. tube._creationDataStorage.pathArray = pathArray;
  68528. tube._creationDataStorage.path3D = path3D;
  68529. tube._creationDataStorage.tessellation = tessellation;
  68530. tube._creationDataStorage.cap = cap;
  68531. tube._creationDataStorage.arc = options.arc;
  68532. tube._creationDataStorage.radius = radius;
  68533. return tube;
  68534. };
  68535. /**
  68536. * Creates a polyhedron mesh
  68537. * * 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
  68538. * * The parameter `size` (positive float, default 1) sets the polygon size
  68539. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  68540. * * 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`
  68541. * * 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
  68542. * * 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)`)
  68543. * * 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
  68544. * * 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
  68545. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  68546. * * 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
  68547. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  68548. * @param name defines the name of the mesh
  68549. * @param options defines the options used to create the mesh
  68550. * @param scene defines the hosting scene
  68551. * @returns the polyhedron mesh
  68552. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  68553. */
  68554. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  68555. var polyhedron = new BABYLON.Mesh(name, scene);
  68556. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  68557. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  68558. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  68559. vertexData.applyToMesh(polyhedron, options.updatable);
  68560. return polyhedron;
  68561. };
  68562. /**
  68563. * Creates a decal mesh.
  68564. * 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
  68565. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  68566. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  68567. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  68568. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  68569. * @param name defines the name of the mesh
  68570. * @param sourceMesh defines the mesh where the decal must be applied
  68571. * @param options defines the options used to create the mesh
  68572. * @param scene defines the hosting scene
  68573. * @returns the decal mesh
  68574. * @see http://doc.babylonjs.com/how_to/decals
  68575. */
  68576. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  68577. var indices = sourceMesh.getIndices();
  68578. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  68579. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  68580. var position = options.position || BABYLON.Vector3.Zero();
  68581. var normal = options.normal || BABYLON.Vector3.Up();
  68582. var size = options.size || BABYLON.Vector3.One();
  68583. var angle = options.angle || 0;
  68584. // Getting correct rotation
  68585. if (!normal) {
  68586. var target = new BABYLON.Vector3(0, 0, 1);
  68587. var camera = sourceMesh.getScene().activeCamera;
  68588. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  68589. normal = camera.globalPosition.subtract(cameraWorldTarget);
  68590. }
  68591. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  68592. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  68593. var pitch = Math.atan2(normal.y, len);
  68594. // Matrix
  68595. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  68596. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  68597. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  68598. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  68599. var vertexData = new BABYLON.VertexData();
  68600. vertexData.indices = [];
  68601. vertexData.positions = [];
  68602. vertexData.normals = [];
  68603. vertexData.uvs = [];
  68604. var currentVertexDataIndex = 0;
  68605. var extractDecalVector3 = function (indexId) {
  68606. var result = new BABYLON.PositionNormalVertex();
  68607. if (!indices || !positions || !normals) {
  68608. return result;
  68609. }
  68610. var vertexId = indices[indexId];
  68611. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  68612. // Send vector to decal local world
  68613. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  68614. // Get normal
  68615. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  68616. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  68617. return result;
  68618. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  68619. var clip = function (vertices, axis) {
  68620. if (vertices.length === 0) {
  68621. return vertices;
  68622. }
  68623. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  68624. var clipVertices = function (v0, v1) {
  68625. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  68626. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  68627. };
  68628. var result = new Array();
  68629. for (var index = 0; index < vertices.length; index += 3) {
  68630. var v1Out;
  68631. var v2Out;
  68632. var v3Out;
  68633. var total = 0;
  68634. var nV1 = null;
  68635. var nV2 = null;
  68636. var nV3 = null;
  68637. var nV4 = null;
  68638. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  68639. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  68640. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  68641. v1Out = d1 > 0;
  68642. v2Out = d2 > 0;
  68643. v3Out = d3 > 0;
  68644. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  68645. switch (total) {
  68646. case 0:
  68647. result.push(vertices[index]);
  68648. result.push(vertices[index + 1]);
  68649. result.push(vertices[index + 2]);
  68650. break;
  68651. case 1:
  68652. if (v1Out) {
  68653. nV1 = vertices[index + 1];
  68654. nV2 = vertices[index + 2];
  68655. nV3 = clipVertices(vertices[index], nV1);
  68656. nV4 = clipVertices(vertices[index], nV2);
  68657. }
  68658. if (v2Out) {
  68659. nV1 = vertices[index];
  68660. nV2 = vertices[index + 2];
  68661. nV3 = clipVertices(vertices[index + 1], nV1);
  68662. nV4 = clipVertices(vertices[index + 1], nV2);
  68663. result.push(nV3);
  68664. result.push(nV2.clone());
  68665. result.push(nV1.clone());
  68666. result.push(nV2.clone());
  68667. result.push(nV3.clone());
  68668. result.push(nV4);
  68669. break;
  68670. }
  68671. if (v3Out) {
  68672. nV1 = vertices[index];
  68673. nV2 = vertices[index + 1];
  68674. nV3 = clipVertices(vertices[index + 2], nV1);
  68675. nV4 = clipVertices(vertices[index + 2], nV2);
  68676. }
  68677. if (nV1 && nV2 && nV3 && nV4) {
  68678. result.push(nV1.clone());
  68679. result.push(nV2.clone());
  68680. result.push(nV3);
  68681. result.push(nV4);
  68682. result.push(nV3.clone());
  68683. result.push(nV2.clone());
  68684. }
  68685. break;
  68686. case 2:
  68687. if (!v1Out) {
  68688. nV1 = vertices[index].clone();
  68689. nV2 = clipVertices(nV1, vertices[index + 1]);
  68690. nV3 = clipVertices(nV1, vertices[index + 2]);
  68691. result.push(nV1);
  68692. result.push(nV2);
  68693. result.push(nV3);
  68694. }
  68695. if (!v2Out) {
  68696. nV1 = vertices[index + 1].clone();
  68697. nV2 = clipVertices(nV1, vertices[index + 2]);
  68698. nV3 = clipVertices(nV1, vertices[index]);
  68699. result.push(nV1);
  68700. result.push(nV2);
  68701. result.push(nV3);
  68702. }
  68703. if (!v3Out) {
  68704. nV1 = vertices[index + 2].clone();
  68705. nV2 = clipVertices(nV1, vertices[index]);
  68706. nV3 = clipVertices(nV1, vertices[index + 1]);
  68707. result.push(nV1);
  68708. result.push(nV2);
  68709. result.push(nV3);
  68710. }
  68711. break;
  68712. case 3:
  68713. break;
  68714. }
  68715. }
  68716. return result;
  68717. };
  68718. for (var index = 0; index < indices.length; index += 3) {
  68719. var faceVertices = new Array();
  68720. faceVertices.push(extractDecalVector3(index));
  68721. faceVertices.push(extractDecalVector3(index + 1));
  68722. faceVertices.push(extractDecalVector3(index + 2));
  68723. // Clip
  68724. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  68725. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  68726. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  68727. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  68728. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  68729. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  68730. if (faceVertices.length === 0) {
  68731. continue;
  68732. }
  68733. // Add UVs and get back to world
  68734. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  68735. var vertex = faceVertices[vIndex];
  68736. //TODO check for Int32Array | Uint32Array | Uint16Array
  68737. vertexData.indices.push(currentVertexDataIndex);
  68738. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  68739. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  68740. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  68741. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  68742. currentVertexDataIndex++;
  68743. }
  68744. }
  68745. // Return mesh
  68746. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  68747. vertexData.applyToMesh(decal);
  68748. decal.position = position.clone();
  68749. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  68750. return decal;
  68751. };
  68752. // Privates
  68753. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  68754. // extrusion geometry
  68755. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  68756. var tangents = path3D.getTangents();
  68757. var normals = path3D.getNormals();
  68758. var binormals = path3D.getBinormals();
  68759. var distances = path3D.getDistances();
  68760. var angle = 0;
  68761. var returnScale = function () { return scale !== null ? scale : 1; };
  68762. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  68763. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  68764. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  68765. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  68766. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  68767. for (var i = 0; i < curve.length; i++) {
  68768. var shapePath = new Array();
  68769. var angleStep = rotate(i, distances[i]);
  68770. var scaleRatio = scl(i, distances[i]);
  68771. for (var p = 0; p < shape.length; p++) {
  68772. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  68773. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  68774. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  68775. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  68776. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  68777. shapePath[p] = rotated;
  68778. }
  68779. shapePaths[index] = shapePath;
  68780. angle += angleStep;
  68781. index++;
  68782. }
  68783. // cap
  68784. var capPath = function (shapePath) {
  68785. var pointCap = Array();
  68786. var barycenter = BABYLON.Vector3.Zero();
  68787. var i;
  68788. for (i = 0; i < shapePath.length; i++) {
  68789. barycenter.addInPlace(shapePath[i]);
  68790. }
  68791. barycenter.scaleInPlace(1.0 / shapePath.length);
  68792. for (i = 0; i < shapePath.length; i++) {
  68793. pointCap.push(barycenter);
  68794. }
  68795. return pointCap;
  68796. };
  68797. switch (cap) {
  68798. case BABYLON.Mesh.NO_CAP:
  68799. break;
  68800. case BABYLON.Mesh.CAP_START:
  68801. shapePaths[0] = capPath(shapePaths[2]);
  68802. shapePaths[1] = shapePaths[2];
  68803. break;
  68804. case BABYLON.Mesh.CAP_END:
  68805. shapePaths[index] = shapePaths[index - 1];
  68806. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  68807. break;
  68808. case BABYLON.Mesh.CAP_ALL:
  68809. shapePaths[0] = capPath(shapePaths[2]);
  68810. shapePaths[1] = shapePaths[2];
  68811. shapePaths[index] = shapePaths[index - 1];
  68812. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  68813. break;
  68814. default:
  68815. break;
  68816. }
  68817. return shapePaths;
  68818. };
  68819. var path3D;
  68820. var pathArray;
  68821. if (instance) { // instance update
  68822. var storage = instance._creationDataStorage;
  68823. path3D = storage.path3D.update(curve);
  68824. pathArray = extrusionPathArray(shape, curve, storage.path3D, storage.pathArray, scale, rotation, scaleFunction, rotateFunction, storage.cap, custom);
  68825. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  68826. return instance;
  68827. }
  68828. // extruded shape creation
  68829. path3D = new BABYLON.Path3D(curve);
  68830. var newShapePaths = new Array();
  68831. cap = (cap < 0 || cap > 3) ? 0 : cap;
  68832. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  68833. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  68834. extrudedGeneric._creationDataStorage.pathArray = pathArray;
  68835. extrudedGeneric._creationDataStorage.path3D = path3D;
  68836. extrudedGeneric._creationDataStorage.cap = cap;
  68837. return extrudedGeneric;
  68838. };
  68839. return MeshBuilder;
  68840. }());
  68841. BABYLON.MeshBuilder = MeshBuilder;
  68842. })(BABYLON || (BABYLON = {}));
  68843. //# sourceMappingURL=babylon.meshBuilder.js.map
  68844. var BABYLON;
  68845. (function (BABYLON) {
  68846. /**
  68847. * Draco compression (https://google.github.io/draco/)
  68848. *
  68849. * This class wraps the Draco module.
  68850. *
  68851. * **Encoder**
  68852. *
  68853. * The encoder is not currently implemented.
  68854. *
  68855. * **Decoder**
  68856. *
  68857. * By default, the configuration points to a copy of the Draco decoder files for glTF from the babylon.js preview cdn https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js.
  68858. *
  68859. * To update the configuration, use the following code:
  68860. * ```javascript
  68861. * BABYLON.DracoCompression.Configuration = {
  68862. * decoder: {
  68863. * wasmUrl: "<url to the WebAssembly library>",
  68864. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  68865. * fallbackUrl: "<url to the fallback JavaScript library>",
  68866. * }
  68867. * };
  68868. * ```
  68869. *
  68870. * 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.
  68871. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  68872. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  68873. *
  68874. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  68875. * ```javascript
  68876. * var dracoCompression = new BABYLON.DracoCompression();
  68877. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  68878. * [BABYLON.VertexBuffer.PositionKind]: 0
  68879. * });
  68880. * ```
  68881. *
  68882. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  68883. */
  68884. var DracoCompression = /** @class */ (function () {
  68885. /**
  68886. * Constructor
  68887. */
  68888. function DracoCompression() {
  68889. }
  68890. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  68891. /**
  68892. * Returns true if the decoder is available.
  68893. */
  68894. get: function () {
  68895. if (typeof DracoDecoderModule !== "undefined") {
  68896. return true;
  68897. }
  68898. var decoder = DracoCompression.Configuration.decoder;
  68899. if (decoder) {
  68900. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  68901. return true;
  68902. }
  68903. if (decoder.fallbackUrl) {
  68904. return true;
  68905. }
  68906. }
  68907. return false;
  68908. },
  68909. enumerable: true,
  68910. configurable: true
  68911. });
  68912. /**
  68913. * Stop all async operations and release resources.
  68914. */
  68915. DracoCompression.prototype.dispose = function () {
  68916. };
  68917. /**
  68918. * Decode Draco compressed mesh data to vertex data.
  68919. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  68920. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  68921. * @returns A promise that resolves with the decoded vertex data
  68922. */
  68923. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  68924. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  68925. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  68926. var module = wrappedModule.module;
  68927. var vertexData = new BABYLON.VertexData();
  68928. var buffer = new module.DecoderBuffer();
  68929. buffer.Init(dataView, dataView.byteLength);
  68930. var decoder = new module.Decoder();
  68931. var geometry;
  68932. var status;
  68933. try {
  68934. var type = decoder.GetEncodedGeometryType(buffer);
  68935. switch (type) {
  68936. case module.TRIANGULAR_MESH:
  68937. geometry = new module.Mesh();
  68938. status = decoder.DecodeBufferToMesh(buffer, geometry);
  68939. break;
  68940. case module.POINT_CLOUD:
  68941. geometry = new module.PointCloud();
  68942. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  68943. break;
  68944. default:
  68945. throw new Error("Invalid geometry type " + type);
  68946. }
  68947. if (!status.ok() || !geometry.ptr) {
  68948. throw new Error(status.error_msg());
  68949. }
  68950. var numPoints = geometry.num_points();
  68951. if (type === module.TRIANGULAR_MESH) {
  68952. var numFaces = geometry.num_faces();
  68953. var faceIndices = new module.DracoInt32Array();
  68954. try {
  68955. var indices = new Uint32Array(numFaces * 3);
  68956. for (var i = 0; i < numFaces; i++) {
  68957. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  68958. var offset = i * 3;
  68959. indices[offset + 0] = faceIndices.GetValue(0);
  68960. indices[offset + 1] = faceIndices.GetValue(1);
  68961. indices[offset + 2] = faceIndices.GetValue(2);
  68962. }
  68963. vertexData.indices = indices;
  68964. }
  68965. finally {
  68966. module.destroy(faceIndices);
  68967. }
  68968. }
  68969. for (var kind in attributes) {
  68970. var uniqueId = attributes[kind];
  68971. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  68972. var dracoData = new module.DracoFloat32Array();
  68973. try {
  68974. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  68975. var babylonData = new Float32Array(numPoints * attribute.num_components());
  68976. for (var i = 0; i < babylonData.length; i++) {
  68977. babylonData[i] = dracoData.GetValue(i);
  68978. }
  68979. vertexData.set(babylonData, kind);
  68980. }
  68981. finally {
  68982. module.destroy(dracoData);
  68983. }
  68984. }
  68985. }
  68986. finally {
  68987. if (geometry) {
  68988. module.destroy(geometry);
  68989. }
  68990. module.destroy(decoder);
  68991. module.destroy(buffer);
  68992. }
  68993. return vertexData;
  68994. });
  68995. };
  68996. DracoCompression._GetDecoderModule = function () {
  68997. if (!DracoCompression._DecoderModulePromise) {
  68998. var promise = null;
  68999. var config_1 = {};
  69000. if (typeof DracoDecoderModule !== "undefined") {
  69001. promise = Promise.resolve();
  69002. }
  69003. else {
  69004. var decoder = DracoCompression.Configuration.decoder;
  69005. if (decoder) {
  69006. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  69007. promise = Promise.all([
  69008. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  69009. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  69010. config_1.wasmBinary = data;
  69011. })
  69012. ]);
  69013. }
  69014. else if (decoder.fallbackUrl) {
  69015. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  69016. }
  69017. }
  69018. }
  69019. if (!promise) {
  69020. throw new Error("Draco decoder module is not available");
  69021. }
  69022. DracoCompression._DecoderModulePromise = promise.then(function () {
  69023. return new Promise(function (resolve) {
  69024. config_1.onModuleLoaded = function (decoderModule) {
  69025. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  69026. resolve({ module: decoderModule });
  69027. };
  69028. DracoDecoderModule(config_1);
  69029. });
  69030. });
  69031. }
  69032. return DracoCompression._DecoderModulePromise;
  69033. };
  69034. DracoCompression._LoadScriptAsync = function (url) {
  69035. return new Promise(function (resolve, reject) {
  69036. BABYLON.Tools.LoadScript(url, function () {
  69037. resolve();
  69038. }, function (message) {
  69039. reject(new Error(message));
  69040. });
  69041. });
  69042. };
  69043. DracoCompression._LoadFileAsync = function (url) {
  69044. return new Promise(function (resolve, reject) {
  69045. BABYLON.Tools.LoadFile(url, function (data) {
  69046. resolve(data);
  69047. }, undefined, undefined, true, function (request, exception) {
  69048. reject(exception);
  69049. });
  69050. });
  69051. };
  69052. /**
  69053. * The configuration. Defaults to the following urls:
  69054. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  69055. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  69056. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  69057. */
  69058. DracoCompression.Configuration = {
  69059. decoder: {
  69060. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  69061. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  69062. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  69063. }
  69064. };
  69065. return DracoCompression;
  69066. }());
  69067. BABYLON.DracoCompression = DracoCompression;
  69068. })(BABYLON || (BABYLON = {}));
  69069. //# sourceMappingURL=babylon.dracoCompression.js.map
  69070. var BABYLON;
  69071. (function (BABYLON) {
  69072. // Sets the default audio engine to Babylon JS.
  69073. BABYLON.Engine.AudioEngineFactory = function (engine) { return new AudioEngine(engine); };
  69074. /**
  69075. * This represents the default audio engine used in babylon.
  69076. * It is responsible to play, synchronize and analyse sounds throughout the application.
  69077. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  69078. */
  69079. var AudioEngine = /** @class */ (function () {
  69080. /**
  69081. * Instantiates a new audio engine.
  69082. *
  69083. * There should be only one per page as some browsers restrict the number
  69084. * of audio contexts you can create.
  69085. * @param engine defines the hosting engine
  69086. */
  69087. function AudioEngine(engine) {
  69088. if (engine === void 0) { engine = BABYLON.Engine.LastCreatedEngine; }
  69089. var _this = this;
  69090. this._audioContext = null;
  69091. this._audioContextInitialized = false;
  69092. this._muteButton = null;
  69093. /**
  69094. * Gets whether the current host supports Web Audio and thus could create AudioContexts.
  69095. */
  69096. this.canUseWebAudio = false;
  69097. /**
  69098. * Defines if Babylon should emit a warning if WebAudio is not supported.
  69099. * @ignoreNaming
  69100. */
  69101. this.WarnedWebAudioUnsupported = false;
  69102. /**
  69103. * Gets whether or not mp3 are supported by your browser.
  69104. */
  69105. this.isMP3supported = false;
  69106. /**
  69107. * Gets whether or not ogg are supported by your browser.
  69108. */
  69109. this.isOGGsupported = false;
  69110. /**
  69111. * Gets whether audio has been unlocked on the device.
  69112. * Some Browsers have strong restrictions about Audio and won t autoplay unless
  69113. * a user interaction has happened.
  69114. */
  69115. this.unlocked = true;
  69116. /**
  69117. * Defines if the audio engine relies on a custom unlocked button.
  69118. * In this case, the embedded button will not be displayed.
  69119. */
  69120. this.useCustomUnlockedButton = false;
  69121. /**
  69122. * Event raised when audio has been unlocked on the browser.
  69123. */
  69124. this.onAudioUnlockedObservable = new BABYLON.Observable();
  69125. /**
  69126. * Event raised when audio has been locked on the browser.
  69127. */
  69128. this.onAudioLockedObservable = new BABYLON.Observable();
  69129. this._tryToRun = false;
  69130. this._onResize = function () {
  69131. _this._moveButtonToTopLeft();
  69132. };
  69133. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  69134. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  69135. this.canUseWebAudio = true;
  69136. }
  69137. var audioElem = document.createElement('audio');
  69138. this._engine = engine;
  69139. try {
  69140. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  69141. this.isMP3supported = true;
  69142. }
  69143. }
  69144. catch (e) {
  69145. // protect error during capability check.
  69146. }
  69147. try {
  69148. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  69149. this.isOGGsupported = true;
  69150. }
  69151. }
  69152. catch (e) {
  69153. // protect error during capability check.
  69154. }
  69155. }
  69156. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  69157. /**
  69158. * Gets the current AudioContext if available.
  69159. */
  69160. get: function () {
  69161. if (!this._audioContextInitialized) {
  69162. this._initializeAudioContext();
  69163. }
  69164. else {
  69165. if (!this.unlocked && !this._muteButton) {
  69166. this._displayMuteButton();
  69167. }
  69168. }
  69169. return this._audioContext;
  69170. },
  69171. enumerable: true,
  69172. configurable: true
  69173. });
  69174. /**
  69175. * Flags the audio engine in Locked state.
  69176. * This happens due to new browser policies preventing audio to autoplay.
  69177. */
  69178. AudioEngine.prototype.lock = function () {
  69179. this._triggerSuspendedState();
  69180. };
  69181. /**
  69182. * Unlocks the audio engine once a user action has been done on the dom.
  69183. * This is helpful to resume play once browser policies have been satisfied.
  69184. */
  69185. AudioEngine.prototype.unlock = function () {
  69186. this._triggerRunningState();
  69187. };
  69188. AudioEngine.prototype._resumeAudioContext = function () {
  69189. var result;
  69190. if (this._audioContext.resume) {
  69191. result = this._audioContext.resume();
  69192. }
  69193. return result || Promise.resolve();
  69194. };
  69195. AudioEngine.prototype._initializeAudioContext = function () {
  69196. var _this = this;
  69197. try {
  69198. if (this.canUseWebAudio) {
  69199. this._audioContext = new AudioContext();
  69200. // create a global volume gain node
  69201. this.masterGain = this._audioContext.createGain();
  69202. this.masterGain.gain.value = 1;
  69203. this.masterGain.connect(this._audioContext.destination);
  69204. this._audioContextInitialized = true;
  69205. if (this._audioContext.state === "running") {
  69206. // Do not wait for the promise to unlock.
  69207. this._triggerRunningState();
  69208. }
  69209. else {
  69210. if (this._audioContext && this._audioContext.resume) {
  69211. this._resumeAudioContext().then(function () {
  69212. _this._triggerRunningState();
  69213. }).catch(function () {
  69214. // Can not resume automatically
  69215. // Needs user action
  69216. _this.lock();
  69217. });
  69218. }
  69219. }
  69220. }
  69221. }
  69222. catch (e) {
  69223. this.canUseWebAudio = false;
  69224. BABYLON.Tools.Error("Web Audio: " + e.message);
  69225. }
  69226. };
  69227. AudioEngine.prototype._triggerRunningState = function () {
  69228. var _this = this;
  69229. if (this._tryToRun) {
  69230. return;
  69231. }
  69232. this._tryToRun = true;
  69233. this._resumeAudioContext()
  69234. .then(function () {
  69235. _this._tryToRun = false;
  69236. _this.unlocked = true;
  69237. if (_this._muteButton) {
  69238. _this._hideMuteButton();
  69239. }
  69240. // Notify users that the audio stack is unlocked/unmuted
  69241. _this.onAudioUnlockedObservable.notifyObservers(_this);
  69242. }).catch(function () {
  69243. _this._tryToRun = false;
  69244. _this.unlocked = false;
  69245. });
  69246. };
  69247. AudioEngine.prototype._triggerSuspendedState = function () {
  69248. this.unlocked = false;
  69249. this.onAudioLockedObservable.notifyObservers(this);
  69250. this._displayMuteButton();
  69251. };
  69252. AudioEngine.prototype._displayMuteButton = function () {
  69253. var _this = this;
  69254. if (this.useCustomUnlockedButton) {
  69255. return;
  69256. }
  69257. this._canvas = this._engine.getRenderingCanvas();
  69258. this._muteButton = document.createElement("BUTTON");
  69259. this._muteButton.className = "babylonUnmuteIcon";
  69260. this._muteButton.id = "babylonUnmuteIconBtn";
  69261. this._muteButton.title = "Unmute";
  69262. var css = ".babylonUnmuteIcon { position: absolute; left: 20px; top: 20px; height: 40px; width: 60px; background-color: rgba(51,51,51,0.7); background-image: url(data:image/svg+xml;charset=UTF-8,%3Csvg%20version%3D%221.1%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2239%22%20height%3D%2232%22%20viewBox%3D%220%200%2039%2032%22%3E%3Cpath%20fill%3D%22white%22%20d%3D%22M9.625%2018.938l-0.031%200.016h-4.953q-0.016%200-0.031-0.016v-12.453q0-0.016%200.031-0.016h4.953q0.031%200%200.031%200.016v12.453zM12.125%207.688l8.719-8.703v27.453l-8.719-8.719-0.016-0.047v-9.938zM23.359%207.875l1.406-1.406%204.219%204.203%204.203-4.203%201.422%201.406-4.219%204.219%204.219%204.203-1.484%201.359-4.141-4.156-4.219%204.219-1.406-1.422%204.219-4.203z%22%3E%3C%2Fpath%3E%3C%2Fsvg%3E); background-size: 80%; background-repeat:no-repeat; background-position: center; background-position-y: 4px; border: none; outline: none; transition: transform 0.125s ease-out; cursor: pointer; z-index: 9999; } .babylonUnmuteIcon:hover { transform: scale(1.05) } .babylonUnmuteIcon:active { background-color: rgba(51,51,51,1) }";
  69263. var style = document.createElement('style');
  69264. style.appendChild(document.createTextNode(css));
  69265. document.getElementsByTagName('head')[0].appendChild(style);
  69266. document.body.appendChild(this._muteButton);
  69267. this._moveButtonToTopLeft();
  69268. this._muteButton.addEventListener('mousedown', function () {
  69269. _this._triggerRunningState();
  69270. }, true);
  69271. this._muteButton.addEventListener('touchend', function () {
  69272. _this._triggerRunningState();
  69273. }, true);
  69274. this._muteButton.addEventListener('click', function () {
  69275. _this._triggerRunningState();
  69276. }, true);
  69277. window.addEventListener("resize", this._onResize);
  69278. };
  69279. AudioEngine.prototype._moveButtonToTopLeft = function () {
  69280. if (this._canvas && this._muteButton) {
  69281. this._muteButton.style.top = this._canvas.offsetTop + 20 + "px";
  69282. this._muteButton.style.left = this._canvas.offsetLeft + 20 + "px";
  69283. }
  69284. };
  69285. AudioEngine.prototype._hideMuteButton = function () {
  69286. if (this._muteButton) {
  69287. document.body.removeChild(this._muteButton);
  69288. this._muteButton = null;
  69289. }
  69290. };
  69291. /**
  69292. * Destroy and release the resources associated with the audio ccontext.
  69293. */
  69294. AudioEngine.prototype.dispose = function () {
  69295. if (this.canUseWebAudio && this._audioContextInitialized) {
  69296. if (this._connectedAnalyser && this._audioContext) {
  69297. this._connectedAnalyser.stopDebugCanvas();
  69298. this._connectedAnalyser.dispose();
  69299. this.masterGain.disconnect();
  69300. this.masterGain.connect(this._audioContext.destination);
  69301. this._connectedAnalyser = null;
  69302. }
  69303. this.masterGain.gain.value = 1;
  69304. }
  69305. this.WarnedWebAudioUnsupported = false;
  69306. this._hideMuteButton();
  69307. window.removeEventListener("resize", this._onResize);
  69308. this.onAudioUnlockedObservable.clear();
  69309. this.onAudioLockedObservable.clear();
  69310. };
  69311. /**
  69312. * Gets the global volume sets on the master gain.
  69313. * @returns the global volume if set or -1 otherwise
  69314. */
  69315. AudioEngine.prototype.getGlobalVolume = function () {
  69316. if (this.canUseWebAudio && this._audioContextInitialized) {
  69317. return this.masterGain.gain.value;
  69318. }
  69319. else {
  69320. return -1;
  69321. }
  69322. };
  69323. /**
  69324. * Sets the global volume of your experience (sets on the master gain).
  69325. * @param newVolume Defines the new global volume of the application
  69326. */
  69327. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  69328. if (this.canUseWebAudio && this._audioContextInitialized) {
  69329. this.masterGain.gain.value = newVolume;
  69330. }
  69331. };
  69332. /**
  69333. * Connect the audio engine to an audio analyser allowing some amazing
  69334. * synchornization between the sounds/music and your visualization (VuMeter for instance).
  69335. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-the-analyser
  69336. * @param analyser The analyser to connect to the engine
  69337. */
  69338. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  69339. if (this._connectedAnalyser) {
  69340. this._connectedAnalyser.stopDebugCanvas();
  69341. }
  69342. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  69343. this._connectedAnalyser = analyser;
  69344. this.masterGain.disconnect();
  69345. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  69346. }
  69347. };
  69348. return AudioEngine;
  69349. }());
  69350. BABYLON.AudioEngine = AudioEngine;
  69351. })(BABYLON || (BABYLON = {}));
  69352. //# sourceMappingURL=babylon.audioEngine.js.map
  69353. var BABYLON;
  69354. (function (BABYLON) {
  69355. /**
  69356. * Defines a sound that can be played in the application.
  69357. * The sound can either be an ambient track or a simple sound played in reaction to a user action.
  69358. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  69359. */
  69360. var Sound = /** @class */ (function () {
  69361. /**
  69362. * Create a sound and attach it to a scene
  69363. * @param name Name of your sound
  69364. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams
  69365. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  69366. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  69367. */
  69368. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  69369. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  69370. var _this = this;
  69371. /**
  69372. * Does the sound autoplay once loaded.
  69373. */
  69374. this.autoplay = false;
  69375. /**
  69376. * Does the sound loop after it finishes playing once.
  69377. */
  69378. this.loop = false;
  69379. /**
  69380. * Does the sound use a custom attenuation curve to simulate the falloff
  69381. * happening when the source gets further away from the camera.
  69382. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-your-own-custom-attenuation-function
  69383. */
  69384. this.useCustomAttenuation = false;
  69385. /**
  69386. * Is this sound currently played.
  69387. */
  69388. this.isPlaying = false;
  69389. /**
  69390. * Is this sound currently paused.
  69391. */
  69392. this.isPaused = false;
  69393. /**
  69394. * Does this sound enables spatial sound.
  69395. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  69396. */
  69397. this.spatialSound = false;
  69398. /**
  69399. * Define the reference distance the sound should be heard perfectly.
  69400. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  69401. */
  69402. this.refDistance = 1;
  69403. /**
  69404. * Define the roll off factor of spatial sounds.
  69405. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  69406. */
  69407. this.rolloffFactor = 1;
  69408. /**
  69409. * Define the max distance the sound should be heard (intensity just became 0 at this point).
  69410. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  69411. */
  69412. this.maxDistance = 100;
  69413. /**
  69414. * Define the distance attenuation model the sound will follow.
  69415. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  69416. */
  69417. this.distanceModel = "linear";
  69418. /**
  69419. * Observable event when the current playing sound finishes.
  69420. */
  69421. this.onEndedObservable = new BABYLON.Observable();
  69422. this._panningModel = "equalpower";
  69423. this._playbackRate = 1;
  69424. this._streaming = false;
  69425. this._startTime = 0;
  69426. this._startOffset = 0;
  69427. this._position = BABYLON.Vector3.Zero();
  69428. /** @hidden */
  69429. this._positionInEmitterSpace = false;
  69430. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  69431. this._volume = 1;
  69432. this._isReadyToPlay = false;
  69433. this._isDirectional = false;
  69434. // Used if you'd like to create a directional sound.
  69435. // If not set, the sound will be omnidirectional
  69436. this._coneInnerAngle = 360;
  69437. this._coneOuterAngle = 360;
  69438. this._coneOuterGain = 0;
  69439. this._isOutputConnected = false;
  69440. this._urlType = "Unknown";
  69441. this.name = name;
  69442. this._scene = scene;
  69443. var compo = scene._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  69444. if (!compo) {
  69445. compo = new BABYLON.AudioSceneComponent(scene);
  69446. scene._addComponent(compo);
  69447. }
  69448. this._readyToPlayCallback = readyToPlayCallback;
  69449. // Default custom attenuation function is a linear attenuation
  69450. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  69451. if (currentDistance < maxDistance) {
  69452. return currentVolume * (1 - currentDistance / maxDistance);
  69453. }
  69454. else {
  69455. return 0;
  69456. }
  69457. };
  69458. if (options) {
  69459. this.autoplay = options.autoplay || false;
  69460. this.loop = options.loop || false;
  69461. // if volume === 0, we need another way to check this option
  69462. if (options.volume !== undefined) {
  69463. this._volume = options.volume;
  69464. }
  69465. this.spatialSound = options.spatialSound || false;
  69466. this.maxDistance = options.maxDistance || 100;
  69467. this.useCustomAttenuation = options.useCustomAttenuation || false;
  69468. this.rolloffFactor = options.rolloffFactor || 1;
  69469. this.refDistance = options.refDistance || 1;
  69470. this.distanceModel = options.distanceModel || "linear";
  69471. this._playbackRate = options.playbackRate || 1;
  69472. this._streaming = options.streaming || false;
  69473. }
  69474. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  69475. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  69476. this._soundGain.gain.value = this._volume;
  69477. this._inputAudioNode = this._soundGain;
  69478. this._outputAudioNode = this._soundGain;
  69479. if (this.spatialSound) {
  69480. this._createSpatialParameters();
  69481. }
  69482. this._scene.mainSoundTrack.AddSound(this);
  69483. var validParameter = true;
  69484. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  69485. if (urlOrArrayBuffer) {
  69486. try {
  69487. if (typeof (urlOrArrayBuffer) === "string") {
  69488. this._urlType = "String";
  69489. }
  69490. else if (urlOrArrayBuffer instanceof ArrayBuffer) {
  69491. this._urlType = "ArrayBuffer";
  69492. }
  69493. else if (urlOrArrayBuffer instanceof MediaStream) {
  69494. this._urlType = "MediaStream";
  69495. }
  69496. else if (Array.isArray(urlOrArrayBuffer)) {
  69497. this._urlType = "Array";
  69498. }
  69499. var urls = [];
  69500. var codecSupportedFound = false;
  69501. switch (this._urlType) {
  69502. case "MediaStream":
  69503. this._streaming = true;
  69504. this._isReadyToPlay = true;
  69505. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(urlOrArrayBuffer);
  69506. if (this.autoplay) {
  69507. this.play();
  69508. }
  69509. if (this._readyToPlayCallback) {
  69510. this._readyToPlayCallback();
  69511. }
  69512. break;
  69513. case "ArrayBuffer":
  69514. if (urlOrArrayBuffer.byteLength > 0) {
  69515. codecSupportedFound = true;
  69516. this._soundLoaded(urlOrArrayBuffer);
  69517. }
  69518. break;
  69519. case "String":
  69520. urls.push(urlOrArrayBuffer);
  69521. case "Array":
  69522. if (urls.length === 0)
  69523. urls = urlOrArrayBuffer;
  69524. // If we found a supported format, we load it immediately and stop the loop
  69525. for (var i = 0; i < urls.length; i++) {
  69526. var url = urls[i];
  69527. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  69528. codecSupportedFound = true;
  69529. }
  69530. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  69531. codecSupportedFound = true;
  69532. }
  69533. if (url.indexOf(".wav", url.length - 4) !== -1) {
  69534. codecSupportedFound = true;
  69535. }
  69536. if (url.indexOf("blob:") !== -1) {
  69537. codecSupportedFound = true;
  69538. }
  69539. if (codecSupportedFound) {
  69540. // Loading sound using XHR2
  69541. if (!this._streaming) {
  69542. this._scene._loadFile(url, function (data) {
  69543. _this._soundLoaded(data);
  69544. }, undefined, true, true, function (exception) {
  69545. if (exception) {
  69546. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  69547. }
  69548. BABYLON.Tools.Error("Sound creation aborted.");
  69549. _this._scene.mainSoundTrack.RemoveSound(_this);
  69550. });
  69551. }
  69552. // Streaming sound using HTML5 Audio tag
  69553. else {
  69554. this._htmlAudioElement = new Audio(url);
  69555. this._htmlAudioElement.controls = false;
  69556. this._htmlAudioElement.loop = this.loop;
  69557. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  69558. this._htmlAudioElement.preload = "auto";
  69559. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  69560. _this._isReadyToPlay = true;
  69561. if (_this.autoplay) {
  69562. _this.play();
  69563. }
  69564. if (_this._readyToPlayCallback) {
  69565. _this._readyToPlayCallback();
  69566. }
  69567. });
  69568. document.body.appendChild(this._htmlAudioElement);
  69569. this._htmlAudioElement.load();
  69570. }
  69571. break;
  69572. }
  69573. }
  69574. break;
  69575. default:
  69576. validParameter = false;
  69577. break;
  69578. }
  69579. if (!validParameter) {
  69580. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  69581. }
  69582. else {
  69583. if (!codecSupportedFound) {
  69584. this._isReadyToPlay = true;
  69585. // Simulating a ready to play event to avoid breaking code path
  69586. if (this._readyToPlayCallback) {
  69587. window.setTimeout(function () {
  69588. if (_this._readyToPlayCallback) {
  69589. _this._readyToPlayCallback();
  69590. }
  69591. }, 1000);
  69592. }
  69593. }
  69594. }
  69595. }
  69596. catch (ex) {
  69597. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  69598. this._scene.mainSoundTrack.RemoveSound(this);
  69599. }
  69600. }
  69601. }
  69602. else {
  69603. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  69604. this._scene.mainSoundTrack.AddSound(this);
  69605. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  69606. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  69607. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  69608. }
  69609. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  69610. if (this._readyToPlayCallback) {
  69611. window.setTimeout(function () {
  69612. if (_this._readyToPlayCallback) {
  69613. _this._readyToPlayCallback();
  69614. }
  69615. }, 1000);
  69616. }
  69617. }
  69618. }
  69619. /**
  69620. * Release the sound and its associated resources
  69621. */
  69622. Sound.prototype.dispose = function () {
  69623. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  69624. if (this.isPlaying) {
  69625. this.stop();
  69626. }
  69627. this._isReadyToPlay = false;
  69628. if (this.soundTrackId === -1) {
  69629. this._scene.mainSoundTrack.RemoveSound(this);
  69630. }
  69631. else if (this._scene.soundTracks) {
  69632. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  69633. }
  69634. if (this._soundGain) {
  69635. this._soundGain.disconnect();
  69636. this._soundGain = null;
  69637. }
  69638. if (this._soundPanner) {
  69639. this._soundPanner.disconnect();
  69640. this._soundPanner = null;
  69641. }
  69642. if (this._soundSource) {
  69643. this._soundSource.disconnect();
  69644. this._soundSource = null;
  69645. }
  69646. this._audioBuffer = null;
  69647. if (this._htmlAudioElement) {
  69648. this._htmlAudioElement.pause();
  69649. this._htmlAudioElement.src = "";
  69650. document.body.removeChild(this._htmlAudioElement);
  69651. }
  69652. if (this._streamingSource) {
  69653. this._streamingSource.disconnect();
  69654. }
  69655. if (this._connectedMesh && this._registerFunc) {
  69656. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  69657. this._connectedMesh = null;
  69658. }
  69659. }
  69660. };
  69661. /**
  69662. * Gets if the sounds is ready to be played or not.
  69663. * @returns true if ready, otherwise false
  69664. */
  69665. Sound.prototype.isReady = function () {
  69666. return this._isReadyToPlay;
  69667. };
  69668. Sound.prototype._soundLoaded = function (audioData) {
  69669. var _this = this;
  69670. if (!BABYLON.Engine.audioEngine.audioContext) {
  69671. return;
  69672. }
  69673. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  69674. _this._audioBuffer = buffer;
  69675. _this._isReadyToPlay = true;
  69676. if (_this.autoplay) {
  69677. _this.play();
  69678. }
  69679. if (_this._readyToPlayCallback) {
  69680. _this._readyToPlayCallback();
  69681. }
  69682. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  69683. };
  69684. /**
  69685. * Sets the data of the sound from an audiobuffer
  69686. * @param audioBuffer The audioBuffer containing the data
  69687. */
  69688. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  69689. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  69690. this._audioBuffer = audioBuffer;
  69691. this._isReadyToPlay = true;
  69692. }
  69693. };
  69694. /**
  69695. * Updates the current sounds options such as maxdistance, loop...
  69696. * @param options A JSON object containing values named as the object properties
  69697. */
  69698. Sound.prototype.updateOptions = function (options) {
  69699. if (options) {
  69700. this.loop = options.loop || this.loop;
  69701. this.maxDistance = options.maxDistance || this.maxDistance;
  69702. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  69703. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  69704. this.refDistance = options.refDistance || this.refDistance;
  69705. this.distanceModel = options.distanceModel || this.distanceModel;
  69706. this._playbackRate = options.playbackRate || this._playbackRate;
  69707. this._updateSpatialParameters();
  69708. if (this.isPlaying) {
  69709. if (this._streaming && this._htmlAudioElement) {
  69710. this._htmlAudioElement.playbackRate = this._playbackRate;
  69711. }
  69712. else {
  69713. if (this._soundSource) {
  69714. this._soundSource.playbackRate.value = this._playbackRate;
  69715. }
  69716. }
  69717. }
  69718. }
  69719. };
  69720. Sound.prototype._createSpatialParameters = function () {
  69721. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  69722. if (this._scene.headphone) {
  69723. this._panningModel = "HRTF";
  69724. }
  69725. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  69726. this._updateSpatialParameters();
  69727. this._soundPanner.connect(this._outputAudioNode);
  69728. this._inputAudioNode = this._soundPanner;
  69729. }
  69730. };
  69731. Sound.prototype._updateSpatialParameters = function () {
  69732. if (this.spatialSound && this._soundPanner) {
  69733. if (this.useCustomAttenuation) {
  69734. // Tricks to disable in a way embedded Web Audio attenuation
  69735. this._soundPanner.distanceModel = "linear";
  69736. this._soundPanner.maxDistance = Number.MAX_VALUE;
  69737. this._soundPanner.refDistance = 1;
  69738. this._soundPanner.rolloffFactor = 1;
  69739. this._soundPanner.panningModel = this._panningModel;
  69740. }
  69741. else {
  69742. this._soundPanner.distanceModel = this.distanceModel;
  69743. this._soundPanner.maxDistance = this.maxDistance;
  69744. this._soundPanner.refDistance = this.refDistance;
  69745. this._soundPanner.rolloffFactor = this.rolloffFactor;
  69746. this._soundPanner.panningModel = this._panningModel;
  69747. }
  69748. }
  69749. };
  69750. /**
  69751. * Switch the panning model to HRTF:
  69752. * Renders a stereo output of higher quality than equalpower — it uses a convolution with measured impulse responses from human subjects.
  69753. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  69754. */
  69755. Sound.prototype.switchPanningModelToHRTF = function () {
  69756. this._panningModel = "HRTF";
  69757. this._switchPanningModel();
  69758. };
  69759. /**
  69760. * Switch the panning model to Equal Power:
  69761. * Represents the equal-power panning algorithm, generally regarded as simple and efficient. equalpower is the default value.
  69762. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  69763. */
  69764. Sound.prototype.switchPanningModelToEqualPower = function () {
  69765. this._panningModel = "equalpower";
  69766. this._switchPanningModel();
  69767. };
  69768. Sound.prototype._switchPanningModel = function () {
  69769. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  69770. this._soundPanner.panningModel = this._panningModel;
  69771. }
  69772. };
  69773. /**
  69774. * Connect this sound to a sound track audio node like gain...
  69775. * @param soundTrackAudioNode the sound track audio node to connect to
  69776. */
  69777. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  69778. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  69779. if (this._isOutputConnected) {
  69780. this._outputAudioNode.disconnect();
  69781. }
  69782. this._outputAudioNode.connect(soundTrackAudioNode);
  69783. this._isOutputConnected = true;
  69784. }
  69785. };
  69786. /**
  69787. * Transform this sound into a directional source
  69788. * @param coneInnerAngle Size of the inner cone in degree
  69789. * @param coneOuterAngle Size of the outer cone in degree
  69790. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  69791. */
  69792. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  69793. if (coneOuterAngle < coneInnerAngle) {
  69794. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  69795. return;
  69796. }
  69797. this._coneInnerAngle = coneInnerAngle;
  69798. this._coneOuterAngle = coneOuterAngle;
  69799. this._coneOuterGain = coneOuterGain;
  69800. this._isDirectional = true;
  69801. if (this.isPlaying && this.loop) {
  69802. this.stop();
  69803. this.play();
  69804. }
  69805. };
  69806. Object.defineProperty(Sound.prototype, "directionalConeInnerAngle", {
  69807. /**
  69808. * Gets or sets the inner angle for the directional cone.
  69809. */
  69810. get: function () {
  69811. return this._coneInnerAngle;
  69812. },
  69813. /**
  69814. * Gets or sets the inner angle for the directional cone.
  69815. */
  69816. set: function (value) {
  69817. if (value != this._coneInnerAngle) {
  69818. if (this._coneOuterAngle < value) {
  69819. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  69820. return;
  69821. }
  69822. this._coneInnerAngle = value;
  69823. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  69824. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  69825. }
  69826. }
  69827. },
  69828. enumerable: true,
  69829. configurable: true
  69830. });
  69831. Object.defineProperty(Sound.prototype, "directionalConeOuterAngle", {
  69832. /**
  69833. * Gets or sets the outer angle for the directional cone.
  69834. */
  69835. get: function () {
  69836. return this._coneOuterAngle;
  69837. },
  69838. /**
  69839. * Gets or sets the outer angle for the directional cone.
  69840. */
  69841. set: function (value) {
  69842. if (value != this._coneOuterAngle) {
  69843. if (value < this._coneInnerAngle) {
  69844. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  69845. return;
  69846. }
  69847. this._coneOuterAngle = value;
  69848. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  69849. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  69850. }
  69851. }
  69852. },
  69853. enumerable: true,
  69854. configurable: true
  69855. });
  69856. /**
  69857. * Sets the position of the emitter if spatial sound is enabled
  69858. * @param newPosition Defines the new posisiton
  69859. */
  69860. Sound.prototype.setPosition = function (newPosition) {
  69861. this._position = newPosition;
  69862. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner && !isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  69863. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  69864. }
  69865. };
  69866. /**
  69867. * Sets the local direction of the emitter if spatial sound is enabled
  69868. * @param newLocalDirection Defines the new local direction
  69869. */
  69870. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  69871. this._localDirection = newLocalDirection;
  69872. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  69873. this._updateDirection();
  69874. }
  69875. };
  69876. Sound.prototype._updateDirection = function () {
  69877. if (!this._connectedMesh || !this._soundPanner) {
  69878. return;
  69879. }
  69880. var mat = this._connectedMesh.getWorldMatrix();
  69881. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  69882. direction.normalize();
  69883. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  69884. };
  69885. /** @hidden */
  69886. Sound.prototype.updateDistanceFromListener = function () {
  69887. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  69888. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  69889. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  69890. }
  69891. };
  69892. /**
  69893. * Sets a new custom attenuation function for the sound.
  69894. * @param callback Defines the function used for the attenuation
  69895. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-your-own-custom-attenuation-function
  69896. */
  69897. Sound.prototype.setAttenuationFunction = function (callback) {
  69898. this._customAttenuationFunction = callback;
  69899. };
  69900. /**
  69901. * Play the sound
  69902. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  69903. * @param offset (optional) Start the sound setting it at a specific time
  69904. */
  69905. Sound.prototype.play = function (time, offset) {
  69906. var _this = this;
  69907. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  69908. try {
  69909. if (this._startOffset < 0) {
  69910. time = -this._startOffset;
  69911. this._startOffset = 0;
  69912. }
  69913. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  69914. if (!this._soundSource || !this._streamingSource) {
  69915. if (this.spatialSound && this._soundPanner) {
  69916. if (!isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  69917. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  69918. }
  69919. if (this._isDirectional) {
  69920. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  69921. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  69922. this._soundPanner.coneOuterGain = this._coneOuterGain;
  69923. if (this._connectedMesh) {
  69924. this._updateDirection();
  69925. }
  69926. else {
  69927. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  69928. }
  69929. }
  69930. }
  69931. }
  69932. if (this._streaming) {
  69933. if (!this._streamingSource) {
  69934. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  69935. this._htmlAudioElement.onended = function () { _this._onended(); };
  69936. this._htmlAudioElement.playbackRate = this._playbackRate;
  69937. }
  69938. this._streamingSource.disconnect();
  69939. this._streamingSource.connect(this._inputAudioNode);
  69940. if (this._htmlAudioElement) {
  69941. // required to manage properly the new suspended default state of Chrome
  69942. // When the option 'streaming: true' is used, we need first to wait for
  69943. // the audio engine to be unlocked by a user gesture before trying to play
  69944. // an HTML Audio elememt
  69945. var tryToPlay = function () {
  69946. if (BABYLON.Engine.audioEngine.unlocked) {
  69947. var playPromise = _this._htmlAudioElement.play();
  69948. // In browsers that don’t yet support this functionality,
  69949. // playPromise won’t be defined.
  69950. if (playPromise !== undefined) {
  69951. playPromise.catch(function (error) {
  69952. // Automatic playback failed.
  69953. // Waiting for the audio engine to be unlocked by user click on unmute
  69954. BABYLON.Engine.audioEngine.lock();
  69955. BABYLON.Engine.audioEngine.onAudioUnlockedObservable.addOnce(function () { tryToPlay(); });
  69956. });
  69957. }
  69958. }
  69959. else {
  69960. BABYLON.Engine.audioEngine.onAudioUnlockedObservable.addOnce(function () { tryToPlay(); });
  69961. }
  69962. };
  69963. tryToPlay();
  69964. }
  69965. }
  69966. else {
  69967. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  69968. this._soundSource.buffer = this._audioBuffer;
  69969. this._soundSource.connect(this._inputAudioNode);
  69970. this._soundSource.loop = this.loop;
  69971. this._soundSource.playbackRate.value = this._playbackRate;
  69972. this._soundSource.onended = function () { _this._onended(); };
  69973. if (this._soundSource.buffer) {
  69974. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  69975. }
  69976. }
  69977. this._startTime = startTime;
  69978. this.isPlaying = true;
  69979. this.isPaused = false;
  69980. }
  69981. catch (ex) {
  69982. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  69983. }
  69984. }
  69985. };
  69986. Sound.prototype._onended = function () {
  69987. this.isPlaying = false;
  69988. if (this.onended) {
  69989. this.onended();
  69990. }
  69991. this.onEndedObservable.notifyObservers(this);
  69992. };
  69993. /**
  69994. * Stop the sound
  69995. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  69996. */
  69997. Sound.prototype.stop = function (time) {
  69998. if (this.isPlaying) {
  69999. if (this._streaming) {
  70000. if (this._htmlAudioElement) {
  70001. this._htmlAudioElement.pause();
  70002. // Test needed for Firefox or it will generate an Invalid State Error
  70003. if (this._htmlAudioElement.currentTime > 0) {
  70004. this._htmlAudioElement.currentTime = 0;
  70005. }
  70006. }
  70007. else {
  70008. this._streamingSource.disconnect();
  70009. }
  70010. }
  70011. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  70012. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  70013. this._soundSource.stop(stopTime);
  70014. this._soundSource.onended = function () { };
  70015. if (!this.isPaused) {
  70016. this._startOffset = 0;
  70017. }
  70018. }
  70019. this.isPlaying = false;
  70020. }
  70021. };
  70022. /**
  70023. * Put the sound in pause
  70024. */
  70025. Sound.prototype.pause = function () {
  70026. if (this.isPlaying) {
  70027. this.isPaused = true;
  70028. if (this._streaming) {
  70029. if (this._htmlAudioElement) {
  70030. this._htmlAudioElement.pause();
  70031. }
  70032. else {
  70033. this._streamingSource.disconnect();
  70034. }
  70035. }
  70036. else if (BABYLON.Engine.audioEngine.audioContext) {
  70037. this.stop(0);
  70038. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  70039. }
  70040. }
  70041. };
  70042. /**
  70043. * Sets a dedicated volume for this sounds
  70044. * @param newVolume Define the new volume of the sound
  70045. * @param time Define in how long the sound should be at this value
  70046. */
  70047. Sound.prototype.setVolume = function (newVolume, time) {
  70048. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  70049. if (time && BABYLON.Engine.audioEngine.audioContext) {
  70050. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  70051. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  70052. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  70053. }
  70054. else {
  70055. this._soundGain.gain.value = newVolume;
  70056. }
  70057. }
  70058. this._volume = newVolume;
  70059. };
  70060. /**
  70061. * Set the sound play back rate
  70062. * @param newPlaybackRate Define the playback rate the sound should be played at
  70063. */
  70064. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  70065. this._playbackRate = newPlaybackRate;
  70066. if (this.isPlaying) {
  70067. if (this._streaming && this._htmlAudioElement) {
  70068. this._htmlAudioElement.playbackRate = this._playbackRate;
  70069. }
  70070. else if (this._soundSource) {
  70071. this._soundSource.playbackRate.value = this._playbackRate;
  70072. }
  70073. }
  70074. };
  70075. /**
  70076. * Gets the volume of the sound.
  70077. * @returns the volume of the sound
  70078. */
  70079. Sound.prototype.getVolume = function () {
  70080. return this._volume;
  70081. };
  70082. /**
  70083. * Attach the sound to a dedicated mesh
  70084. * @param meshToConnectTo The mesh to connect the sound with
  70085. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#attaching-a-sound-to-a-mesh
  70086. */
  70087. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  70088. var _this = this;
  70089. if (this._connectedMesh && this._registerFunc) {
  70090. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  70091. this._registerFunc = null;
  70092. }
  70093. this._connectedMesh = meshToConnectTo;
  70094. if (!this.spatialSound) {
  70095. this.spatialSound = true;
  70096. this._createSpatialParameters();
  70097. if (this.isPlaying && this.loop) {
  70098. this.stop();
  70099. this.play();
  70100. }
  70101. }
  70102. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  70103. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  70104. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  70105. };
  70106. /**
  70107. * Detach the sound from the previously attached mesh
  70108. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#attaching-a-sound-to-a-mesh
  70109. */
  70110. Sound.prototype.detachFromMesh = function () {
  70111. if (this._connectedMesh && this._registerFunc) {
  70112. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  70113. this._registerFunc = null;
  70114. this._connectedMesh = null;
  70115. }
  70116. };
  70117. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  70118. if (!node.getBoundingInfo) {
  70119. return;
  70120. }
  70121. var mesh = node;
  70122. if (this._positionInEmitterSpace) {
  70123. mesh.worldMatrixFromCache.invertToRef(BABYLON.Tmp.Matrix[0]);
  70124. this.setPosition(BABYLON.Tmp.Matrix[0].getTranslation());
  70125. }
  70126. else {
  70127. var boundingInfo = mesh.getBoundingInfo();
  70128. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  70129. }
  70130. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  70131. this._updateDirection();
  70132. }
  70133. };
  70134. /**
  70135. * Clone the current sound in the scene.
  70136. * @returns the new sound clone
  70137. */
  70138. Sound.prototype.clone = function () {
  70139. var _this = this;
  70140. if (!this._streaming) {
  70141. var setBufferAndRun = function () {
  70142. if (_this._isReadyToPlay) {
  70143. clonedSound._audioBuffer = _this.getAudioBuffer();
  70144. clonedSound._isReadyToPlay = true;
  70145. if (clonedSound.autoplay) {
  70146. clonedSound.play();
  70147. }
  70148. }
  70149. else {
  70150. window.setTimeout(setBufferAndRun, 300);
  70151. }
  70152. };
  70153. var currentOptions = {
  70154. autoplay: this.autoplay, loop: this.loop,
  70155. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  70156. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  70157. refDistance: this.refDistance, distanceModel: this.distanceModel
  70158. };
  70159. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  70160. if (this.useCustomAttenuation) {
  70161. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  70162. }
  70163. clonedSound.setPosition(this._position);
  70164. clonedSound.setPlaybackRate(this._playbackRate);
  70165. setBufferAndRun();
  70166. return clonedSound;
  70167. }
  70168. // Can't clone a streaming sound
  70169. else {
  70170. return null;
  70171. }
  70172. };
  70173. /**
  70174. * Gets the current underlying audio buffer containing the data
  70175. * @returns the audio buffer
  70176. */
  70177. Sound.prototype.getAudioBuffer = function () {
  70178. return this._audioBuffer;
  70179. };
  70180. /**
  70181. * Serializes the Sound in a JSON representation
  70182. * @returns the JSON representation of the sound
  70183. */
  70184. Sound.prototype.serialize = function () {
  70185. var serializationObject = {
  70186. name: this.name,
  70187. url: this.name,
  70188. autoplay: this.autoplay,
  70189. loop: this.loop,
  70190. volume: this._volume,
  70191. spatialSound: this.spatialSound,
  70192. maxDistance: this.maxDistance,
  70193. rolloffFactor: this.rolloffFactor,
  70194. refDistance: this.refDistance,
  70195. distanceModel: this.distanceModel,
  70196. playbackRate: this._playbackRate,
  70197. panningModel: this._panningModel,
  70198. soundTrackId: this.soundTrackId
  70199. };
  70200. if (this.spatialSound) {
  70201. if (this._connectedMesh)
  70202. serializationObject.connectedMeshId = this._connectedMesh.id;
  70203. serializationObject.position = this._position.asArray();
  70204. serializationObject.refDistance = this.refDistance;
  70205. serializationObject.distanceModel = this.distanceModel;
  70206. serializationObject.isDirectional = this._isDirectional;
  70207. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  70208. serializationObject.coneInnerAngle = this._coneInnerAngle;
  70209. serializationObject.coneOuterAngle = this._coneOuterAngle;
  70210. serializationObject.coneOuterGain = this._coneOuterGain;
  70211. }
  70212. return serializationObject;
  70213. };
  70214. /**
  70215. * Parse a JSON representation of a sound to innstantiate in a given scene
  70216. * @param parsedSound Define the JSON representation of the sound (usually coming from the serialize method)
  70217. * @param scene Define the scene the new parsed sound should be created in
  70218. * @param rootUrl Define the rooturl of the load in case we need to fetch relative dependencies
  70219. * @param sourceSound Define a cound place holder if do not need to instantiate a new one
  70220. * @returns the newly parsed sound
  70221. */
  70222. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  70223. var soundName = parsedSound.name;
  70224. var soundUrl;
  70225. if (parsedSound.url) {
  70226. soundUrl = rootUrl + parsedSound.url;
  70227. }
  70228. else {
  70229. soundUrl = rootUrl + soundName;
  70230. }
  70231. var options = {
  70232. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  70233. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  70234. rolloffFactor: parsedSound.rolloffFactor,
  70235. refDistance: parsedSound.refDistance,
  70236. distanceModel: parsedSound.distanceModel,
  70237. playbackRate: parsedSound.playbackRate
  70238. };
  70239. var newSound;
  70240. if (!sourceSound) {
  70241. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  70242. scene._addPendingData(newSound);
  70243. }
  70244. else {
  70245. var setBufferAndRun = function () {
  70246. if (sourceSound._isReadyToPlay) {
  70247. newSound._audioBuffer = sourceSound.getAudioBuffer();
  70248. newSound._isReadyToPlay = true;
  70249. if (newSound.autoplay) {
  70250. newSound.play();
  70251. }
  70252. }
  70253. else {
  70254. window.setTimeout(setBufferAndRun, 300);
  70255. }
  70256. };
  70257. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  70258. setBufferAndRun();
  70259. }
  70260. if (parsedSound.position) {
  70261. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  70262. newSound.setPosition(soundPosition);
  70263. }
  70264. if (parsedSound.isDirectional) {
  70265. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  70266. if (parsedSound.localDirectionToMesh) {
  70267. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  70268. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  70269. }
  70270. }
  70271. if (parsedSound.connectedMeshId) {
  70272. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  70273. if (connectedMesh) {
  70274. newSound.attachToMesh(connectedMesh);
  70275. }
  70276. }
  70277. return newSound;
  70278. };
  70279. return Sound;
  70280. }());
  70281. BABYLON.Sound = Sound;
  70282. })(BABYLON || (BABYLON = {}));
  70283. //# sourceMappingURL=babylon.sound.js.map
  70284. var BABYLON;
  70285. (function (BABYLON) {
  70286. /**
  70287. * It could be useful to isolate your music & sounds on several tracks to better manage volume on a grouped instance of sounds.
  70288. * It will be also used in a future release to apply effects on a specific track.
  70289. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-sound-tracks
  70290. */
  70291. var SoundTrack = /** @class */ (function () {
  70292. /**
  70293. * Creates a new sound track.
  70294. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-sound-tracks
  70295. * @param scene Define the scene the sound track belongs to
  70296. * @param options
  70297. */
  70298. function SoundTrack(scene, options) {
  70299. if (options === void 0) { options = {}; }
  70300. /**
  70301. * The unique identifier of the sound track in the scene.
  70302. */
  70303. this.id = -1;
  70304. this._isMainTrack = false;
  70305. this._isInitialized = false;
  70306. this._scene = scene;
  70307. this.soundCollection = new Array();
  70308. this._options = options;
  70309. if (!this._isMainTrack && this._scene.soundTracks) {
  70310. this._scene.soundTracks.push(this);
  70311. this.id = this._scene.soundTracks.length - 1;
  70312. }
  70313. }
  70314. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  70315. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  70316. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  70317. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  70318. if (this._options) {
  70319. if (this._options.volume) {
  70320. this._outputAudioNode.gain.value = this._options.volume;
  70321. }
  70322. if (this._options.mainTrack) {
  70323. this._isMainTrack = this._options.mainTrack;
  70324. }
  70325. }
  70326. this._isInitialized = true;
  70327. }
  70328. };
  70329. /**
  70330. * Release the sound track and its associated resources
  70331. */
  70332. SoundTrack.prototype.dispose = function () {
  70333. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  70334. if (this._connectedAnalyser) {
  70335. this._connectedAnalyser.stopDebugCanvas();
  70336. }
  70337. while (this.soundCollection.length) {
  70338. this.soundCollection[0].dispose();
  70339. }
  70340. if (this._outputAudioNode) {
  70341. this._outputAudioNode.disconnect();
  70342. }
  70343. this._outputAudioNode = null;
  70344. }
  70345. };
  70346. /**
  70347. * Adds a sound to this sound track
  70348. * @param sound define the cound to add
  70349. * @ignoreNaming
  70350. */
  70351. SoundTrack.prototype.AddSound = function (sound) {
  70352. if (!this._isInitialized) {
  70353. this._initializeSoundTrackAudioGraph();
  70354. }
  70355. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  70356. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  70357. }
  70358. if (sound.soundTrackId) {
  70359. if (sound.soundTrackId === -1) {
  70360. this._scene.mainSoundTrack.RemoveSound(sound);
  70361. }
  70362. else if (this._scene.soundTracks) {
  70363. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  70364. }
  70365. }
  70366. this.soundCollection.push(sound);
  70367. sound.soundTrackId = this.id;
  70368. };
  70369. /**
  70370. * Removes a sound to this sound track
  70371. * @param sound define the cound to remove
  70372. * @ignoreNaming
  70373. */
  70374. SoundTrack.prototype.RemoveSound = function (sound) {
  70375. var index = this.soundCollection.indexOf(sound);
  70376. if (index !== -1) {
  70377. this.soundCollection.splice(index, 1);
  70378. }
  70379. };
  70380. /**
  70381. * Set a global volume for the full sound track.
  70382. * @param newVolume Define the new volume of the sound track
  70383. */
  70384. SoundTrack.prototype.setVolume = function (newVolume) {
  70385. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  70386. this._outputAudioNode.gain.value = newVolume;
  70387. }
  70388. };
  70389. /**
  70390. * Switch the panning model to HRTF:
  70391. * Renders a stereo output of higher quality than equalpower — it uses a convolution with measured impulse responses from human subjects.
  70392. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  70393. */
  70394. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  70395. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  70396. for (var i = 0; i < this.soundCollection.length; i++) {
  70397. this.soundCollection[i].switchPanningModelToHRTF();
  70398. }
  70399. }
  70400. };
  70401. /**
  70402. * Switch the panning model to Equal Power:
  70403. * Represents the equal-power panning algorithm, generally regarded as simple and efficient. equalpower is the default value.
  70404. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  70405. */
  70406. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  70407. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  70408. for (var i = 0; i < this.soundCollection.length; i++) {
  70409. this.soundCollection[i].switchPanningModelToEqualPower();
  70410. }
  70411. }
  70412. };
  70413. /**
  70414. * Connect the sound track to an audio analyser allowing some amazing
  70415. * synchornization between the sounds/music and your visualization (VuMeter for instance).
  70416. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-the-analyser
  70417. * @param analyser The analyser to connect to the engine
  70418. */
  70419. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  70420. if (this._connectedAnalyser) {
  70421. this._connectedAnalyser.stopDebugCanvas();
  70422. }
  70423. this._connectedAnalyser = analyser;
  70424. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  70425. this._outputAudioNode.disconnect();
  70426. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  70427. }
  70428. };
  70429. return SoundTrack;
  70430. }());
  70431. BABYLON.SoundTrack = SoundTrack;
  70432. })(BABYLON || (BABYLON = {}));
  70433. //# sourceMappingURL=babylon.soundtrack.js.map
  70434. var BABYLON;
  70435. (function (BABYLON) {
  70436. /**
  70437. * Class used to work with sound analyzer using fast fourier transform (FFT)
  70438. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  70439. */
  70440. var Analyser = /** @class */ (function () {
  70441. /**
  70442. * Creates a new analyser
  70443. * @param scene defines hosting scene
  70444. */
  70445. function Analyser(scene) {
  70446. /**
  70447. * Gets or sets the smoothing
  70448. * @ignorenaming
  70449. */
  70450. this.SMOOTHING = 0.75;
  70451. /**
  70452. * Gets or sets the FFT table size
  70453. * @ignorenaming
  70454. */
  70455. this.FFT_SIZE = 512;
  70456. /**
  70457. * Gets or sets the bar graph amplitude
  70458. * @ignorenaming
  70459. */
  70460. this.BARGRAPHAMPLITUDE = 256;
  70461. /**
  70462. * Gets or sets the position of the debug canvas
  70463. * @ignorenaming
  70464. */
  70465. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  70466. /**
  70467. * Gets or sets the debug canvas size
  70468. * @ignorenaming
  70469. */
  70470. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  70471. this._scene = scene;
  70472. this._audioEngine = BABYLON.Engine.audioEngine;
  70473. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  70474. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  70475. this._webAudioAnalyser.minDecibels = -140;
  70476. this._webAudioAnalyser.maxDecibels = 0;
  70477. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  70478. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  70479. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  70480. }
  70481. }
  70482. /**
  70483. * Get the number of data values you will have to play with for the visualization
  70484. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  70485. * @returns a number
  70486. */
  70487. Analyser.prototype.getFrequencyBinCount = function () {
  70488. if (this._audioEngine.canUseWebAudio) {
  70489. return this._webAudioAnalyser.frequencyBinCount;
  70490. }
  70491. else {
  70492. return 0;
  70493. }
  70494. };
  70495. /**
  70496. * Gets the current frequency data as a byte array
  70497. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  70498. * @returns a Uint8Array
  70499. */
  70500. Analyser.prototype.getByteFrequencyData = function () {
  70501. if (this._audioEngine.canUseWebAudio) {
  70502. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  70503. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  70504. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  70505. }
  70506. return this._byteFreqs;
  70507. };
  70508. /**
  70509. * Gets the current waveform as a byte array
  70510. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  70511. * @returns a Uint8Array
  70512. */
  70513. Analyser.prototype.getByteTimeDomainData = function () {
  70514. if (this._audioEngine.canUseWebAudio) {
  70515. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  70516. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  70517. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  70518. }
  70519. return this._byteTime;
  70520. };
  70521. /**
  70522. * Gets the current frequency data as a float array
  70523. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  70524. * @returns a Float32Array
  70525. */
  70526. Analyser.prototype.getFloatFrequencyData = function () {
  70527. if (this._audioEngine.canUseWebAudio) {
  70528. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  70529. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  70530. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  70531. }
  70532. return this._floatFreqs;
  70533. };
  70534. /**
  70535. * Renders the debug canvas
  70536. */
  70537. Analyser.prototype.drawDebugCanvas = function () {
  70538. var _this = this;
  70539. if (this._audioEngine.canUseWebAudio) {
  70540. if (!this._debugCanvas) {
  70541. this._debugCanvas = document.createElement("canvas");
  70542. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  70543. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  70544. this._debugCanvas.style.position = "absolute";
  70545. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  70546. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  70547. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  70548. document.body.appendChild(this._debugCanvas);
  70549. this._registerFunc = function () {
  70550. _this.drawDebugCanvas();
  70551. };
  70552. this._scene.registerBeforeRender(this._registerFunc);
  70553. }
  70554. if (this._registerFunc && this._debugCanvasContext) {
  70555. var workingArray = this.getByteFrequencyData();
  70556. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  70557. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  70558. // Draw the frequency domain chart.
  70559. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  70560. var value = workingArray[i];
  70561. var percent = value / this.BARGRAPHAMPLITUDE;
  70562. var height = this.DEBUGCANVASSIZE.height * percent;
  70563. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  70564. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  70565. var hue = i / this.getFrequencyBinCount() * 360;
  70566. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  70567. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  70568. }
  70569. }
  70570. }
  70571. };
  70572. /**
  70573. * Stops rendering the debug canvas and removes it
  70574. */
  70575. Analyser.prototype.stopDebugCanvas = function () {
  70576. if (this._debugCanvas) {
  70577. if (this._registerFunc) {
  70578. this._scene.unregisterBeforeRender(this._registerFunc);
  70579. this._registerFunc = null;
  70580. }
  70581. document.body.removeChild(this._debugCanvas);
  70582. this._debugCanvas = null;
  70583. this._debugCanvasContext = null;
  70584. }
  70585. };
  70586. /**
  70587. * Connects two audio nodes
  70588. * @param inputAudioNode defines first node to connect
  70589. * @param outputAudioNode defines second node to connect
  70590. */
  70591. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  70592. if (this._audioEngine.canUseWebAudio) {
  70593. inputAudioNode.connect(this._webAudioAnalyser);
  70594. this._webAudioAnalyser.connect(outputAudioNode);
  70595. }
  70596. };
  70597. /**
  70598. * Releases all associated resources
  70599. */
  70600. Analyser.prototype.dispose = function () {
  70601. if (this._audioEngine.canUseWebAudio) {
  70602. this._webAudioAnalyser.disconnect();
  70603. }
  70604. };
  70605. return Analyser;
  70606. }());
  70607. BABYLON.Analyser = Analyser;
  70608. })(BABYLON || (BABYLON = {}));
  70609. //# sourceMappingURL=babylon.analyser.js.map
  70610. var BABYLON;
  70611. (function (BABYLON) {
  70612. /**
  70613. * Wraps one or more Sound objects and selects one with random weight for playback.
  70614. */
  70615. var WeightedSound = /** @class */ (function () {
  70616. /**
  70617. * Creates a new WeightedSound from the list of sounds given.
  70618. * @param loop When true a Sound will be selected and played when the current playing Sound completes.
  70619. * @param sounds Array of Sounds that will be selected from.
  70620. * @param weights Array of number values for selection weights; length must equal sounds, values will be normalized to 1
  70621. */
  70622. function WeightedSound(loop, sounds, weights) {
  70623. var _this = this;
  70624. /** When true a Sound will be selected and played when the current playing Sound completes. */
  70625. this.loop = false;
  70626. this._coneInnerAngle = 360;
  70627. this._coneOuterAngle = 360;
  70628. this._volume = 1;
  70629. /** A Sound is currently playing. */
  70630. this.isPlaying = false;
  70631. /** A Sound is currently paused. */
  70632. this.isPaused = false;
  70633. this._sounds = [];
  70634. this._weights = [];
  70635. if (sounds.length !== weights.length) {
  70636. throw new Error('Sounds length does not equal weights length');
  70637. }
  70638. this.loop = loop;
  70639. this._weights = weights;
  70640. // Normalize the weights
  70641. var weightSum = 0;
  70642. for (var _i = 0, weights_1 = weights; _i < weights_1.length; _i++) {
  70643. var weight = weights_1[_i];
  70644. weightSum += weight;
  70645. }
  70646. var invWeightSum = weightSum > 0 ? 1 / weightSum : 0;
  70647. for (var i = 0; i < this._weights.length; i++) {
  70648. this._weights[i] *= invWeightSum;
  70649. }
  70650. this._sounds = sounds;
  70651. for (var _a = 0, _b = this._sounds; _a < _b.length; _a++) {
  70652. var sound = _b[_a];
  70653. sound.onEndedObservable.add(function () { _this._onended(); });
  70654. }
  70655. }
  70656. Object.defineProperty(WeightedSound.prototype, "directionalConeInnerAngle", {
  70657. /**
  70658. * The size of cone in degrees for a directional sound in which there will be no attenuation.
  70659. */
  70660. get: function () {
  70661. return this._coneInnerAngle;
  70662. },
  70663. /**
  70664. * The size of cone in degress for a directional sound in which there will be no attenuation.
  70665. */
  70666. set: function (value) {
  70667. if (value !== this._coneInnerAngle) {
  70668. if (this._coneOuterAngle < value) {
  70669. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  70670. return;
  70671. }
  70672. this._coneInnerAngle = value;
  70673. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  70674. var sound = _a[_i];
  70675. sound.directionalConeInnerAngle = value;
  70676. }
  70677. }
  70678. },
  70679. enumerable: true,
  70680. configurable: true
  70681. });
  70682. Object.defineProperty(WeightedSound.prototype, "directionalConeOuterAngle", {
  70683. /**
  70684. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  70685. * Listener angles between innerAngle and outerAngle will falloff linearly.
  70686. */
  70687. get: function () {
  70688. return this._coneOuterAngle;
  70689. },
  70690. /**
  70691. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  70692. * Listener angles between innerAngle and outerAngle will falloff linearly.
  70693. */
  70694. set: function (value) {
  70695. if (value !== this._coneOuterAngle) {
  70696. if (value < this._coneInnerAngle) {
  70697. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  70698. return;
  70699. }
  70700. this._coneOuterAngle = value;
  70701. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  70702. var sound = _a[_i];
  70703. sound.directionalConeOuterAngle = value;
  70704. }
  70705. }
  70706. },
  70707. enumerable: true,
  70708. configurable: true
  70709. });
  70710. Object.defineProperty(WeightedSound.prototype, "volume", {
  70711. /**
  70712. * Playback volume.
  70713. */
  70714. get: function () {
  70715. return this._volume;
  70716. },
  70717. /**
  70718. * Playback volume.
  70719. */
  70720. set: function (value) {
  70721. if (value !== this._volume) {
  70722. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  70723. var sound = _a[_i];
  70724. sound.setVolume(value);
  70725. }
  70726. }
  70727. },
  70728. enumerable: true,
  70729. configurable: true
  70730. });
  70731. WeightedSound.prototype._onended = function () {
  70732. if (this._currentIndex !== undefined) {
  70733. this._sounds[this._currentIndex].autoplay = false;
  70734. }
  70735. if (this.loop && this.isPlaying) {
  70736. this.play();
  70737. }
  70738. else {
  70739. this.isPlaying = false;
  70740. }
  70741. };
  70742. /**
  70743. * Suspend playback
  70744. */
  70745. WeightedSound.prototype.pause = function () {
  70746. this.isPaused = true;
  70747. if (this._currentIndex !== undefined) {
  70748. this._sounds[this._currentIndex].pause();
  70749. }
  70750. };
  70751. /**
  70752. * Stop playback
  70753. */
  70754. WeightedSound.prototype.stop = function () {
  70755. this.isPlaying = false;
  70756. if (this._currentIndex !== undefined) {
  70757. this._sounds[this._currentIndex].stop();
  70758. }
  70759. };
  70760. /**
  70761. * Start playback.
  70762. * @param startOffset Position the clip head at a specific time in seconds.
  70763. */
  70764. WeightedSound.prototype.play = function (startOffset) {
  70765. if (!this.isPaused) {
  70766. this.stop();
  70767. var randomValue = Math.random();
  70768. var total = 0;
  70769. for (var i = 0; i < this._weights.length; i++) {
  70770. total += this._weights[i];
  70771. if (randomValue <= total) {
  70772. this._currentIndex = i;
  70773. break;
  70774. }
  70775. }
  70776. }
  70777. var sound = this._sounds[this._currentIndex];
  70778. if (sound.isReady()) {
  70779. sound.play(0, this.isPaused ? undefined : startOffset);
  70780. }
  70781. else {
  70782. sound.autoplay = true;
  70783. }
  70784. this.isPlaying = true;
  70785. this.isPaused = false;
  70786. };
  70787. return WeightedSound;
  70788. }());
  70789. BABYLON.WeightedSound = WeightedSound;
  70790. })(BABYLON || (BABYLON = {}));
  70791. //# sourceMappingURL=babylon.weightedsound.js.map
  70792. var BABYLON;
  70793. (function (BABYLON) {
  70794. // Adds the parser to the scene parsers.
  70795. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_AUDIO, function (parsedData, scene, container, rootUrl) {
  70796. // TODO: add sound
  70797. var loadedSounds = [];
  70798. var loadedSound;
  70799. container.sounds = container.sounds || [];
  70800. if (parsedData.sounds !== undefined && parsedData.sounds !== null) {
  70801. for (var index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  70802. var parsedSound = parsedData.sounds[index];
  70803. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  70804. if (!parsedSound.url)
  70805. parsedSound.url = parsedSound.name;
  70806. if (!loadedSounds[parsedSound.url]) {
  70807. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  70808. loadedSounds[parsedSound.url] = loadedSound;
  70809. container.sounds.push(loadedSound);
  70810. }
  70811. else {
  70812. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  70813. }
  70814. }
  70815. else {
  70816. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  70817. }
  70818. }
  70819. }
  70820. loadedSounds = [];
  70821. });
  70822. Object.defineProperty(BABYLON.Scene.prototype, "mainSoundTrack", {
  70823. get: function () {
  70824. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  70825. if (!compo) {
  70826. compo = new AudioSceneComponent(this);
  70827. this._addComponent(compo);
  70828. }
  70829. if (!this._mainSoundTrack) {
  70830. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  70831. }
  70832. return this._mainSoundTrack;
  70833. },
  70834. enumerable: true,
  70835. configurable: true
  70836. });
  70837. BABYLON.Scene.prototype.getSoundByName = function (name) {
  70838. var index;
  70839. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  70840. if (this.mainSoundTrack.soundCollection[index].name === name) {
  70841. return this.mainSoundTrack.soundCollection[index];
  70842. }
  70843. }
  70844. if (this.soundTracks) {
  70845. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  70846. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  70847. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  70848. return this.soundTracks[sdIndex].soundCollection[index];
  70849. }
  70850. }
  70851. }
  70852. }
  70853. return null;
  70854. };
  70855. Object.defineProperty(BABYLON.Scene.prototype, "audioEnabled", {
  70856. get: function () {
  70857. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  70858. if (!compo) {
  70859. compo = new AudioSceneComponent(this);
  70860. this._addComponent(compo);
  70861. }
  70862. return compo.audioEnabled;
  70863. },
  70864. set: function (value) {
  70865. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  70866. if (!compo) {
  70867. compo = new AudioSceneComponent(this);
  70868. this._addComponent(compo);
  70869. }
  70870. if (value) {
  70871. compo.enableAudio();
  70872. }
  70873. else {
  70874. compo.disableAudio();
  70875. }
  70876. },
  70877. enumerable: true,
  70878. configurable: true
  70879. });
  70880. Object.defineProperty(BABYLON.Scene.prototype, "headphone", {
  70881. get: function () {
  70882. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  70883. if (!compo) {
  70884. compo = new AudioSceneComponent(this);
  70885. this._addComponent(compo);
  70886. }
  70887. return compo.headphone;
  70888. },
  70889. set: function (value) {
  70890. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  70891. if (!compo) {
  70892. compo = new AudioSceneComponent(this);
  70893. this._addComponent(compo);
  70894. }
  70895. if (value) {
  70896. compo.switchAudioModeForHeadphones();
  70897. }
  70898. else {
  70899. compo.switchAudioModeForNormalSpeakers();
  70900. }
  70901. },
  70902. enumerable: true,
  70903. configurable: true
  70904. });
  70905. /**
  70906. * Defines the sound scene component responsible to manage any sounds
  70907. * in a given scene.
  70908. */
  70909. var AudioSceneComponent = /** @class */ (function () {
  70910. /**
  70911. * Creates a new instance of the component for the given scene
  70912. * @param scene Defines the scene to register the component in
  70913. */
  70914. function AudioSceneComponent(scene) {
  70915. /**
  70916. * The component name helpfull to identify the component in the list of scene components.
  70917. */
  70918. this.name = BABYLON.SceneComponentConstants.NAME_AUDIO;
  70919. this._audioEnabled = true;
  70920. this._headphone = false;
  70921. this.scene = scene;
  70922. scene.soundTracks = new Array();
  70923. scene.sounds = new Array();
  70924. }
  70925. Object.defineProperty(AudioSceneComponent.prototype, "audioEnabled", {
  70926. /**
  70927. * Gets whether audio is enabled or not.
  70928. * Please use related enable/disable method to switch state.
  70929. */
  70930. get: function () {
  70931. return this._audioEnabled;
  70932. },
  70933. enumerable: true,
  70934. configurable: true
  70935. });
  70936. Object.defineProperty(AudioSceneComponent.prototype, "headphone", {
  70937. /**
  70938. * Gets whether audio is outputing to headphone or not.
  70939. * Please use the according Switch methods to change output.
  70940. */
  70941. get: function () {
  70942. return this._headphone;
  70943. },
  70944. enumerable: true,
  70945. configurable: true
  70946. });
  70947. /**
  70948. * Registers the component in a given scene
  70949. */
  70950. AudioSceneComponent.prototype.register = function () {
  70951. this.scene._afterRenderStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDER_AUDIO, this, this._afterRender);
  70952. };
  70953. /**
  70954. * Rebuilds the elements related to this component in case of
  70955. * context lost for instance.
  70956. */
  70957. AudioSceneComponent.prototype.rebuild = function () {
  70958. // Nothing to do here. (Not rendering related)
  70959. };
  70960. /**
  70961. * Serializes the component data to the specified json object
  70962. * @param serializationObject The object to serialize to
  70963. */
  70964. AudioSceneComponent.prototype.serialize = function (serializationObject) {
  70965. serializationObject.sounds = [];
  70966. if (this.scene.soundTracks) {
  70967. for (var index = 0; index < this.scene.soundTracks.length; index++) {
  70968. var soundtrack = this.scene.soundTracks[index];
  70969. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  70970. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  70971. }
  70972. }
  70973. }
  70974. };
  70975. /**
  70976. * Adds all the element from the container to the scene
  70977. * @param container the container holding the elements
  70978. */
  70979. AudioSceneComponent.prototype.addFromContainer = function (container) {
  70980. var _this = this;
  70981. if (!container.sounds) {
  70982. return;
  70983. }
  70984. container.sounds.forEach(function (sound) {
  70985. sound.play();
  70986. sound.autoplay = true;
  70987. _this.scene.mainSoundTrack.AddSound(sound);
  70988. });
  70989. };
  70990. /**
  70991. * Removes all the elements in the container from the scene
  70992. * @param container contains the elements to remove
  70993. */
  70994. AudioSceneComponent.prototype.removeFromContainer = function (container) {
  70995. var _this = this;
  70996. if (!container.sounds) {
  70997. return;
  70998. }
  70999. container.sounds.forEach(function (sound) {
  71000. sound.stop();
  71001. sound.autoplay = false;
  71002. _this.scene.mainSoundTrack.RemoveSound(sound);
  71003. });
  71004. };
  71005. /**
  71006. * Disposes the component and the associated ressources.
  71007. */
  71008. AudioSceneComponent.prototype.dispose = function () {
  71009. var scene = this.scene;
  71010. if (scene._mainSoundTrack) {
  71011. scene.mainSoundTrack.dispose();
  71012. }
  71013. if (scene.soundTracks) {
  71014. for (var scIndex = 0; scIndex < scene.soundTracks.length; scIndex++) {
  71015. scene.soundTracks[scIndex].dispose();
  71016. }
  71017. }
  71018. };
  71019. /**
  71020. * Disables audio in the associated scene.
  71021. */
  71022. AudioSceneComponent.prototype.disableAudio = function () {
  71023. var scene = this.scene;
  71024. this._audioEnabled = false;
  71025. var i;
  71026. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  71027. scene.mainSoundTrack.soundCollection[i].pause();
  71028. }
  71029. if (scene.soundTracks) {
  71030. for (i = 0; i < scene.soundTracks.length; i++) {
  71031. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  71032. scene.soundTracks[i].soundCollection[j].pause();
  71033. }
  71034. }
  71035. }
  71036. };
  71037. /**
  71038. * Enables audio in the associated scene.
  71039. */
  71040. AudioSceneComponent.prototype.enableAudio = function () {
  71041. var scene = this.scene;
  71042. this._audioEnabled = true;
  71043. var i;
  71044. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  71045. if (scene.mainSoundTrack.soundCollection[i].isPaused) {
  71046. scene.mainSoundTrack.soundCollection[i].play();
  71047. }
  71048. }
  71049. if (scene.soundTracks) {
  71050. for (i = 0; i < scene.soundTracks.length; i++) {
  71051. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  71052. if (scene.soundTracks[i].soundCollection[j].isPaused) {
  71053. scene.soundTracks[i].soundCollection[j].play();
  71054. }
  71055. }
  71056. }
  71057. }
  71058. };
  71059. /**
  71060. * Switch audio to headphone output.
  71061. */
  71062. AudioSceneComponent.prototype.switchAudioModeForHeadphones = function () {
  71063. var scene = this.scene;
  71064. this._headphone = true;
  71065. scene.mainSoundTrack.switchPanningModelToHRTF();
  71066. if (scene.soundTracks) {
  71067. for (var i = 0; i < scene.soundTracks.length; i++) {
  71068. scene.soundTracks[i].switchPanningModelToHRTF();
  71069. }
  71070. }
  71071. };
  71072. /**
  71073. * Switch audio to normal speakers.
  71074. */
  71075. AudioSceneComponent.prototype.switchAudioModeForNormalSpeakers = function () {
  71076. var scene = this.scene;
  71077. this._headphone = false;
  71078. scene.mainSoundTrack.switchPanningModelToEqualPower();
  71079. if (scene.soundTracks) {
  71080. for (var i = 0; i < scene.soundTracks.length; i++) {
  71081. scene.soundTracks[i].switchPanningModelToEqualPower();
  71082. }
  71083. }
  71084. };
  71085. AudioSceneComponent.prototype._afterRender = function () {
  71086. var scene = this.scene;
  71087. if (!this._audioEnabled || !scene._mainSoundTrack || !scene.soundTracks || (scene._mainSoundTrack.soundCollection.length === 0 && scene.soundTracks.length === 1)) {
  71088. return;
  71089. }
  71090. var listeningCamera;
  71091. var audioEngine = BABYLON.Engine.audioEngine;
  71092. if (scene.activeCameras.length > 0) {
  71093. listeningCamera = scene.activeCameras[0];
  71094. }
  71095. else {
  71096. listeningCamera = scene.activeCamera;
  71097. }
  71098. if (listeningCamera && audioEngine.audioContext) {
  71099. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  71100. // for VR cameras
  71101. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  71102. listeningCamera = listeningCamera.rigCameras[0];
  71103. }
  71104. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  71105. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  71106. cameraDirection.normalize();
  71107. // To avoid some errors on GearVR
  71108. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  71109. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  71110. }
  71111. var i;
  71112. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  71113. var sound = scene.mainSoundTrack.soundCollection[i];
  71114. if (sound.useCustomAttenuation) {
  71115. sound.updateDistanceFromListener();
  71116. }
  71117. }
  71118. if (scene.soundTracks) {
  71119. for (i = 0; i < scene.soundTracks.length; i++) {
  71120. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  71121. sound = scene.soundTracks[i].soundCollection[j];
  71122. if (sound.useCustomAttenuation) {
  71123. sound.updateDistanceFromListener();
  71124. }
  71125. }
  71126. }
  71127. }
  71128. }
  71129. };
  71130. return AudioSceneComponent;
  71131. }());
  71132. BABYLON.AudioSceneComponent = AudioSceneComponent;
  71133. })(BABYLON || (BABYLON = {}));
  71134. //# sourceMappingURL=babylon.audioSceneComponent.js.map
  71135. var BABYLON;
  71136. (function (BABYLON) {
  71137. /**
  71138. * This defines an action helpful to play a defined sound on a triggered action.
  71139. */
  71140. var PlaySoundAction = /** @class */ (function (_super) {
  71141. __extends(PlaySoundAction, _super);
  71142. /**
  71143. * Instantiate the action
  71144. * @param triggerOptions defines the trigger options
  71145. * @param sound defines the sound to play
  71146. * @param condition defines the trigger related conditions
  71147. */
  71148. function PlaySoundAction(triggerOptions, sound, condition) {
  71149. var _this = _super.call(this, triggerOptions, condition) || this;
  71150. _this._sound = sound;
  71151. return _this;
  71152. }
  71153. /** @hidden */
  71154. PlaySoundAction.prototype._prepare = function () {
  71155. };
  71156. /**
  71157. * Execute the action and play the sound.
  71158. */
  71159. PlaySoundAction.prototype.execute = function () {
  71160. if (this._sound !== undefined)
  71161. this._sound.play();
  71162. };
  71163. /**
  71164. * Serializes the actions and its related information.
  71165. * @param parent defines the object to serialize in
  71166. * @returns the serialized object
  71167. */
  71168. PlaySoundAction.prototype.serialize = function (parent) {
  71169. return _super.prototype._serialize.call(this, {
  71170. name: "PlaySoundAction",
  71171. properties: [{ name: "sound", value: this._sound.name }]
  71172. }, parent);
  71173. };
  71174. return PlaySoundAction;
  71175. }(BABYLON.Action));
  71176. BABYLON.PlaySoundAction = PlaySoundAction;
  71177. /**
  71178. * This defines an action helpful to stop a defined sound on a triggered action.
  71179. */
  71180. var StopSoundAction = /** @class */ (function (_super) {
  71181. __extends(StopSoundAction, _super);
  71182. /**
  71183. * Instantiate the action
  71184. * @param triggerOptions defines the trigger options
  71185. * @param sound defines the sound to stop
  71186. * @param condition defines the trigger related conditions
  71187. */
  71188. function StopSoundAction(triggerOptions, sound, condition) {
  71189. var _this = _super.call(this, triggerOptions, condition) || this;
  71190. _this._sound = sound;
  71191. return _this;
  71192. }
  71193. /** @hidden */
  71194. StopSoundAction.prototype._prepare = function () {
  71195. };
  71196. /**
  71197. * Execute the action and stop the sound.
  71198. */
  71199. StopSoundAction.prototype.execute = function () {
  71200. if (this._sound !== undefined)
  71201. this._sound.stop();
  71202. };
  71203. /**
  71204. * Serializes the actions and its related information.
  71205. * @param parent defines the object to serialize in
  71206. * @returns the serialized object
  71207. */
  71208. StopSoundAction.prototype.serialize = function (parent) {
  71209. return _super.prototype._serialize.call(this, {
  71210. name: "StopSoundAction",
  71211. properties: [{ name: "sound", value: this._sound.name }]
  71212. }, parent);
  71213. };
  71214. return StopSoundAction;
  71215. }(BABYLON.Action));
  71216. BABYLON.StopSoundAction = StopSoundAction;
  71217. })(BABYLON || (BABYLON = {}));
  71218. //# sourceMappingURL=babylon.directAudioActions.js.map
  71219. var BABYLON;
  71220. (function (BABYLON) {
  71221. /**
  71222. * Class for creating a cube texture
  71223. */
  71224. var CubeTexture = /** @class */ (function (_super) {
  71225. __extends(CubeTexture, _super);
  71226. /**
  71227. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  71228. * as prefiltered data.
  71229. * @param rootUrl defines the url of the texture or the root name of the six images
  71230. * @param scene defines the scene the texture is attached to
  71231. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  71232. * @param noMipmap defines if mipmaps should be created or not
  71233. * @param files defines the six files to load for the different faces
  71234. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  71235. * @param onError defines a callback triggered in case of error during load
  71236. * @param format defines the internal format to use for the texture once loaded
  71237. * @param prefiltered defines whether or not the texture is created from prefiltered data
  71238. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  71239. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  71240. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  71241. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  71242. * @return the cube texture
  71243. */
  71244. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  71245. if (extensions === void 0) { extensions = null; }
  71246. if (noMipmap === void 0) { noMipmap = false; }
  71247. if (files === void 0) { files = null; }
  71248. if (onLoad === void 0) { onLoad = null; }
  71249. if (onError === void 0) { onError = null; }
  71250. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  71251. if (prefiltered === void 0) { prefiltered = false; }
  71252. if (forcedExtension === void 0) { forcedExtension = null; }
  71253. if (createPolynomials === void 0) { createPolynomials = false; }
  71254. if (lodScale === void 0) { lodScale = 0.8; }
  71255. if (lodOffset === void 0) { lodOffset = 0; }
  71256. var _this = _super.call(this, scene) || this;
  71257. /**
  71258. * Gets or sets the center of the bounding box associated with the cube texture.
  71259. * It must define where the camera used to render the texture was set
  71260. * @see http://doc.babylonjs.com/how_to/reflect#using-local-cubemap-mode
  71261. */
  71262. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  71263. _this._rotationY = 0;
  71264. /** @hidden */
  71265. _this._prefiltered = false;
  71266. _this.name = rootUrl;
  71267. _this.url = rootUrl;
  71268. _this._noMipmap = noMipmap;
  71269. _this.hasAlpha = false;
  71270. _this._format = format;
  71271. _this.isCube = true;
  71272. _this._textureMatrix = BABYLON.Matrix.Identity();
  71273. _this._createPolynomials = createPolynomials;
  71274. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  71275. if (!rootUrl && !files) {
  71276. return _this;
  71277. }
  71278. var lastDot = rootUrl.lastIndexOf(".");
  71279. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  71280. var isDDS = (extension === ".dds");
  71281. var isEnv = (extension === ".env");
  71282. if (isEnv) {
  71283. _this.gammaSpace = false;
  71284. _this._prefiltered = false;
  71285. }
  71286. else {
  71287. _this._prefiltered = prefiltered;
  71288. if (prefiltered) {
  71289. _this.gammaSpace = false;
  71290. }
  71291. }
  71292. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  71293. if (!files) {
  71294. if (!isEnv && !isDDS && !extensions) {
  71295. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  71296. }
  71297. files = [];
  71298. if (extensions) {
  71299. for (var index = 0; index < extensions.length; index++) {
  71300. files.push(rootUrl + extensions[index]);
  71301. }
  71302. }
  71303. }
  71304. _this._files = files;
  71305. if (!_this._texture) {
  71306. if (!scene.useDelayedTextureLoading) {
  71307. if (prefiltered) {
  71308. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  71309. }
  71310. else {
  71311. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  71312. }
  71313. }
  71314. else {
  71315. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  71316. }
  71317. }
  71318. else if (onLoad) {
  71319. if (_this._texture.isReady) {
  71320. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  71321. }
  71322. else {
  71323. _this._texture.onLoadedObservable.add(onLoad);
  71324. }
  71325. }
  71326. return _this;
  71327. }
  71328. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  71329. /**
  71330. * Returns the bounding box size
  71331. * @see http://doc.babylonjs.com/how_to/reflect#using-local-cubemap-mode
  71332. */
  71333. get: function () {
  71334. return this._boundingBoxSize;
  71335. },
  71336. /**
  71337. * Gets or sets the size of the bounding box associated with the cube texture
  71338. * When defined, the cubemap will switch to local mode
  71339. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  71340. * @example https://www.babylonjs-playground.com/#RNASML
  71341. */
  71342. set: function (value) {
  71343. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  71344. return;
  71345. }
  71346. this._boundingBoxSize = value;
  71347. var scene = this.getScene();
  71348. if (scene) {
  71349. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  71350. }
  71351. },
  71352. enumerable: true,
  71353. configurable: true
  71354. });
  71355. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  71356. /**
  71357. * Gets texture matrix rotation angle around Y axis radians.
  71358. */
  71359. get: function () {
  71360. return this._rotationY;
  71361. },
  71362. /**
  71363. * Sets texture matrix rotation angle around Y axis in radians.
  71364. */
  71365. set: function (value) {
  71366. this._rotationY = value;
  71367. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  71368. },
  71369. enumerable: true,
  71370. configurable: true
  71371. });
  71372. /**
  71373. * Creates a cube texture from an array of image urls
  71374. * @param files defines an array of image urls
  71375. * @param scene defines the hosting scene
  71376. * @param noMipmap specifies if mip maps are not used
  71377. * @returns a cube texture
  71378. */
  71379. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  71380. var rootUrlKey = "";
  71381. files.forEach(function (url) { return rootUrlKey += url; });
  71382. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  71383. };
  71384. /**
  71385. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  71386. * @param url defines the url of the prefiltered texture
  71387. * @param scene defines the scene the texture is attached to
  71388. * @param forcedExtension defines the extension of the file if different from the url
  71389. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  71390. * @return the prefiltered texture
  71391. */
  71392. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  71393. if (forcedExtension === void 0) { forcedExtension = null; }
  71394. if (createPolynomials === void 0) { createPolynomials = true; }
  71395. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  71396. };
  71397. /**
  71398. * Delays loading of the cube texture
  71399. */
  71400. CubeTexture.prototype.delayLoad = function () {
  71401. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  71402. return;
  71403. }
  71404. var scene = this.getScene();
  71405. if (!scene) {
  71406. return;
  71407. }
  71408. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  71409. this._texture = this._getFromCache(this.url, this._noMipmap);
  71410. if (!this._texture) {
  71411. if (this._prefiltered) {
  71412. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  71413. }
  71414. else {
  71415. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  71416. }
  71417. }
  71418. };
  71419. /**
  71420. * Returns the reflection texture matrix
  71421. * @returns the reflection texture matrix
  71422. */
  71423. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  71424. return this._textureMatrix;
  71425. };
  71426. /**
  71427. * Sets the reflection texture matrix
  71428. * @param value Reflection texture matrix
  71429. */
  71430. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  71431. this._textureMatrix = value;
  71432. };
  71433. /**
  71434. * Parses text to create a cube texture
  71435. * @param parsedTexture define the serialized text to read from
  71436. * @param scene defines the hosting scene
  71437. * @param rootUrl defines the root url of the cube texture
  71438. * @returns a cube texture
  71439. */
  71440. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  71441. var texture = BABYLON.SerializationHelper.Parse(function () {
  71442. var prefiltered = false;
  71443. if (parsedTexture.prefiltered) {
  71444. prefiltered = parsedTexture.prefiltered;
  71445. }
  71446. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  71447. }, parsedTexture, scene);
  71448. // Local Cubemaps
  71449. if (parsedTexture.boundingBoxPosition) {
  71450. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  71451. }
  71452. if (parsedTexture.boundingBoxSize) {
  71453. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  71454. }
  71455. // Animations
  71456. if (parsedTexture.animations) {
  71457. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  71458. var parsedAnimation = parsedTexture.animations[animationIndex];
  71459. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  71460. }
  71461. }
  71462. return texture;
  71463. };
  71464. /**
  71465. * Makes a clone, or deep copy, of the cube texture
  71466. * @returns a new cube texture
  71467. */
  71468. CubeTexture.prototype.clone = function () {
  71469. var _this = this;
  71470. return BABYLON.SerializationHelper.Clone(function () {
  71471. var scene = _this.getScene();
  71472. if (!scene) {
  71473. return _this;
  71474. }
  71475. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  71476. }, this);
  71477. };
  71478. __decorate([
  71479. BABYLON.serialize("rotationY")
  71480. ], CubeTexture.prototype, "rotationY", null);
  71481. return CubeTexture;
  71482. }(BABYLON.BaseTexture));
  71483. BABYLON.CubeTexture = CubeTexture;
  71484. })(BABYLON || (BABYLON = {}));
  71485. //# sourceMappingURL=babylon.cubeTexture.js.map
  71486. var BABYLON;
  71487. (function (BABYLON) {
  71488. /**
  71489. * Raw cube texture where the raw buffers are passed in
  71490. */
  71491. var RawCubeTexture = /** @class */ (function (_super) {
  71492. __extends(RawCubeTexture, _super);
  71493. /**
  71494. * Creates a cube texture where the raw buffers are passed in.
  71495. * @param scene defines the scene the texture is attached to
  71496. * @param data defines the array of data to use to create each face
  71497. * @param size defines the size of the textures
  71498. * @param format defines the format of the data
  71499. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  71500. * @param generateMipMaps defines if the engine should generate the mip levels
  71501. * @param invertY defines if data must be stored with Y axis inverted
  71502. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  71503. * @param compression defines the compression used (null by default)
  71504. */
  71505. function RawCubeTexture(scene, data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  71506. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  71507. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71508. if (generateMipMaps === void 0) { generateMipMaps = false; }
  71509. if (invertY === void 0) { invertY = false; }
  71510. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  71511. if (compression === void 0) { compression = null; }
  71512. var _this = _super.call(this, "", scene) || this;
  71513. _this._texture = scene.getEngine().createRawCubeTexture(data, size, format, type, generateMipMaps, invertY, samplingMode, compression);
  71514. return _this;
  71515. }
  71516. /**
  71517. * Updates the raw cube texture.
  71518. * @param data defines the data to store
  71519. * @param format defines the data format
  71520. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  71521. * @param invertY defines if data must be stored with Y axis inverted
  71522. * @param compression defines the compression used (null by default)
  71523. * @param level defines which level of the texture to update
  71524. */
  71525. RawCubeTexture.prototype.update = function (data, format, type, invertY, compression, level) {
  71526. if (compression === void 0) { compression = null; }
  71527. if (level === void 0) { level = 0; }
  71528. this._texture.getEngine().updateRawCubeTexture(this._texture, data, format, type, invertY, compression);
  71529. };
  71530. /**
  71531. * Updates a raw cube texture with RGBD encoded data.
  71532. * @param data defines the array of data [mipmap][face] to use to create each face
  71533. * @param sphericalPolynomial defines the spherical polynomial for irradiance
  71534. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  71535. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  71536. * @returns a promsie that resolves when the operation is complete
  71537. */
  71538. RawCubeTexture.prototype.updateRGBDAsync = function (data, sphericalPolynomial, lodScale, lodOffset) {
  71539. if (sphericalPolynomial === void 0) { sphericalPolynomial = null; }
  71540. if (lodScale === void 0) { lodScale = 0.8; }
  71541. if (lodOffset === void 0) { lodOffset = 0; }
  71542. return RawCubeTexture._UpdateRGBDAsync(this._texture, data, sphericalPolynomial, lodScale, lodOffset);
  71543. };
  71544. /**
  71545. * Clones the raw cube texture.
  71546. * @return a new cube texture
  71547. */
  71548. RawCubeTexture.prototype.clone = function () {
  71549. var _this = this;
  71550. return BABYLON.SerializationHelper.Clone(function () {
  71551. var scene = _this.getScene();
  71552. var internalTexture = _this._texture;
  71553. var texture = new RawCubeTexture(scene, internalTexture._bufferViewArray, internalTexture.width, internalTexture.format, internalTexture.type, internalTexture.generateMipMaps, internalTexture.invertY, internalTexture.samplingMode, internalTexture._compression);
  71554. if (internalTexture.dataSource === BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD) {
  71555. texture.updateRGBDAsync(internalTexture._bufferViewArrayArray, internalTexture._sphericalPolynomial, internalTexture._lodGenerationScale, internalTexture._lodGenerationOffset);
  71556. }
  71557. return texture;
  71558. }, this);
  71559. };
  71560. /** @hidden */
  71561. RawCubeTexture._UpdateRGBDAsync = function (internalTexture, data, sphericalPolynomial, lodScale, lodOffset) {
  71562. internalTexture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD;
  71563. internalTexture._bufferViewArrayArray = data;
  71564. internalTexture._lodGenerationScale = lodScale;
  71565. internalTexture._lodGenerationOffset = lodOffset;
  71566. internalTexture._sphericalPolynomial = sphericalPolynomial;
  71567. return BABYLON.EnvironmentTextureTools.UploadLevelsAsync(internalTexture, data).then(function () {
  71568. internalTexture.isReady = true;
  71569. });
  71570. };
  71571. return RawCubeTexture;
  71572. }(BABYLON.CubeTexture));
  71573. BABYLON.RawCubeTexture = RawCubeTexture;
  71574. })(BABYLON || (BABYLON = {}));
  71575. //# sourceMappingURL=babylon.rawCubeTexture.js.map
  71576. var BABYLON;
  71577. (function (BABYLON) {
  71578. /**
  71579. * This Helps creating a texture that will be created from a camera in your scene.
  71580. * It is basically a dynamic texture that could be used to create special effects for instance.
  71581. * Actually, It is the base of lot of effects in the framework like post process, shadows, effect layers and rendering pipelines...
  71582. */
  71583. var RenderTargetTexture = /** @class */ (function (_super) {
  71584. __extends(RenderTargetTexture, _super);
  71585. /**
  71586. * Instantiate a render target texture. This is mainly used to render of screen the scene to for instance apply post processse
  71587. * or used a shadow, depth texture...
  71588. * @param name The friendly name of the texture
  71589. * @param size The size of the RTT (number if square, or {width: number, height:number} or {ratio:} to define a ratio from the main scene)
  71590. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  71591. * @param generateMipMaps True if mip maps need to be generated after render.
  71592. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  71593. * @param type The type of the buffer in the RTT (int, half float, float...)
  71594. * @param isCube True if a cube texture needs to be created
  71595. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  71596. * @param generateDepthBuffer True to generate a depth buffer
  71597. * @param generateStencilBuffer True to generate a stencil buffer
  71598. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  71599. * @param format The internal format of the buffer in the RTT (RED, RG, RGB, RGBA, ALPHA...)
  71600. */
  71601. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti, format) {
  71602. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  71603. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71604. if (isCube === void 0) { isCube = false; }
  71605. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  71606. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  71607. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  71608. if (isMulti === void 0) { isMulti = false; }
  71609. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  71610. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  71611. _this.isCube = isCube;
  71612. /**
  71613. * Define if particles should be rendered in your texture.
  71614. */
  71615. _this.renderParticles = true;
  71616. /**
  71617. * Define if sprites should be rendered in your texture.
  71618. */
  71619. _this.renderSprites = false;
  71620. /**
  71621. * Override the default coordinates mode to projection for RTT as it is the most common case for rendered textures.
  71622. */
  71623. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  71624. /**
  71625. * Define if the camera viewport should be respected while rendering the texture or if the render should be done to the entire texture.
  71626. */
  71627. _this.ignoreCameraViewport = false;
  71628. /**
  71629. * An event triggered when the texture is unbind.
  71630. */
  71631. _this.onBeforeBindObservable = new BABYLON.Observable();
  71632. /**
  71633. * An event triggered when the texture is unbind.
  71634. */
  71635. _this.onAfterUnbindObservable = new BABYLON.Observable();
  71636. /**
  71637. * An event triggered before rendering the texture
  71638. */
  71639. _this.onBeforeRenderObservable = new BABYLON.Observable();
  71640. /**
  71641. * An event triggered after rendering the texture
  71642. */
  71643. _this.onAfterRenderObservable = new BABYLON.Observable();
  71644. /**
  71645. * An event triggered after the texture clear
  71646. */
  71647. _this.onClearObservable = new BABYLON.Observable();
  71648. _this._currentRefreshId = -1;
  71649. _this._refreshRate = 1;
  71650. _this._samples = 1;
  71651. /**
  71652. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  71653. * It must define where the camera used to render the texture is set
  71654. */
  71655. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  71656. scene = _this.getScene();
  71657. if (!scene) {
  71658. return _this;
  71659. }
  71660. _this.renderList = new Array();
  71661. _this._engine = scene.getEngine();
  71662. _this.name = name;
  71663. _this.isRenderTarget = true;
  71664. _this._initialSizeParameter = size;
  71665. _this._processSizeParameter(size);
  71666. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  71667. });
  71668. _this._generateMipMaps = generateMipMaps ? true : false;
  71669. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  71670. // Rendering groups
  71671. _this._renderingManager = new BABYLON.RenderingManager(scene);
  71672. _this._renderingManager._useSceneAutoClearSetup = true;
  71673. if (isMulti) {
  71674. return _this;
  71675. }
  71676. _this._renderTargetOptions = {
  71677. generateMipMaps: generateMipMaps,
  71678. type: type,
  71679. format: format,
  71680. samplingMode: samplingMode,
  71681. generateDepthBuffer: generateDepthBuffer,
  71682. generateStencilBuffer: generateStencilBuffer
  71683. };
  71684. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  71685. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71686. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71687. }
  71688. if (isCube) {
  71689. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  71690. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  71691. _this._textureMatrix = BABYLON.Matrix.Identity();
  71692. }
  71693. else {
  71694. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  71695. }
  71696. return _this;
  71697. }
  71698. Object.defineProperty(RenderTargetTexture.prototype, "renderList", {
  71699. /**
  71700. * Use this list to define the list of mesh you want to render.
  71701. */
  71702. get: function () {
  71703. return this._renderList;
  71704. },
  71705. set: function (value) {
  71706. this._renderList = value;
  71707. if (this._renderList) {
  71708. this._hookArray(this._renderList);
  71709. }
  71710. },
  71711. enumerable: true,
  71712. configurable: true
  71713. });
  71714. RenderTargetTexture.prototype._hookArray = function (array) {
  71715. var _this = this;
  71716. var oldPush = array.push;
  71717. array.push = function () {
  71718. var items = [];
  71719. for (var _i = 0; _i < arguments.length; _i++) {
  71720. items[_i] = arguments[_i];
  71721. }
  71722. var wasEmpty = array.length === 0;
  71723. var result = oldPush.apply(array, items);
  71724. if (wasEmpty) {
  71725. _this.getScene().meshes.forEach(function (mesh) {
  71726. mesh._markSubMeshesAsLightDirty();
  71727. });
  71728. }
  71729. return result;
  71730. };
  71731. var oldSplice = array.splice;
  71732. array.splice = function (index, deleteCount) {
  71733. var deleted = oldSplice.apply(array, [index, deleteCount]);
  71734. if (array.length === 0) {
  71735. _this.getScene().meshes.forEach(function (mesh) {
  71736. mesh._markSubMeshesAsLightDirty();
  71737. });
  71738. }
  71739. return deleted;
  71740. };
  71741. };
  71742. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  71743. /**
  71744. * Set a after unbind callback in the texture.
  71745. * This has been kept for backward compatibility and use of onAfterUnbindObservable is recommended.
  71746. */
  71747. set: function (callback) {
  71748. if (this._onAfterUnbindObserver) {
  71749. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  71750. }
  71751. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  71752. },
  71753. enumerable: true,
  71754. configurable: true
  71755. });
  71756. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  71757. /**
  71758. * Set a before render callback in the texture.
  71759. * This has been kept for backward compatibility and use of onBeforeRenderObservable is recommended.
  71760. */
  71761. set: function (callback) {
  71762. if (this._onBeforeRenderObserver) {
  71763. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  71764. }
  71765. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  71766. },
  71767. enumerable: true,
  71768. configurable: true
  71769. });
  71770. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  71771. /**
  71772. * Set a after render callback in the texture.
  71773. * This has been kept for backward compatibility and use of onAfterRenderObservable is recommended.
  71774. */
  71775. set: function (callback) {
  71776. if (this._onAfterRenderObserver) {
  71777. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  71778. }
  71779. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  71780. },
  71781. enumerable: true,
  71782. configurable: true
  71783. });
  71784. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  71785. /**
  71786. * Set a clear callback in the texture.
  71787. * This has been kept for backward compatibility and use of onClearObservable is recommended.
  71788. */
  71789. set: function (callback) {
  71790. if (this._onClearObserver) {
  71791. this.onClearObservable.remove(this._onClearObserver);
  71792. }
  71793. this._onClearObserver = this.onClearObservable.add(callback);
  71794. },
  71795. enumerable: true,
  71796. configurable: true
  71797. });
  71798. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  71799. /**
  71800. * Gets render target creation options that were used.
  71801. */
  71802. get: function () {
  71803. return this._renderTargetOptions;
  71804. },
  71805. enumerable: true,
  71806. configurable: true
  71807. });
  71808. RenderTargetTexture.prototype._onRatioRescale = function () {
  71809. if (this._sizeRatio) {
  71810. this.resize(this._initialSizeParameter);
  71811. }
  71812. };
  71813. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  71814. get: function () {
  71815. return this._boundingBoxSize;
  71816. },
  71817. /**
  71818. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  71819. * When defined, the cubemap will switch to local mode
  71820. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  71821. * @example https://www.babylonjs-playground.com/#RNASML
  71822. */
  71823. set: function (value) {
  71824. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  71825. return;
  71826. }
  71827. this._boundingBoxSize = value;
  71828. var scene = this.getScene();
  71829. if (scene) {
  71830. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  71831. }
  71832. },
  71833. enumerable: true,
  71834. configurable: true
  71835. });
  71836. /**
  71837. * Creates a depth stencil texture.
  71838. * This is only available in WebGL 2 or with the depth texture extension available.
  71839. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  71840. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  71841. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  71842. */
  71843. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  71844. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  71845. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  71846. if (generateStencil === void 0) { generateStencil = false; }
  71847. if (!this.getScene()) {
  71848. return;
  71849. }
  71850. var engine = this.getScene().getEngine();
  71851. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  71852. bilinearFiltering: bilinearFiltering,
  71853. comparisonFunction: comparisonFunction,
  71854. generateStencil: generateStencil,
  71855. isCube: this.isCube
  71856. });
  71857. engine.setFrameBufferDepthStencilTexture(this);
  71858. };
  71859. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  71860. if (size.ratio) {
  71861. this._sizeRatio = size.ratio;
  71862. this._size = {
  71863. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  71864. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  71865. };
  71866. }
  71867. else {
  71868. this._size = size;
  71869. }
  71870. };
  71871. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  71872. /**
  71873. * Define the number of samples to use in case of MSAA.
  71874. * It defaults to one meaning no MSAA has been enabled.
  71875. */
  71876. get: function () {
  71877. return this._samples;
  71878. },
  71879. set: function (value) {
  71880. if (this._samples === value) {
  71881. return;
  71882. }
  71883. var scene = this.getScene();
  71884. if (!scene) {
  71885. return;
  71886. }
  71887. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  71888. },
  71889. enumerable: true,
  71890. configurable: true
  71891. });
  71892. /**
  71893. * Resets the refresh counter of the texture and start bak from scratch.
  71894. * Could be usefull to regenerate the texture if it is setup to render only once.
  71895. */
  71896. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  71897. this._currentRefreshId = -1;
  71898. };
  71899. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  71900. /**
  71901. * Define the refresh rate of the texture or the rendering frequency.
  71902. * Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  71903. */
  71904. get: function () {
  71905. return this._refreshRate;
  71906. },
  71907. set: function (value) {
  71908. this._refreshRate = value;
  71909. this.resetRefreshCounter();
  71910. },
  71911. enumerable: true,
  71912. configurable: true
  71913. });
  71914. /**
  71915. * Adds a post process to the render target rendering passes.
  71916. * @param postProcess define the post process to add
  71917. */
  71918. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  71919. if (!this._postProcessManager) {
  71920. var scene = this.getScene();
  71921. if (!scene) {
  71922. return;
  71923. }
  71924. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  71925. this._postProcesses = new Array();
  71926. }
  71927. this._postProcesses.push(postProcess);
  71928. this._postProcesses[0].autoClear = false;
  71929. };
  71930. /**
  71931. * Clear all the post processes attached to the render target
  71932. * @param dispose define if the cleared post processesshould also be disposed (false by default)
  71933. */
  71934. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  71935. if (dispose === void 0) { dispose = false; }
  71936. if (!this._postProcesses) {
  71937. return;
  71938. }
  71939. if (dispose) {
  71940. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  71941. var postProcess = _a[_i];
  71942. postProcess.dispose();
  71943. }
  71944. }
  71945. this._postProcesses = [];
  71946. };
  71947. /**
  71948. * Remove one of the post process from the list of attached post processes to the texture
  71949. * @param postProcess define the post process to remove from the list
  71950. */
  71951. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  71952. if (!this._postProcesses) {
  71953. return;
  71954. }
  71955. var index = this._postProcesses.indexOf(postProcess);
  71956. if (index === -1) {
  71957. return;
  71958. }
  71959. this._postProcesses.splice(index, 1);
  71960. if (this._postProcesses.length > 0) {
  71961. this._postProcesses[0].autoClear = false;
  71962. }
  71963. };
  71964. /** @hidden */
  71965. RenderTargetTexture.prototype._shouldRender = function () {
  71966. if (this._currentRefreshId === -1) { // At least render once
  71967. this._currentRefreshId = 1;
  71968. return true;
  71969. }
  71970. if (this.refreshRate === this._currentRefreshId) {
  71971. this._currentRefreshId = 1;
  71972. return true;
  71973. }
  71974. this._currentRefreshId++;
  71975. return false;
  71976. };
  71977. /**
  71978. * Gets the actual render size of the texture.
  71979. * @returns the width of the render size
  71980. */
  71981. RenderTargetTexture.prototype.getRenderSize = function () {
  71982. return this.getRenderWidth();
  71983. };
  71984. /**
  71985. * Gets the actual render width of the texture.
  71986. * @returns the width of the render size
  71987. */
  71988. RenderTargetTexture.prototype.getRenderWidth = function () {
  71989. if (this._size.width) {
  71990. return this._size.width;
  71991. }
  71992. return this._size;
  71993. };
  71994. /**
  71995. * Gets the actual render height of the texture.
  71996. * @returns the height of the render size
  71997. */
  71998. RenderTargetTexture.prototype.getRenderHeight = function () {
  71999. if (this._size.width) {
  72000. return this._size.height;
  72001. }
  72002. return this._size;
  72003. };
  72004. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  72005. /**
  72006. * Get if the texture can be rescaled or not.
  72007. */
  72008. get: function () {
  72009. return true;
  72010. },
  72011. enumerable: true,
  72012. configurable: true
  72013. });
  72014. /**
  72015. * Resize the texture using a ratio.
  72016. * @param ratio the ratio to apply to the texture size in order to compute the new target size
  72017. */
  72018. RenderTargetTexture.prototype.scale = function (ratio) {
  72019. var newSize = this.getRenderSize() * ratio;
  72020. this.resize(newSize);
  72021. };
  72022. /**
  72023. * Get the texture reflection matrix used to rotate/transform the reflection.
  72024. * @returns the reflection matrix
  72025. */
  72026. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  72027. if (this.isCube) {
  72028. return this._textureMatrix;
  72029. }
  72030. return _super.prototype.getReflectionTextureMatrix.call(this);
  72031. };
  72032. /**
  72033. * Resize the texture to a new desired size.
  72034. * Be carrefull as it will recreate all the data in the new texture.
  72035. * @param size Define the new size. It can be:
  72036. * - a number for squared texture,
  72037. * - an object containing { width: number, height: number }
  72038. * - or an object containing a ratio { ratio: number }
  72039. */
  72040. RenderTargetTexture.prototype.resize = function (size) {
  72041. this.releaseInternalTexture();
  72042. var scene = this.getScene();
  72043. if (!scene) {
  72044. return;
  72045. }
  72046. this._processSizeParameter(size);
  72047. if (this.isCube) {
  72048. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  72049. }
  72050. else {
  72051. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  72052. }
  72053. };
  72054. /**
  72055. * Renders all the objects from the render list into the texture.
  72056. * @param useCameraPostProcess Define if camera post processes should be used during the rendering
  72057. * @param dumpForDebug Define if the rendering result should be dumped (copied) for debugging purpose
  72058. */
  72059. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  72060. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  72061. if (dumpForDebug === void 0) { dumpForDebug = false; }
  72062. var scene = this.getScene();
  72063. if (!scene) {
  72064. return;
  72065. }
  72066. var engine = scene.getEngine();
  72067. if (this.useCameraPostProcesses !== undefined) {
  72068. useCameraPostProcess = this.useCameraPostProcesses;
  72069. }
  72070. if (this._waitingRenderList) {
  72071. this.renderList = [];
  72072. for (var index = 0; index < this._waitingRenderList.length; index++) {
  72073. var id = this._waitingRenderList[index];
  72074. var mesh_1 = scene.getMeshByID(id);
  72075. if (mesh_1) {
  72076. this.renderList.push(mesh_1);
  72077. }
  72078. }
  72079. delete this._waitingRenderList;
  72080. }
  72081. // Is predicate defined?
  72082. if (this.renderListPredicate) {
  72083. if (this.renderList) {
  72084. this.renderList.splice(0); // Clear previous renderList
  72085. }
  72086. else {
  72087. this.renderList = [];
  72088. }
  72089. var scene = this.getScene();
  72090. if (!scene) {
  72091. return;
  72092. }
  72093. var sceneMeshes = scene.meshes;
  72094. for (var index = 0; index < sceneMeshes.length; index++) {
  72095. var mesh = sceneMeshes[index];
  72096. if (this.renderListPredicate(mesh)) {
  72097. this.renderList.push(mesh);
  72098. }
  72099. }
  72100. }
  72101. this.onBeforeBindObservable.notifyObservers(this);
  72102. // Set custom projection.
  72103. // Needs to be before binding to prevent changing the aspect ratio.
  72104. var camera;
  72105. if (this.activeCamera) {
  72106. camera = this.activeCamera;
  72107. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  72108. if (this.activeCamera !== scene.activeCamera) {
  72109. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  72110. }
  72111. }
  72112. else {
  72113. camera = scene.activeCamera;
  72114. if (camera) {
  72115. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  72116. }
  72117. }
  72118. // Prepare renderingManager
  72119. this._renderingManager.reset();
  72120. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  72121. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  72122. var sceneRenderId = scene.getRenderId();
  72123. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  72124. var mesh = currentRenderList[meshIndex];
  72125. if (mesh) {
  72126. if (!mesh.isReady(this.refreshRate === 0)) {
  72127. this.resetRefreshCounter();
  72128. continue;
  72129. }
  72130. mesh._preActivateForIntermediateRendering(sceneRenderId);
  72131. var isMasked = void 0;
  72132. if (!this.renderList && camera) {
  72133. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  72134. }
  72135. else {
  72136. isMasked = false;
  72137. }
  72138. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  72139. mesh._activate(sceneRenderId);
  72140. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  72141. var subMesh = mesh.subMeshes[subIndex];
  72142. scene._activeIndices.addCount(subMesh.indexCount, false);
  72143. this._renderingManager.dispatch(subMesh, mesh);
  72144. }
  72145. }
  72146. }
  72147. }
  72148. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  72149. var particleSystem = scene.particleSystems[particleIndex];
  72150. var emitter = particleSystem.emitter;
  72151. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  72152. continue;
  72153. }
  72154. if (currentRenderList.indexOf(emitter) >= 0) {
  72155. this._renderingManager.dispatchParticles(particleSystem);
  72156. }
  72157. }
  72158. if (this.isCube) {
  72159. for (var face = 0; face < 6; face++) {
  72160. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  72161. scene.incrementRenderId();
  72162. scene.resetCachedMaterial();
  72163. }
  72164. }
  72165. else {
  72166. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  72167. }
  72168. this.onAfterUnbindObservable.notifyObservers(this);
  72169. if (scene.activeCamera) {
  72170. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  72171. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  72172. }
  72173. engine.setViewport(scene.activeCamera.viewport);
  72174. }
  72175. scene.resetCachedMaterial();
  72176. };
  72177. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  72178. var minimum = 128;
  72179. var x = renderDimension * scale;
  72180. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  72181. // Ensure we don't exceed the render dimension (while staying POT)
  72182. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  72183. };
  72184. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  72185. var _this = this;
  72186. if (!this._texture) {
  72187. return;
  72188. }
  72189. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  72190. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  72191. });
  72192. };
  72193. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  72194. var scene = this.getScene();
  72195. if (!scene) {
  72196. return;
  72197. }
  72198. var engine = scene.getEngine();
  72199. if (!this._texture) {
  72200. return;
  72201. }
  72202. // Bind
  72203. if (this._postProcessManager) {
  72204. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  72205. }
  72206. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  72207. if (this._texture) {
  72208. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  72209. }
  72210. }
  72211. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  72212. // Clear
  72213. if (this.onClearObservable.hasObservers()) {
  72214. this.onClearObservable.notifyObservers(engine);
  72215. }
  72216. else {
  72217. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  72218. }
  72219. if (!this._doNotChangeAspectRatio) {
  72220. scene.updateTransformMatrix(true);
  72221. }
  72222. // Render
  72223. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  72224. if (this._postProcessManager) {
  72225. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  72226. }
  72227. else if (useCameraPostProcess) {
  72228. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  72229. }
  72230. if (!this._doNotChangeAspectRatio) {
  72231. scene.updateTransformMatrix(true);
  72232. }
  72233. // Dump ?
  72234. if (dumpForDebug) {
  72235. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  72236. }
  72237. // Unbind
  72238. if (!this.isCube || faceIndex === 5) {
  72239. if (this.isCube) {
  72240. if (faceIndex === 5) {
  72241. engine.generateMipMapsForCubemap(this._texture);
  72242. }
  72243. }
  72244. this.unbindFrameBuffer(engine, faceIndex);
  72245. }
  72246. else {
  72247. this.onAfterRenderObservable.notifyObservers(faceIndex);
  72248. }
  72249. };
  72250. /**
  72251. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  72252. * This allowed control for front to back rendering or reversly depending of the special needs.
  72253. *
  72254. * @param renderingGroupId The rendering group id corresponding to its index
  72255. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  72256. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  72257. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  72258. */
  72259. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  72260. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  72261. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  72262. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  72263. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  72264. };
  72265. /**
  72266. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  72267. *
  72268. * @param renderingGroupId The rendering group id corresponding to its index
  72269. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  72270. */
  72271. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  72272. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  72273. this._renderingManager._useSceneAutoClearSetup = false;
  72274. };
  72275. /**
  72276. * Clones the texture.
  72277. * @returns the cloned texture
  72278. */
  72279. RenderTargetTexture.prototype.clone = function () {
  72280. var textureSize = this.getSize();
  72281. 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);
  72282. // Base texture
  72283. newTexture.hasAlpha = this.hasAlpha;
  72284. newTexture.level = this.level;
  72285. // RenderTarget Texture
  72286. newTexture.coordinatesMode = this.coordinatesMode;
  72287. if (this.renderList) {
  72288. newTexture.renderList = this.renderList.slice(0);
  72289. }
  72290. return newTexture;
  72291. };
  72292. /**
  72293. * Serialize the texture to a JSON representation we can easily use in the resepective Parse function.
  72294. * @returns The JSON representation of the texture
  72295. */
  72296. RenderTargetTexture.prototype.serialize = function () {
  72297. if (!this.name) {
  72298. return null;
  72299. }
  72300. var serializationObject = _super.prototype.serialize.call(this);
  72301. serializationObject.renderTargetSize = this.getRenderSize();
  72302. serializationObject.renderList = [];
  72303. if (this.renderList) {
  72304. for (var index = 0; index < this.renderList.length; index++) {
  72305. serializationObject.renderList.push(this.renderList[index].id);
  72306. }
  72307. }
  72308. return serializationObject;
  72309. };
  72310. /**
  72311. * This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  72312. */
  72313. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  72314. var objBuffer = this.getInternalTexture();
  72315. var scene = this.getScene();
  72316. if (objBuffer && scene) {
  72317. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  72318. }
  72319. };
  72320. /**
  72321. * Dispose the texture and release its associated resources.
  72322. */
  72323. RenderTargetTexture.prototype.dispose = function () {
  72324. if (this._postProcessManager) {
  72325. this._postProcessManager.dispose();
  72326. this._postProcessManager = null;
  72327. }
  72328. this.clearPostProcesses(true);
  72329. if (this._resizeObserver) {
  72330. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  72331. this._resizeObserver = null;
  72332. }
  72333. this.renderList = null;
  72334. // Remove from custom render targets
  72335. var scene = this.getScene();
  72336. if (!scene) {
  72337. return;
  72338. }
  72339. var index = scene.customRenderTargets.indexOf(this);
  72340. if (index >= 0) {
  72341. scene.customRenderTargets.splice(index, 1);
  72342. }
  72343. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  72344. var camera = _a[_i];
  72345. index = camera.customRenderTargets.indexOf(this);
  72346. if (index >= 0) {
  72347. camera.customRenderTargets.splice(index, 1);
  72348. }
  72349. }
  72350. _super.prototype.dispose.call(this);
  72351. };
  72352. /** @hidden */
  72353. RenderTargetTexture.prototype._rebuild = function () {
  72354. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  72355. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  72356. }
  72357. if (this._postProcessManager) {
  72358. this._postProcessManager._rebuild();
  72359. }
  72360. };
  72361. /**
  72362. * Clear the info related to rendering groups preventing retention point in material dispose.
  72363. */
  72364. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  72365. if (this._renderingManager) {
  72366. this._renderingManager.freeRenderingGroups();
  72367. }
  72368. };
  72369. /**
  72370. * The texture will only be rendered once which can be useful to improve performance if everything in your render is static for instance.
  72371. */
  72372. RenderTargetTexture.REFRESHRATE_RENDER_ONCE = 0;
  72373. /**
  72374. * The texture will only be rendered rendered every frame and is recomended for dynamic contents.
  72375. */
  72376. RenderTargetTexture.REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  72377. /**
  72378. * The texture will be rendered every 2 frames which could be enough if your dynamic objects are not
  72379. * the central point of your effect and can save a lot of performances.
  72380. */
  72381. RenderTargetTexture.REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  72382. return RenderTargetTexture;
  72383. }(BABYLON.Texture));
  72384. BABYLON.RenderTargetTexture = RenderTargetTexture;
  72385. })(BABYLON || (BABYLON = {}));
  72386. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  72387. var BABYLON;
  72388. (function (BABYLON) {
  72389. ;
  72390. /**
  72391. * A multi render target, like a render target provides the ability to render to a texture.
  72392. * Unlike the render target, it can render to several draw buffers in one draw.
  72393. * This is specially interesting in deferred rendering or for any effects requiring more than
  72394. * just one color from a single pass.
  72395. */
  72396. var MultiRenderTarget = /** @class */ (function (_super) {
  72397. __extends(MultiRenderTarget, _super);
  72398. /**
  72399. * Instantiate a new multi render target texture.
  72400. * A multi render target, like a render target provides the ability to render to a texture.
  72401. * Unlike the render target, it can render to several draw buffers in one draw.
  72402. * This is specially interesting in deferred rendering or for any effects requiring more than
  72403. * just one color from a single pass.
  72404. * @param name Define the name of the texture
  72405. * @param size Define the size of the buffers to render to
  72406. * @param count Define the number of target we are rendering into
  72407. * @param scene Define the scene the texture belongs to
  72408. * @param options Define the options used to create the multi render target
  72409. */
  72410. function MultiRenderTarget(name, size, count, scene, options) {
  72411. var _this = this;
  72412. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  72413. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  72414. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  72415. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  72416. _this._engine = scene.getEngine();
  72417. if (!_this.isSupported) {
  72418. _this.dispose();
  72419. return;
  72420. }
  72421. var types = [];
  72422. var samplingModes = [];
  72423. for (var i = 0; i < count; i++) {
  72424. if (options && options.types && options.types[i] !== undefined) {
  72425. types.push(options.types[i]);
  72426. }
  72427. else {
  72428. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  72429. }
  72430. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  72431. samplingModes.push(options.samplingModes[i]);
  72432. }
  72433. else {
  72434. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  72435. }
  72436. }
  72437. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  72438. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  72439. _this._size = size;
  72440. _this._multiRenderTargetOptions = {
  72441. samplingModes: samplingModes,
  72442. generateMipMaps: generateMipMaps,
  72443. generateDepthBuffer: generateDepthBuffer,
  72444. generateStencilBuffer: generateStencilBuffer,
  72445. generateDepthTexture: generateDepthTexture,
  72446. types: types,
  72447. textureCount: count
  72448. };
  72449. _this._createInternalTextures();
  72450. _this._createTextures();
  72451. return _this;
  72452. }
  72453. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  72454. /**
  72455. * Get if draw buffers are currently supported by the used hardware and browser.
  72456. */
  72457. get: function () {
  72458. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  72459. },
  72460. enumerable: true,
  72461. configurable: true
  72462. });
  72463. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  72464. /**
  72465. * Get the list of textures generated by the multi render target.
  72466. */
  72467. get: function () {
  72468. return this._textures;
  72469. },
  72470. enumerable: true,
  72471. configurable: true
  72472. });
  72473. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  72474. /**
  72475. * Get the depth texture generated by the multi render target if options.generateDepthTexture has been set
  72476. */
  72477. get: function () {
  72478. return this._textures[this._textures.length - 1];
  72479. },
  72480. enumerable: true,
  72481. configurable: true
  72482. });
  72483. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  72484. /**
  72485. * Set the wrapping mode on U of all the textures we are rendering to.
  72486. * Can be any of the Texture. (CLAMP_ADDRESSMODE, MIRROR_ADDRESSMODE or WRAP_ADDRESSMODE)
  72487. */
  72488. set: function (wrap) {
  72489. if (this._textures) {
  72490. for (var i = 0; i < this._textures.length; i++) {
  72491. this._textures[i].wrapU = wrap;
  72492. }
  72493. }
  72494. },
  72495. enumerable: true,
  72496. configurable: true
  72497. });
  72498. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  72499. /**
  72500. * Set the wrapping mode on V of all the textures we are rendering to.
  72501. * Can be any of the Texture. (CLAMP_ADDRESSMODE, MIRROR_ADDRESSMODE or WRAP_ADDRESSMODE)
  72502. */
  72503. set: function (wrap) {
  72504. if (this._textures) {
  72505. for (var i = 0; i < this._textures.length; i++) {
  72506. this._textures[i].wrapV = wrap;
  72507. }
  72508. }
  72509. },
  72510. enumerable: true,
  72511. configurable: true
  72512. });
  72513. /** @hidden */
  72514. MultiRenderTarget.prototype._rebuild = function () {
  72515. this.releaseInternalTextures();
  72516. this._createInternalTextures();
  72517. for (var i = 0; i < this._internalTextures.length; i++) {
  72518. var texture = this._textures[i];
  72519. texture._texture = this._internalTextures[i];
  72520. }
  72521. // Keeps references to frame buffer and stencil/depth buffer
  72522. this._texture = this._internalTextures[0];
  72523. };
  72524. MultiRenderTarget.prototype._createInternalTextures = function () {
  72525. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  72526. };
  72527. MultiRenderTarget.prototype._createTextures = function () {
  72528. this._textures = [];
  72529. for (var i = 0; i < this._internalTextures.length; i++) {
  72530. var texture = new BABYLON.Texture(null, this.getScene());
  72531. texture._texture = this._internalTextures[i];
  72532. this._textures.push(texture);
  72533. }
  72534. // Keeps references to frame buffer and stencil/depth buffer
  72535. this._texture = this._internalTextures[0];
  72536. };
  72537. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  72538. /**
  72539. * Define the number of samples used if MSAA is enabled.
  72540. */
  72541. get: function () {
  72542. return this._samples;
  72543. },
  72544. set: function (value) {
  72545. if (this._samples === value) {
  72546. return;
  72547. }
  72548. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  72549. },
  72550. enumerable: true,
  72551. configurable: true
  72552. });
  72553. /**
  72554. * Resize all the textures in the multi render target.
  72555. * Be carrefull as it will recreate all the data in the new texture.
  72556. * @param size Define the new size
  72557. */
  72558. MultiRenderTarget.prototype.resize = function (size) {
  72559. this.releaseInternalTextures();
  72560. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  72561. this._createInternalTextures();
  72562. };
  72563. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  72564. var _this = this;
  72565. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  72566. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  72567. });
  72568. };
  72569. /**
  72570. * Dispose the render targets and their associated resources
  72571. */
  72572. MultiRenderTarget.prototype.dispose = function () {
  72573. this.releaseInternalTextures();
  72574. _super.prototype.dispose.call(this);
  72575. };
  72576. /**
  72577. * Release all the underlying texture used as draw buffers.
  72578. */
  72579. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  72580. if (!this._internalTextures) {
  72581. return;
  72582. }
  72583. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  72584. if (this._internalTextures[i] !== undefined) {
  72585. this._internalTextures[i].dispose();
  72586. this._internalTextures.splice(i, 1);
  72587. }
  72588. }
  72589. };
  72590. return MultiRenderTarget;
  72591. }(BABYLON.RenderTargetTexture));
  72592. BABYLON.MultiRenderTarget = MultiRenderTarget;
  72593. })(BABYLON || (BABYLON = {}));
  72594. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  72595. var BABYLON;
  72596. (function (BABYLON) {
  72597. /**
  72598. * Mirror texture can be used to simulate the view from a mirror in a scene.
  72599. * It will dynamically be rendered every frame to adapt to the camera point of view.
  72600. * You can then easily use it as a reflectionTexture on a flat surface.
  72601. * In case the surface is not a plane, please consider relying on reflection probes.
  72602. * @see https://doc.babylonjs.com/how_to/reflect#mirrors
  72603. */
  72604. var MirrorTexture = /** @class */ (function (_super) {
  72605. __extends(MirrorTexture, _super);
  72606. /**
  72607. * Instantiates a Mirror Texture.
  72608. * Mirror texture can be used to simulate the view from a mirror in a scene.
  72609. * It will dynamically be rendered every frame to adapt to the camera point of view.
  72610. * You can then easily use it as a reflectionTexture on a flat surface.
  72611. * In case the surface is not a plane, please consider relying on reflection probes.
  72612. * @see https://doc.babylonjs.com/how_to/reflect#mirrors
  72613. * @param name
  72614. * @param size
  72615. * @param scene
  72616. * @param generateMipMaps
  72617. * @param type
  72618. * @param samplingMode
  72619. * @param generateDepthBuffer
  72620. */
  72621. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  72622. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72623. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  72624. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  72625. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  72626. _this.scene = scene;
  72627. /**
  72628. * Define the reflection plane we want to use. The mirrorPlane is usually set to the constructed reflector.
  72629. * It is possible to directly set the mirrorPlane by directly using a BABYLON.Plane(a, b, c, d) where a, b and c give the plane normal vector (a, b, c) and d is a scalar displacement from the mirrorPlane to the origin. However in all but the very simplest of situations it is more straight forward to set it to the reflector as stated in the doc.
  72630. * @see https://doc.babylonjs.com/how_to/reflect#mirrors
  72631. */
  72632. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  72633. _this._transformMatrix = BABYLON.Matrix.Zero();
  72634. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  72635. _this._adaptiveBlurKernel = 0;
  72636. _this._blurKernelX = 0;
  72637. _this._blurKernelY = 0;
  72638. _this._blurRatio = 1.0;
  72639. _this.ignoreCameraViewport = true;
  72640. _this._updateGammaSpace();
  72641. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  72642. _this._updateGammaSpace;
  72643. });
  72644. _this.onBeforeRenderObservable.add(function () {
  72645. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  72646. _this._savedViewMatrix = scene.getViewMatrix();
  72647. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  72648. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  72649. scene.clipPlane = _this.mirrorPlane;
  72650. scene.getEngine().cullBackFaces = false;
  72651. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  72652. });
  72653. _this.onAfterRenderObservable.add(function () {
  72654. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  72655. scene.getEngine().cullBackFaces = true;
  72656. scene._mirroredCameraPosition = null;
  72657. delete scene.clipPlane;
  72658. });
  72659. return _this;
  72660. }
  72661. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  72662. get: function () {
  72663. return this._blurRatio;
  72664. },
  72665. /**
  72666. * Define the blur ratio used to blur the reflection if needed.
  72667. */
  72668. set: function (value) {
  72669. if (this._blurRatio === value) {
  72670. return;
  72671. }
  72672. this._blurRatio = value;
  72673. this._preparePostProcesses();
  72674. },
  72675. enumerable: true,
  72676. configurable: true
  72677. });
  72678. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  72679. /**
  72680. * Define the adaptive blur kernel used to blur the reflection if needed.
  72681. * This will autocompute the closest best match for the `blurKernel`
  72682. */
  72683. set: function (value) {
  72684. this._adaptiveBlurKernel = value;
  72685. this._autoComputeBlurKernel();
  72686. },
  72687. enumerable: true,
  72688. configurable: true
  72689. });
  72690. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  72691. /**
  72692. * Define the blur kernel used to blur the reflection if needed.
  72693. * Please consider using `adaptiveBlurKernel` as it could find the closest best value for you.
  72694. */
  72695. set: function (value) {
  72696. this.blurKernelX = value;
  72697. this.blurKernelY = value;
  72698. },
  72699. enumerable: true,
  72700. configurable: true
  72701. });
  72702. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  72703. get: function () {
  72704. return this._blurKernelX;
  72705. },
  72706. /**
  72707. * Define the blur kernel on the X Axis used to blur the reflection if needed.
  72708. * Please consider using `adaptiveBlurKernel` as it could find the closest best value for you.
  72709. */
  72710. set: function (value) {
  72711. if (this._blurKernelX === value) {
  72712. return;
  72713. }
  72714. this._blurKernelX = value;
  72715. this._preparePostProcesses();
  72716. },
  72717. enumerable: true,
  72718. configurable: true
  72719. });
  72720. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  72721. get: function () {
  72722. return this._blurKernelY;
  72723. },
  72724. /**
  72725. * Define the blur kernel on the Y Axis used to blur the reflection if needed.
  72726. * Please consider using `adaptiveBlurKernel` as it could find the closest best value for you.
  72727. */
  72728. set: function (value) {
  72729. if (this._blurKernelY === value) {
  72730. return;
  72731. }
  72732. this._blurKernelY = value;
  72733. this._preparePostProcesses();
  72734. },
  72735. enumerable: true,
  72736. configurable: true
  72737. });
  72738. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  72739. var engine = this.getScene().getEngine();
  72740. var dw = this.getRenderWidth() / engine.getRenderWidth();
  72741. var dh = this.getRenderHeight() / engine.getRenderHeight();
  72742. this.blurKernelX = this._adaptiveBlurKernel * dw;
  72743. this.blurKernelY = this._adaptiveBlurKernel * dh;
  72744. };
  72745. MirrorTexture.prototype._onRatioRescale = function () {
  72746. if (this._sizeRatio) {
  72747. this.resize(this._initialSizeParameter);
  72748. if (!this._adaptiveBlurKernel) {
  72749. this._preparePostProcesses();
  72750. }
  72751. }
  72752. if (this._adaptiveBlurKernel) {
  72753. this._autoComputeBlurKernel();
  72754. }
  72755. };
  72756. MirrorTexture.prototype._updateGammaSpace = function () {
  72757. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  72758. };
  72759. MirrorTexture.prototype._preparePostProcesses = function () {
  72760. this.clearPostProcesses(true);
  72761. if (this._blurKernelX && this._blurKernelY) {
  72762. var engine = this.getScene().getEngine();
  72763. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  72764. 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);
  72765. this._blurX.autoClear = false;
  72766. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  72767. this._blurX.inputTexture = this._texture;
  72768. }
  72769. else {
  72770. this._blurX.alwaysForcePOT = true;
  72771. }
  72772. 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);
  72773. this._blurY.autoClear = false;
  72774. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  72775. this.addPostProcess(this._blurX);
  72776. this.addPostProcess(this._blurY);
  72777. }
  72778. else {
  72779. if (this._blurY) {
  72780. this.removePostProcess(this._blurY);
  72781. this._blurY.dispose();
  72782. this._blurY = null;
  72783. }
  72784. if (this._blurX) {
  72785. this.removePostProcess(this._blurX);
  72786. this._blurX.dispose();
  72787. this._blurX = null;
  72788. }
  72789. }
  72790. };
  72791. /**
  72792. * Clone the mirror texture.
  72793. * @returns the cloned texture
  72794. */
  72795. MirrorTexture.prototype.clone = function () {
  72796. var scene = this.getScene();
  72797. if (!scene) {
  72798. return this;
  72799. }
  72800. var textureSize = this.getSize();
  72801. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  72802. // Base texture
  72803. newTexture.hasAlpha = this.hasAlpha;
  72804. newTexture.level = this.level;
  72805. // Mirror Texture
  72806. newTexture.mirrorPlane = this.mirrorPlane.clone();
  72807. if (this.renderList) {
  72808. newTexture.renderList = this.renderList.slice(0);
  72809. }
  72810. return newTexture;
  72811. };
  72812. /**
  72813. * Serialize the texture to a JSON representation you could use in Parse later on
  72814. * @returns the serialized JSON representation
  72815. */
  72816. MirrorTexture.prototype.serialize = function () {
  72817. if (!this.name) {
  72818. return null;
  72819. }
  72820. var serializationObject = _super.prototype.serialize.call(this);
  72821. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  72822. return serializationObject;
  72823. };
  72824. /**
  72825. * Dispose the texture and release its associated resources.
  72826. */
  72827. MirrorTexture.prototype.dispose = function () {
  72828. _super.prototype.dispose.call(this);
  72829. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  72830. };
  72831. return MirrorTexture;
  72832. }(BABYLON.RenderTargetTexture));
  72833. BABYLON.MirrorTexture = MirrorTexture;
  72834. })(BABYLON || (BABYLON = {}));
  72835. //# sourceMappingURL=babylon.mirrorTexture.js.map
  72836. var BABYLON;
  72837. (function (BABYLON) {
  72838. /**
  72839. * Creates a refraction texture used by refraction channel of the standard material.
  72840. * It is like a mirror but to see through a material.
  72841. * @see https://doc.babylonjs.com/how_to/reflect#refraction
  72842. */
  72843. var RefractionTexture = /** @class */ (function (_super) {
  72844. __extends(RefractionTexture, _super);
  72845. /**
  72846. * Creates a refraction texture used by refraction channel of the standard material.
  72847. * It is like a mirror but to see through a material.
  72848. * @see https://doc.babylonjs.com/how_to/reflect#refraction
  72849. * @param name Define the texture name
  72850. * @param size Define the size of the underlying texture
  72851. * @param scene Define the scene the refraction belongs to
  72852. * @param generateMipMaps Define if we need to generate mips level for the refraction
  72853. */
  72854. function RefractionTexture(name, size, scene, generateMipMaps) {
  72855. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  72856. /**
  72857. * Define the reflection plane we want to use. The refractionPlane is usually set to the constructed refractor.
  72858. * It is possible to directly set the refractionPlane by directly using a BABYLON.Plane(a, b, c, d) where a, b and c give the plane normal vector (a, b, c) and d is a scalar displacement from the refractionPlane to the origin. However in all but the very simplest of situations it is more straight forward to set it to the refractor as stated in the doc.
  72859. * @see https://doc.babylonjs.com/how_to/reflect#refraction
  72860. */
  72861. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  72862. /**
  72863. * Define how deep under the surface we should see.
  72864. */
  72865. _this.depth = 2.0;
  72866. _this.onBeforeRenderObservable.add(function () {
  72867. scene.clipPlane = _this.refractionPlane;
  72868. });
  72869. _this.onAfterRenderObservable.add(function () {
  72870. delete scene.clipPlane;
  72871. });
  72872. return _this;
  72873. }
  72874. /**
  72875. * Clone the refraction texture.
  72876. * @returns the cloned texture
  72877. */
  72878. RefractionTexture.prototype.clone = function () {
  72879. var scene = this.getScene();
  72880. if (!scene) {
  72881. return this;
  72882. }
  72883. var textureSize = this.getSize();
  72884. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  72885. // Base texture
  72886. newTexture.hasAlpha = this.hasAlpha;
  72887. newTexture.level = this.level;
  72888. // Refraction Texture
  72889. newTexture.refractionPlane = this.refractionPlane.clone();
  72890. if (this.renderList) {
  72891. newTexture.renderList = this.renderList.slice(0);
  72892. }
  72893. newTexture.depth = this.depth;
  72894. return newTexture;
  72895. };
  72896. /**
  72897. * Serialize the texture to a JSON representation you could use in Parse later on
  72898. * @returns the serialized JSON representation
  72899. */
  72900. RefractionTexture.prototype.serialize = function () {
  72901. if (!this.name) {
  72902. return null;
  72903. }
  72904. var serializationObject = _super.prototype.serialize.call(this);
  72905. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  72906. serializationObject.depth = this.depth;
  72907. return serializationObject;
  72908. };
  72909. return RefractionTexture;
  72910. }(BABYLON.RenderTargetTexture));
  72911. BABYLON.RefractionTexture = RefractionTexture;
  72912. })(BABYLON || (BABYLON = {}));
  72913. //# sourceMappingURL=babylon.refractionTexture.js.map
  72914. var BABYLON;
  72915. (function (BABYLON) {
  72916. /**
  72917. * A class extending {BABYLON.Texture} allowing drawing on a texture
  72918. * @see http://doc.babylonjs.com/how_to/dynamictexture
  72919. */
  72920. var DynamicTexture = /** @class */ (function (_super) {
  72921. __extends(DynamicTexture, _super);
  72922. /**
  72923. * Creates a {BABYLON.DynamicTexture}
  72924. * @param name defines the name of the texture
  72925. * @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
  72926. * @param scene defines the scene where you want the texture
  72927. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  72928. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  72929. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  72930. */
  72931. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  72932. if (scene === void 0) { scene = null; }
  72933. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  72934. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  72935. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  72936. _this.name = name;
  72937. _this._engine = _this.getScene().getEngine();
  72938. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72939. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72940. _this._generateMipMaps = generateMipMaps;
  72941. if (options.getContext) {
  72942. _this._canvas = options;
  72943. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  72944. }
  72945. else {
  72946. _this._canvas = document.createElement("canvas");
  72947. if (options.width || options.width === 0) {
  72948. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  72949. }
  72950. else {
  72951. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  72952. }
  72953. }
  72954. var textureSize = _this.getSize();
  72955. _this._canvas.width = textureSize.width;
  72956. _this._canvas.height = textureSize.height;
  72957. _this._context = _this._canvas.getContext("2d");
  72958. return _this;
  72959. }
  72960. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  72961. /**
  72962. * Gets the current state of canRescale
  72963. */
  72964. get: function () {
  72965. return true;
  72966. },
  72967. enumerable: true,
  72968. configurable: true
  72969. });
  72970. DynamicTexture.prototype._recreate = function (textureSize) {
  72971. this._canvas.width = textureSize.width;
  72972. this._canvas.height = textureSize.height;
  72973. this.releaseInternalTexture();
  72974. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  72975. };
  72976. /**
  72977. * Scales the texture
  72978. * @param ratio the scale factor to apply to both width and height
  72979. */
  72980. DynamicTexture.prototype.scale = function (ratio) {
  72981. var textureSize = this.getSize();
  72982. textureSize.width *= ratio;
  72983. textureSize.height *= ratio;
  72984. this._recreate(textureSize);
  72985. };
  72986. /**
  72987. * Resizes the texture
  72988. * @param width the new width
  72989. * @param height the new height
  72990. */
  72991. DynamicTexture.prototype.scaleTo = function (width, height) {
  72992. var textureSize = this.getSize();
  72993. textureSize.width = width;
  72994. textureSize.height = height;
  72995. this._recreate(textureSize);
  72996. };
  72997. /**
  72998. * Gets the context of the canvas used by the texture
  72999. * @returns the canvas context of the dynamic texture
  73000. */
  73001. DynamicTexture.prototype.getContext = function () {
  73002. return this._context;
  73003. };
  73004. /**
  73005. * Clears the texture
  73006. */
  73007. DynamicTexture.prototype.clear = function () {
  73008. var size = this.getSize();
  73009. this._context.fillRect(0, 0, size.width, size.height);
  73010. };
  73011. /**
  73012. * Updates the texture
  73013. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  73014. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  73015. */
  73016. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  73017. if (premulAlpha === void 0) { premulAlpha = false; }
  73018. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  73019. };
  73020. /**
  73021. * Draws text onto the texture
  73022. * @param text defines the text to be drawn
  73023. * @param x defines the placement of the text from the left
  73024. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  73025. * @param font defines the font to be used with font-style, font-size, font-name
  73026. * @param color defines the color used for the text
  73027. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  73028. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  73029. * @param update defines whether texture is immediately update (default is true)
  73030. */
  73031. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  73032. if (update === void 0) { update = true; }
  73033. var size = this.getSize();
  73034. if (clearColor) {
  73035. this._context.fillStyle = clearColor;
  73036. this._context.fillRect(0, 0, size.width, size.height);
  73037. }
  73038. this._context.font = font;
  73039. if (x === null || x === undefined) {
  73040. var textSize = this._context.measureText(text);
  73041. x = (size.width - textSize.width) / 2;
  73042. }
  73043. if (y === null || y === undefined) {
  73044. var fontSize = parseInt((font.replace(/\D/g, '')));
  73045. y = (size.height / 2) + (fontSize / 3.65);
  73046. }
  73047. this._context.fillStyle = color;
  73048. this._context.fillText(text, x, y);
  73049. if (update) {
  73050. this.update(invertY);
  73051. }
  73052. };
  73053. /**
  73054. * Clones the texture
  73055. * @returns the clone of the texture.
  73056. */
  73057. DynamicTexture.prototype.clone = function () {
  73058. var scene = this.getScene();
  73059. if (!scene) {
  73060. return this;
  73061. }
  73062. var textureSize = this.getSize();
  73063. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  73064. // Base texture
  73065. newTexture.hasAlpha = this.hasAlpha;
  73066. newTexture.level = this.level;
  73067. // Dynamic Texture
  73068. newTexture.wrapU = this.wrapU;
  73069. newTexture.wrapV = this.wrapV;
  73070. return newTexture;
  73071. };
  73072. /**
  73073. * Serializes the dynamic texture. The scene should be ready before the dynamic texture is serialized
  73074. * @returns a serialized dynamic texture object
  73075. */
  73076. DynamicTexture.prototype.serialize = function () {
  73077. var scene = this.getScene();
  73078. if (scene && !scene.isReady()) {
  73079. BABYLON.Tools.Warn("The scene must be ready before serializing the dynamic texture");
  73080. }
  73081. var serializationObject = _super.prototype.serialize.call(this);
  73082. serializationObject.base64String = this._canvas.toDataURL();
  73083. serializationObject.invertY = this._invertY;
  73084. serializationObject.samplingMode = this.samplingMode;
  73085. return serializationObject;
  73086. };
  73087. /** @hidden */
  73088. DynamicTexture.prototype._rebuild = function () {
  73089. this.update();
  73090. };
  73091. return DynamicTexture;
  73092. }(BABYLON.Texture));
  73093. BABYLON.DynamicTexture = DynamicTexture;
  73094. })(BABYLON || (BABYLON = {}));
  73095. //# sourceMappingURL=babylon.dynamicTexture.js.map
  73096. var BABYLON;
  73097. (function (BABYLON) {
  73098. /**
  73099. * If you want to display a video in your scene, this is the special texture for that.
  73100. * This special texture works similar to other textures, with the exception of a few parameters.
  73101. * @see https://doc.babylonjs.com/how_to/video_texture
  73102. */
  73103. var VideoTexture = /** @class */ (function (_super) {
  73104. __extends(VideoTexture, _super);
  73105. /**
  73106. * Creates a video texture.
  73107. * If you want to display a video in your scene, this is the special texture for that.
  73108. * This special texture works similar to other textures, with the exception of a few parameters.
  73109. * @see https://doc.babylonjs.com/how_to/video_texture
  73110. * @param {string | null} name optional name, will detect from video source, if not defined
  73111. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  73112. * @param {BABYLON.Scene} scene is obviously the current scene.
  73113. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  73114. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  73115. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  73116. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  73117. */
  73118. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  73119. if (generateMipMaps === void 0) { generateMipMaps = false; }
  73120. if (invertY === void 0) { invertY = false; }
  73121. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  73122. if (settings === void 0) { settings = {
  73123. autoPlay: true,
  73124. loop: true,
  73125. autoUpdateTexture: true,
  73126. }; }
  73127. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  73128. _this._onUserActionRequestedObservable = null;
  73129. _this._stillImageCaptured = false;
  73130. _this._poster = false;
  73131. _this._createInternalTexture = function () {
  73132. if (_this._texture != null) {
  73133. if (_this._poster) {
  73134. _this._texture.dispose();
  73135. _this._poster = false;
  73136. }
  73137. else {
  73138. return;
  73139. }
  73140. }
  73141. if (!_this._engine.needPOTTextures ||
  73142. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  73143. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73144. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73145. }
  73146. else {
  73147. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73148. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73149. _this._generateMipMaps = false;
  73150. }
  73151. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  73152. if (!_this.video.autoplay) {
  73153. var oldHandler_1 = _this.video.onplaying;
  73154. var error_1 = false;
  73155. _this.video.onplaying = function () {
  73156. _this.video.onplaying = oldHandler_1;
  73157. _this._texture.isReady = true;
  73158. _this._updateInternalTexture();
  73159. if (!error_1) {
  73160. _this.video.pause();
  73161. }
  73162. if (_this.onLoadObservable.hasObservers()) {
  73163. _this.onLoadObservable.notifyObservers(_this);
  73164. }
  73165. };
  73166. var playing = _this.video.play();
  73167. if (playing) {
  73168. playing.then(function () {
  73169. // Everything is good.
  73170. })
  73171. .catch(function () {
  73172. error_1 = true;
  73173. // On Chrome for instance, new policies might prevent playing without user interaction.
  73174. if (_this._onUserActionRequestedObservable && _this._onUserActionRequestedObservable.hasObservers()) {
  73175. _this._onUserActionRequestedObservable.notifyObservers(_this);
  73176. }
  73177. });
  73178. }
  73179. else {
  73180. _this.video.onplaying = oldHandler_1;
  73181. _this._texture.isReady = true;
  73182. _this._updateInternalTexture();
  73183. if (_this.onLoadObservable.hasObservers()) {
  73184. _this.onLoadObservable.notifyObservers(_this);
  73185. }
  73186. }
  73187. }
  73188. else {
  73189. _this._texture.isReady = true;
  73190. _this._updateInternalTexture();
  73191. if (_this.onLoadObservable.hasObservers()) {
  73192. _this.onLoadObservable.notifyObservers(_this);
  73193. }
  73194. }
  73195. };
  73196. _this.reset = function () {
  73197. if (_this._texture == null) {
  73198. return;
  73199. }
  73200. if (!_this._poster) {
  73201. _this._texture.dispose();
  73202. _this._texture = null;
  73203. }
  73204. };
  73205. _this._updateInternalTexture = function (e) {
  73206. if (_this._texture == null || !_this._texture.isReady) {
  73207. return;
  73208. }
  73209. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  73210. return;
  73211. }
  73212. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  73213. };
  73214. _this._engine = _this.getScene().getEngine();
  73215. _this._generateMipMaps = generateMipMaps;
  73216. _this._samplingMode = samplingMode;
  73217. _this.autoUpdateTexture = settings.autoUpdateTexture;
  73218. _this.name = name || _this._getName(src);
  73219. _this.video = _this._getVideo(src);
  73220. if (settings.poster) {
  73221. _this.video.poster = settings.poster;
  73222. }
  73223. if (settings.autoPlay !== undefined) {
  73224. _this.video.autoplay = settings.autoPlay;
  73225. }
  73226. if (settings.loop !== undefined) {
  73227. _this.video.loop = settings.loop;
  73228. }
  73229. _this.video.setAttribute("playsinline", "");
  73230. _this.video.addEventListener("canplay", _this._createInternalTexture);
  73231. _this.video.addEventListener("paused", _this._updateInternalTexture);
  73232. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  73233. _this.video.addEventListener("emptied", _this.reset);
  73234. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  73235. _this._createInternalTexture();
  73236. }
  73237. if (settings.poster) {
  73238. _this._texture = _this._engine.createTexture(settings.poster, false, true, scene);
  73239. _this._poster = true;
  73240. }
  73241. return _this;
  73242. }
  73243. Object.defineProperty(VideoTexture.prototype, "onUserActionRequestedObservable", {
  73244. /**
  73245. * Event triggerd when a dom action is required by the user to play the video.
  73246. * This happens due to recent changes in browser policies preventing video to auto start.
  73247. */
  73248. get: function () {
  73249. if (!this._onUserActionRequestedObservable) {
  73250. this._onUserActionRequestedObservable = new BABYLON.Observable();
  73251. }
  73252. return this._onUserActionRequestedObservable;
  73253. },
  73254. enumerable: true,
  73255. configurable: true
  73256. });
  73257. VideoTexture.prototype._getName = function (src) {
  73258. if (src instanceof HTMLVideoElement) {
  73259. return src.currentSrc;
  73260. }
  73261. if (typeof src === "object") {
  73262. return src.toString();
  73263. }
  73264. return src;
  73265. };
  73266. ;
  73267. VideoTexture.prototype._getVideo = function (src) {
  73268. if (src instanceof HTMLVideoElement) {
  73269. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  73270. return src;
  73271. }
  73272. var video = document.createElement("video");
  73273. if (typeof src === "string") {
  73274. BABYLON.Tools.SetCorsBehavior(src, video);
  73275. video.src = src;
  73276. }
  73277. else {
  73278. BABYLON.Tools.SetCorsBehavior(src[0], video);
  73279. src.forEach(function (url) {
  73280. var source = document.createElement("source");
  73281. source.src = url;
  73282. video.appendChild(source);
  73283. });
  73284. }
  73285. return video;
  73286. };
  73287. ;
  73288. /**
  73289. * @hidden Internal method to initiate `update`.
  73290. */
  73291. VideoTexture.prototype._rebuild = function () {
  73292. this.update();
  73293. };
  73294. /**
  73295. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  73296. */
  73297. VideoTexture.prototype.update = function () {
  73298. if (!this.autoUpdateTexture) {
  73299. // Expecting user to call `updateTexture` manually
  73300. return;
  73301. }
  73302. this.updateTexture(true);
  73303. };
  73304. /**
  73305. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  73306. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  73307. */
  73308. VideoTexture.prototype.updateTexture = function (isVisible) {
  73309. if (!isVisible) {
  73310. return;
  73311. }
  73312. if (this.video.paused && this._stillImageCaptured) {
  73313. return;
  73314. }
  73315. this._stillImageCaptured = true;
  73316. this._updateInternalTexture();
  73317. };
  73318. /**
  73319. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  73320. * @param url New url.
  73321. */
  73322. VideoTexture.prototype.updateURL = function (url) {
  73323. this.video.src = url;
  73324. };
  73325. /**
  73326. * Dispose the texture and release its associated resources.
  73327. */
  73328. VideoTexture.prototype.dispose = function () {
  73329. _super.prototype.dispose.call(this);
  73330. if (this._onUserActionRequestedObservable) {
  73331. this._onUserActionRequestedObservable.clear();
  73332. this._onUserActionRequestedObservable = null;
  73333. }
  73334. this.video.removeEventListener("canplay", this._createInternalTexture);
  73335. this.video.removeEventListener("paused", this._updateInternalTexture);
  73336. this.video.removeEventListener("seeked", this._updateInternalTexture);
  73337. this.video.removeEventListener("emptied", this.reset);
  73338. this.video.pause();
  73339. };
  73340. /**
  73341. * Creates a video texture straight from your WebCam video feed.
  73342. * @param scene Define the scene the texture should be created in
  73343. * @param onReady Define a callback to triggered once the texture will be ready
  73344. * @param constraints Define the constraints to use to create the web cam feed from WebRTC
  73345. */
  73346. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  73347. var video = document.createElement("video");
  73348. video.setAttribute('autoplay', '');
  73349. video.setAttribute('muted', '');
  73350. video.setAttribute('playsinline', '');
  73351. var constraintsDeviceId;
  73352. if (constraints && constraints.deviceId) {
  73353. constraintsDeviceId = {
  73354. exact: constraints.deviceId,
  73355. };
  73356. }
  73357. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  73358. if (navigator.mediaDevices) {
  73359. navigator.mediaDevices.getUserMedia({ video: constraints })
  73360. .then(function (stream) {
  73361. if (video.mozSrcObject !== undefined) {
  73362. // hack for Firefox < 19
  73363. video.mozSrcObject = stream;
  73364. }
  73365. else {
  73366. video.srcObject = stream;
  73367. }
  73368. var onPlaying = function () {
  73369. if (onReady) {
  73370. onReady(new VideoTexture("video", video, scene, true, true));
  73371. }
  73372. video.removeEventListener("playing", onPlaying);
  73373. };
  73374. video.addEventListener("playing", onPlaying);
  73375. video.play();
  73376. })
  73377. .catch(function (err) {
  73378. BABYLON.Tools.Error(err.name);
  73379. });
  73380. }
  73381. else {
  73382. navigator.getUserMedia =
  73383. navigator.getUserMedia ||
  73384. navigator.webkitGetUserMedia ||
  73385. navigator.mozGetUserMedia ||
  73386. navigator.msGetUserMedia;
  73387. if (navigator.getUserMedia) {
  73388. navigator.getUserMedia({
  73389. video: {
  73390. deviceId: constraintsDeviceId,
  73391. width: {
  73392. min: (constraints && constraints.minWidth) || 256,
  73393. max: (constraints && constraints.maxWidth) || 640,
  73394. },
  73395. height: {
  73396. min: (constraints && constraints.minHeight) || 256,
  73397. max: (constraints && constraints.maxHeight) || 480,
  73398. },
  73399. },
  73400. }, function (stream) {
  73401. if (video.mozSrcObject !== undefined) {
  73402. // hack for Firefox < 19
  73403. video.mozSrcObject = stream;
  73404. }
  73405. else {
  73406. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  73407. }
  73408. video.play();
  73409. if (onReady) {
  73410. onReady(new VideoTexture("video", video, scene, true, true));
  73411. }
  73412. }, function (e) {
  73413. BABYLON.Tools.Error(e.name);
  73414. });
  73415. }
  73416. }
  73417. };
  73418. return VideoTexture;
  73419. }(BABYLON.Texture));
  73420. BABYLON.VideoTexture = VideoTexture;
  73421. })(BABYLON || (BABYLON = {}));
  73422. //# sourceMappingURL=babylon.videoTexture.js.map
  73423. var BABYLON;
  73424. (function (BABYLON) {
  73425. /**
  73426. * Raw texture can help creating a texture directly from an array of data.
  73427. * This can be super useful if you either get the data from an uncompressed source or
  73428. * if you wish to create your texture pixel by pixel.
  73429. */
  73430. var RawTexture = /** @class */ (function (_super) {
  73431. __extends(RawTexture, _super);
  73432. /**
  73433. * Instantiates a new RawTexture.
  73434. * Raw texture can help creating a texture directly from an array of data.
  73435. * This can be super useful if you either get the data from an uncompressed source or
  73436. * if you wish to create your texture pixel by pixel.
  73437. * @param data define the array of data to use to create the texture
  73438. * @param width define the width of the texture
  73439. * @param height define the height of the texture
  73440. * @param format define the format of the data (RGB, RGBA... Engine.TEXTUREFORMAT_xxx)
  73441. * @param scene define the scene the texture belongs to
  73442. * @param generateMipMaps define whether mip maps should be generated or not
  73443. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  73444. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  73445. * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx)
  73446. */
  73447. function RawTexture(data, width, height,
  73448. /**
  73449. * Define the format of the data (RGB, RGBA... Engine.TEXTUREFORMAT_xxx)
  73450. */
  73451. format, scene, generateMipMaps, invertY, samplingMode, type) {
  73452. if (generateMipMaps === void 0) { generateMipMaps = true; }
  73453. if (invertY === void 0) { invertY = false; }
  73454. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  73455. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73456. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  73457. _this.format = format;
  73458. _this._engine = scene.getEngine();
  73459. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  73460. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73461. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73462. return _this;
  73463. }
  73464. /**
  73465. * Updates the texture underlying data.
  73466. * @param data Define the new data of the texture
  73467. */
  73468. RawTexture.prototype.update = function (data) {
  73469. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  73470. };
  73471. /**
  73472. * Creates a luminance texture from some data.
  73473. * @param data Define the texture data
  73474. * @param width Define the width of the texture
  73475. * @param height Define the height of the texture
  73476. * @param scene Define the scene the texture belongs to
  73477. * @param generateMipMaps Define whether or not to create mip maps for the texture
  73478. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  73479. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  73480. * @returns the luminance texture
  73481. */
  73482. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  73483. if (generateMipMaps === void 0) { generateMipMaps = true; }
  73484. if (invertY === void 0) { invertY = false; }
  73485. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  73486. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  73487. };
  73488. /**
  73489. * Creates a luminance alpha texture from some data.
  73490. * @param data Define the texture data
  73491. * @param width Define the width of the texture
  73492. * @param height Define the height of the texture
  73493. * @param scene Define the scene the texture belongs to
  73494. * @param generateMipMaps Define whether or not to create mip maps for the texture
  73495. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  73496. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  73497. * @returns the luminance alpha texture
  73498. */
  73499. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  73500. if (generateMipMaps === void 0) { generateMipMaps = true; }
  73501. if (invertY === void 0) { invertY = false; }
  73502. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  73503. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  73504. };
  73505. /**
  73506. * Creates an alpha texture from some data.
  73507. * @param data Define the texture data
  73508. * @param width Define the width of the texture
  73509. * @param height Define the height of the texture
  73510. * @param scene Define the scene the texture belongs to
  73511. * @param generateMipMaps Define whether or not to create mip maps for the texture
  73512. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  73513. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  73514. * @returns the alpha texture
  73515. */
  73516. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  73517. if (generateMipMaps === void 0) { generateMipMaps = true; }
  73518. if (invertY === void 0) { invertY = false; }
  73519. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  73520. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  73521. };
  73522. /**
  73523. * Creates a RGB texture from some data.
  73524. * @param data Define the texture data
  73525. * @param width Define the width of the texture
  73526. * @param height Define the height of the texture
  73527. * @param scene Define the scene the texture belongs to
  73528. * @param generateMipMaps Define whether or not to create mip maps for the texture
  73529. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  73530. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  73531. * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx)
  73532. * @returns the RGB alpha texture
  73533. */
  73534. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  73535. if (generateMipMaps === void 0) { generateMipMaps = true; }
  73536. if (invertY === void 0) { invertY = false; }
  73537. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  73538. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73539. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  73540. };
  73541. /**
  73542. * Creates a RGBA texture from some data.
  73543. * @param data Define the texture data
  73544. * @param width Define the width of the texture
  73545. * @param height Define the height of the texture
  73546. * @param scene Define the scene the texture belongs to
  73547. * @param generateMipMaps Define whether or not to create mip maps for the texture
  73548. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  73549. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  73550. * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx)
  73551. * @returns the RGBA texture
  73552. */
  73553. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  73554. if (generateMipMaps === void 0) { generateMipMaps = true; }
  73555. if (invertY === void 0) { invertY = false; }
  73556. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  73557. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73558. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  73559. };
  73560. /**
  73561. * Creates a R texture from some data.
  73562. * @param data Define the texture data
  73563. * @param width Define the width of the texture
  73564. * @param height Define the height of the texture
  73565. * @param scene Define the scene the texture belongs to
  73566. * @param generateMipMaps Define whether or not to create mip maps for the texture
  73567. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  73568. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  73569. * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx)
  73570. * @returns the R texture
  73571. */
  73572. RawTexture.CreateRTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  73573. if (generateMipMaps === void 0) { generateMipMaps = true; }
  73574. if (invertY === void 0) { invertY = false; }
  73575. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  73576. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  73577. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_R, scene, generateMipMaps, invertY, samplingMode, type);
  73578. };
  73579. return RawTexture;
  73580. }(BABYLON.Texture));
  73581. BABYLON.RawTexture = RawTexture;
  73582. })(BABYLON || (BABYLON = {}));
  73583. //# sourceMappingURL=babylon.rawTexture.js.map
  73584. var BABYLON;
  73585. (function (BABYLON) {
  73586. /**
  73587. * Class used to store 3D textures containing user data
  73588. */
  73589. var RawTexture3D = /** @class */ (function (_super) {
  73590. __extends(RawTexture3D, _super);
  73591. /**
  73592. * Create a new RawTexture3D
  73593. * @param data defines the data of the texture
  73594. * @param width defines the width of the texture
  73595. * @param height defines the height of the texture
  73596. * @param depth defines the depth of the texture
  73597. * @param format defines the texture format to use
  73598. * @param scene defines the hosting scene
  73599. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  73600. * @param invertY defines if texture must be stored with Y axis inverted
  73601. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  73602. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  73603. */
  73604. function RawTexture3D(data, width, height, depth,
  73605. /** Gets or sets the texture format to use */
  73606. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  73607. if (generateMipMaps === void 0) { generateMipMaps = true; }
  73608. if (invertY === void 0) { invertY = false; }
  73609. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  73610. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73611. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  73612. _this.format = format;
  73613. _this._engine = scene.getEngine();
  73614. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  73615. _this.is3D = true;
  73616. return _this;
  73617. }
  73618. /**
  73619. * Update the texture with new data
  73620. * @param data defines the data to store in the texture
  73621. */
  73622. RawTexture3D.prototype.update = function (data) {
  73623. if (!this._texture) {
  73624. return;
  73625. }
  73626. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  73627. };
  73628. return RawTexture3D;
  73629. }(BABYLON.Texture));
  73630. BABYLON.RawTexture3D = RawTexture3D;
  73631. })(BABYLON || (BABYLON = {}));
  73632. //# sourceMappingURL=babylon.rawTexture3D.js.map
  73633. var BABYLON;
  73634. (function (BABYLON) {
  73635. /**
  73636. * PostProcessManager is used to manage one or more post processes or post process pipelines
  73637. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  73638. */
  73639. var PostProcessManager = /** @class */ (function () {
  73640. /**
  73641. * Creates a new instance PostProcess
  73642. * @param scene The scene that the post process is associated with.
  73643. */
  73644. function PostProcessManager(scene) {
  73645. this._vertexBuffers = {};
  73646. this._scene = scene;
  73647. }
  73648. PostProcessManager.prototype._prepareBuffers = function () {
  73649. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  73650. return;
  73651. }
  73652. // VBO
  73653. var vertices = [];
  73654. vertices.push(1, 1);
  73655. vertices.push(-1, 1);
  73656. vertices.push(-1, -1);
  73657. vertices.push(1, -1);
  73658. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  73659. this._buildIndexBuffer();
  73660. };
  73661. PostProcessManager.prototype._buildIndexBuffer = function () {
  73662. // Indices
  73663. var indices = [];
  73664. indices.push(0);
  73665. indices.push(1);
  73666. indices.push(2);
  73667. indices.push(0);
  73668. indices.push(2);
  73669. indices.push(3);
  73670. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  73671. };
  73672. /**
  73673. * Rebuilds the vertex buffers of the manager.
  73674. * @hidden
  73675. */
  73676. PostProcessManager.prototype._rebuild = function () {
  73677. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  73678. if (!vb) {
  73679. return;
  73680. }
  73681. vb._rebuild();
  73682. this._buildIndexBuffer();
  73683. };
  73684. // Methods
  73685. /**
  73686. * Prepares a frame to be run through a post process.
  73687. * @param sourceTexture The input texture to the post procesess. (default: null)
  73688. * @param postProcesses An array of post processes to be run. (default: null)
  73689. * @returns True if the post processes were able to be run.
  73690. * @hidden
  73691. */
  73692. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  73693. if (sourceTexture === void 0) { sourceTexture = null; }
  73694. if (postProcesses === void 0) { postProcesses = null; }
  73695. var camera = this._scene.activeCamera;
  73696. if (!camera) {
  73697. return false;
  73698. }
  73699. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  73700. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  73701. return false;
  73702. }
  73703. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  73704. return true;
  73705. };
  73706. /**
  73707. * Manually render a set of post processes to a texture.
  73708. * @param postProcesses An array of post processes to be run.
  73709. * @param targetTexture The target texture to render to.
  73710. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  73711. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  73712. * @param lodLevel defines which lod of the texture to render to
  73713. */
  73714. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  73715. if (targetTexture === void 0) { targetTexture = null; }
  73716. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  73717. if (faceIndex === void 0) { faceIndex = 0; }
  73718. if (lodLevel === void 0) { lodLevel = 0; }
  73719. var engine = this._scene.getEngine();
  73720. for (var index = 0; index < postProcesses.length; index++) {
  73721. if (index < postProcesses.length - 1) {
  73722. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  73723. }
  73724. else {
  73725. if (targetTexture) {
  73726. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  73727. }
  73728. else {
  73729. engine.restoreDefaultFramebuffer();
  73730. }
  73731. }
  73732. var pp = postProcesses[index];
  73733. var effect = pp.apply();
  73734. if (effect) {
  73735. pp.onBeforeRenderObservable.notifyObservers(effect);
  73736. // VBOs
  73737. this._prepareBuffers();
  73738. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  73739. // Draw order
  73740. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  73741. pp.onAfterRenderObservable.notifyObservers(effect);
  73742. }
  73743. }
  73744. // Restore depth buffer
  73745. engine.setDepthBuffer(true);
  73746. engine.setDepthWrite(true);
  73747. };
  73748. /**
  73749. * Finalize the result of the output of the postprocesses.
  73750. * @param doNotPresent If true the result will not be displayed to the screen.
  73751. * @param targetTexture The target texture to render to.
  73752. * @param faceIndex The index of the face to bind the target texture to.
  73753. * @param postProcesses The array of post processes to render.
  73754. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  73755. * @hidden
  73756. */
  73757. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  73758. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  73759. var camera = this._scene.activeCamera;
  73760. if (!camera) {
  73761. return;
  73762. }
  73763. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  73764. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  73765. return;
  73766. }
  73767. var engine = this._scene.getEngine();
  73768. for (var index = 0, len = postProcesses.length; index < len; index++) {
  73769. var pp = postProcesses[index];
  73770. if (index < len - 1) {
  73771. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  73772. }
  73773. else {
  73774. if (targetTexture) {
  73775. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  73776. pp._outputTexture = targetTexture;
  73777. }
  73778. else {
  73779. engine.restoreDefaultFramebuffer();
  73780. pp._outputTexture = null;
  73781. }
  73782. }
  73783. if (doNotPresent) {
  73784. break;
  73785. }
  73786. var effect = pp.apply();
  73787. if (effect) {
  73788. pp.onBeforeRenderObservable.notifyObservers(effect);
  73789. // VBOs
  73790. this._prepareBuffers();
  73791. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  73792. // Draw order
  73793. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  73794. pp.onAfterRenderObservable.notifyObservers(effect);
  73795. }
  73796. }
  73797. // Restore states
  73798. engine.setDepthBuffer(true);
  73799. engine.setDepthWrite(true);
  73800. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  73801. };
  73802. /**
  73803. * Disposes of the post process manager.
  73804. */
  73805. PostProcessManager.prototype.dispose = function () {
  73806. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  73807. if (buffer) {
  73808. buffer.dispose();
  73809. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  73810. }
  73811. if (this._indexBuffer) {
  73812. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  73813. this._indexBuffer = null;
  73814. }
  73815. };
  73816. return PostProcessManager;
  73817. }());
  73818. BABYLON.PostProcessManager = PostProcessManager;
  73819. })(BABYLON || (BABYLON = {}));
  73820. //# sourceMappingURL=babylon.postProcessManager.js.map
  73821. var BABYLON;
  73822. (function (BABYLON) {
  73823. /**
  73824. * PostProcess can be used to apply a shader to a texture after it has been rendered
  73825. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  73826. */
  73827. var PostProcess = /** @class */ (function () {
  73828. /**
  73829. * Creates a new instance PostProcess
  73830. * @param name The name of the PostProcess.
  73831. * @param fragmentUrl The url of the fragment shader to be used.
  73832. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  73833. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  73834. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  73835. * @param camera The camera to apply the render pass to.
  73836. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  73837. * @param engine The engine which the post process will be applied. (default: current engine)
  73838. * @param reusable If the post process can be reused on the same frame. (default: false)
  73839. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  73840. * @param textureType Type of textures used when performing the post process. (default: 0)
  73841. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  73842. * @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
  73843. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  73844. */
  73845. function PostProcess(
  73846. /** Name of the PostProcess. */
  73847. name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  73848. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  73849. if (defines === void 0) { defines = null; }
  73850. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73851. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  73852. if (blockCompilation === void 0) { blockCompilation = false; }
  73853. this.name = name;
  73854. /**
  73855. * Width of the texture to apply the post process on
  73856. */
  73857. this.width = -1;
  73858. /**
  73859. * Height of the texture to apply the post process on
  73860. */
  73861. this.height = -1;
  73862. /**
  73863. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  73864. * @hidden
  73865. */
  73866. this._outputTexture = null;
  73867. /**
  73868. * If the buffer needs to be cleared before applying the post process. (default: true)
  73869. * Should be set to false if shader will overwrite all previous pixels.
  73870. */
  73871. this.autoClear = true;
  73872. /**
  73873. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  73874. */
  73875. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  73876. /**
  73877. * Animations to be used for the post processing
  73878. */
  73879. this.animations = new Array();
  73880. /**
  73881. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  73882. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  73883. */
  73884. this.enablePixelPerfectMode = false;
  73885. /**
  73886. * Force the postprocess to be applied without taking in account viewport
  73887. */
  73888. this.forceFullscreenViewport = true;
  73889. /**
  73890. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  73891. *
  73892. * | Value | Type | Description |
  73893. * | ----- | ----------------------------------- | ----------- |
  73894. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  73895. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  73896. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  73897. *
  73898. */
  73899. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  73900. /**
  73901. * Force textures to be a power of two (default: false)
  73902. */
  73903. this.alwaysForcePOT = false;
  73904. this._samples = 1;
  73905. /**
  73906. * Modify the scale of the post process to be the same as the viewport (default: false)
  73907. */
  73908. this.adaptScaleToCurrentViewport = false;
  73909. this._reusable = false;
  73910. /**
  73911. * Smart array of input and output textures for the post process.
  73912. * @hidden
  73913. */
  73914. this._textures = new BABYLON.SmartArray(2);
  73915. /**
  73916. * The index in _textures that corresponds to the output texture.
  73917. * @hidden
  73918. */
  73919. this._currentRenderTextureInd = 0;
  73920. this._scaleRatio = new BABYLON.Vector2(1, 1);
  73921. this._texelSize = BABYLON.Vector2.Zero();
  73922. // Events
  73923. /**
  73924. * An event triggered when the postprocess is activated.
  73925. */
  73926. this.onActivateObservable = new BABYLON.Observable();
  73927. /**
  73928. * An event triggered when the postprocess changes its size.
  73929. */
  73930. this.onSizeChangedObservable = new BABYLON.Observable();
  73931. /**
  73932. * An event triggered when the postprocess applies its effect.
  73933. */
  73934. this.onApplyObservable = new BABYLON.Observable();
  73935. /**
  73936. * An event triggered before rendering the postprocess
  73937. */
  73938. this.onBeforeRenderObservable = new BABYLON.Observable();
  73939. /**
  73940. * An event triggered after rendering the postprocess
  73941. */
  73942. this.onAfterRenderObservable = new BABYLON.Observable();
  73943. if (camera != null) {
  73944. this._camera = camera;
  73945. this._scene = camera.getScene();
  73946. camera.attachPostProcess(this);
  73947. this._engine = this._scene.getEngine();
  73948. this._scene.postProcesses.push(this);
  73949. }
  73950. else if (engine) {
  73951. this._engine = engine;
  73952. this._engine.postProcesses.push(this);
  73953. }
  73954. this._options = options;
  73955. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  73956. this._reusable = reusable || false;
  73957. this._textureType = textureType;
  73958. this._samplers = samplers || [];
  73959. this._samplers.push("textureSampler");
  73960. this._fragmentUrl = fragmentUrl;
  73961. this._vertexUrl = vertexUrl;
  73962. this._parameters = parameters || [];
  73963. this._parameters.push("scale");
  73964. this._indexParameters = indexParameters;
  73965. if (!blockCompilation) {
  73966. this.updateEffect(defines);
  73967. }
  73968. }
  73969. Object.defineProperty(PostProcess.prototype, "samples", {
  73970. /**
  73971. * Number of sample textures (default: 1)
  73972. */
  73973. get: function () {
  73974. return this._samples;
  73975. },
  73976. set: function (n) {
  73977. var _this = this;
  73978. this._samples = n;
  73979. this._textures.forEach(function (texture) {
  73980. if (texture.samples !== _this._samples) {
  73981. _this._engine.updateRenderTargetTextureSampleCount(texture, _this._samples);
  73982. }
  73983. });
  73984. },
  73985. enumerable: true,
  73986. configurable: true
  73987. });
  73988. Object.defineProperty(PostProcess.prototype, "onActivate", {
  73989. /**
  73990. * A function that is added to the onActivateObservable
  73991. */
  73992. set: function (callback) {
  73993. if (this._onActivateObserver) {
  73994. this.onActivateObservable.remove(this._onActivateObserver);
  73995. }
  73996. if (callback) {
  73997. this._onActivateObserver = this.onActivateObservable.add(callback);
  73998. }
  73999. },
  74000. enumerable: true,
  74001. configurable: true
  74002. });
  74003. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  74004. /**
  74005. * A function that is added to the onSizeChangedObservable
  74006. */
  74007. set: function (callback) {
  74008. if (this._onSizeChangedObserver) {
  74009. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  74010. }
  74011. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  74012. },
  74013. enumerable: true,
  74014. configurable: true
  74015. });
  74016. Object.defineProperty(PostProcess.prototype, "onApply", {
  74017. /**
  74018. * A function that is added to the onApplyObservable
  74019. */
  74020. set: function (callback) {
  74021. if (this._onApplyObserver) {
  74022. this.onApplyObservable.remove(this._onApplyObserver);
  74023. }
  74024. this._onApplyObserver = this.onApplyObservable.add(callback);
  74025. },
  74026. enumerable: true,
  74027. configurable: true
  74028. });
  74029. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  74030. /**
  74031. * A function that is added to the onBeforeRenderObservable
  74032. */
  74033. set: function (callback) {
  74034. if (this._onBeforeRenderObserver) {
  74035. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  74036. }
  74037. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  74038. },
  74039. enumerable: true,
  74040. configurable: true
  74041. });
  74042. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  74043. /**
  74044. * A function that is added to the onAfterRenderObservable
  74045. */
  74046. set: function (callback) {
  74047. if (this._onAfterRenderObserver) {
  74048. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  74049. }
  74050. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  74051. },
  74052. enumerable: true,
  74053. configurable: true
  74054. });
  74055. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  74056. /**
  74057. * 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
  74058. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  74059. */
  74060. get: function () {
  74061. return this._textures.data[this._currentRenderTextureInd];
  74062. },
  74063. set: function (value) {
  74064. this._forcedOutputTexture = value;
  74065. },
  74066. enumerable: true,
  74067. configurable: true
  74068. });
  74069. /**
  74070. * Gets the camera which post process is applied to.
  74071. * @returns The camera the post process is applied to.
  74072. */
  74073. PostProcess.prototype.getCamera = function () {
  74074. return this._camera;
  74075. };
  74076. Object.defineProperty(PostProcess.prototype, "texelSize", {
  74077. /**
  74078. * Gets the texel size of the postprocess.
  74079. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  74080. */
  74081. get: function () {
  74082. if (this._shareOutputWithPostProcess) {
  74083. return this._shareOutputWithPostProcess.texelSize;
  74084. }
  74085. if (this._forcedOutputTexture) {
  74086. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  74087. }
  74088. return this._texelSize;
  74089. },
  74090. enumerable: true,
  74091. configurable: true
  74092. });
  74093. /**
  74094. * Gets the engine which this post process belongs to.
  74095. * @returns The engine the post process was enabled with.
  74096. */
  74097. PostProcess.prototype.getEngine = function () {
  74098. return this._engine;
  74099. };
  74100. /**
  74101. * The effect that is created when initializing the post process.
  74102. * @returns The created effect corrisponding the the postprocess.
  74103. */
  74104. PostProcess.prototype.getEffect = function () {
  74105. return this._effect;
  74106. };
  74107. /**
  74108. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  74109. * @param postProcess The post process to share the output with.
  74110. * @returns This post process.
  74111. */
  74112. PostProcess.prototype.shareOutputWith = function (postProcess) {
  74113. this._disposeTextures();
  74114. this._shareOutputWithPostProcess = postProcess;
  74115. return this;
  74116. };
  74117. /**
  74118. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  74119. * This should be called if the post process that shares output with this post process is disabled/disposed.
  74120. */
  74121. PostProcess.prototype.useOwnOutput = function () {
  74122. if (this._textures.length == 0) {
  74123. this._textures = new BABYLON.SmartArray(2);
  74124. }
  74125. this._shareOutputWithPostProcess = null;
  74126. };
  74127. /**
  74128. * Updates the effect with the current post process compile time values and recompiles the shader.
  74129. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  74130. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  74131. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  74132. * @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
  74133. * @param onCompiled Called when the shader has been compiled.
  74134. * @param onError Called if there is an error when compiling a shader.
  74135. */
  74136. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  74137. if (defines === void 0) { defines = null; }
  74138. if (uniforms === void 0) { uniforms = null; }
  74139. if (samplers === void 0) { samplers = null; }
  74140. 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);
  74141. };
  74142. /**
  74143. * The post process is reusable if it can be used multiple times within one frame.
  74144. * @returns If the post process is reusable
  74145. */
  74146. PostProcess.prototype.isReusable = function () {
  74147. return this._reusable;
  74148. };
  74149. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  74150. PostProcess.prototype.markTextureDirty = function () {
  74151. this.width = -1;
  74152. };
  74153. /**
  74154. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  74155. * 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.
  74156. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  74157. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  74158. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  74159. * @returns The target texture that was bound to be written to.
  74160. */
  74161. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  74162. var _this = this;
  74163. if (sourceTexture === void 0) { sourceTexture = null; }
  74164. camera = camera || this._camera;
  74165. var scene = camera.getScene();
  74166. var engine = scene.getEngine();
  74167. var maxSize = engine.getCaps().maxTextureSize;
  74168. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  74169. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  74170. // 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
  74171. var webVRCamera = camera.parent;
  74172. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  74173. requiredWidth /= 2;
  74174. }
  74175. var desiredWidth = (this._options.width || requiredWidth);
  74176. var desiredHeight = this._options.height || requiredHeight;
  74177. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  74178. if (this.adaptScaleToCurrentViewport) {
  74179. var currentViewport = engine.currentViewport;
  74180. if (currentViewport) {
  74181. desiredWidth *= currentViewport.width;
  74182. desiredHeight *= currentViewport.height;
  74183. }
  74184. }
  74185. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  74186. if (!this._options.width) {
  74187. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  74188. }
  74189. if (!this._options.height) {
  74190. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  74191. }
  74192. }
  74193. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  74194. if (this._textures.length > 0) {
  74195. for (var i = 0; i < this._textures.length; i++) {
  74196. this._engine._releaseTexture(this._textures.data[i]);
  74197. }
  74198. this._textures.reset();
  74199. }
  74200. this.width = desiredWidth;
  74201. this.height = desiredHeight;
  74202. var textureSize = { width: this.width, height: this.height };
  74203. var textureOptions = {
  74204. generateMipMaps: false,
  74205. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  74206. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  74207. samplingMode: this.renderTargetSamplingMode,
  74208. type: this._textureType
  74209. };
  74210. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  74211. if (this._reusable) {
  74212. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  74213. }
  74214. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  74215. this.onSizeChangedObservable.notifyObservers(this);
  74216. }
  74217. this._textures.forEach(function (texture) {
  74218. if (texture.samples !== _this.samples) {
  74219. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  74220. }
  74221. });
  74222. }
  74223. var target;
  74224. if (this._shareOutputWithPostProcess) {
  74225. target = this._shareOutputWithPostProcess.inputTexture;
  74226. }
  74227. else if (this._forcedOutputTexture) {
  74228. target = this._forcedOutputTexture;
  74229. this.width = this._forcedOutputTexture.width;
  74230. this.height = this._forcedOutputTexture.height;
  74231. }
  74232. else {
  74233. target = this.inputTexture;
  74234. }
  74235. // Bind the input of this post process to be used as the output of the previous post process.
  74236. if (this.enablePixelPerfectMode) {
  74237. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  74238. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  74239. }
  74240. else {
  74241. this._scaleRatio.copyFromFloats(1, 1);
  74242. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  74243. }
  74244. this.onActivateObservable.notifyObservers(camera);
  74245. // Clear
  74246. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  74247. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, scene._allowPostProcessClearColor, true, true);
  74248. }
  74249. if (this._reusable) {
  74250. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  74251. }
  74252. return target;
  74253. };
  74254. Object.defineProperty(PostProcess.prototype, "isSupported", {
  74255. /**
  74256. * If the post process is supported.
  74257. */
  74258. get: function () {
  74259. return this._effect.isSupported;
  74260. },
  74261. enumerable: true,
  74262. configurable: true
  74263. });
  74264. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  74265. /**
  74266. * The aspect ratio of the output texture.
  74267. */
  74268. get: function () {
  74269. if (this._shareOutputWithPostProcess) {
  74270. return this._shareOutputWithPostProcess.aspectRatio;
  74271. }
  74272. if (this._forcedOutputTexture) {
  74273. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  74274. }
  74275. return this.width / this.height;
  74276. },
  74277. enumerable: true,
  74278. configurable: true
  74279. });
  74280. /**
  74281. * Get a value indicating if the post-process is ready to be used
  74282. * @returns true if the post-process is ready (shader is compiled)
  74283. */
  74284. PostProcess.prototype.isReady = function () {
  74285. return this._effect && this._effect.isReady();
  74286. };
  74287. /**
  74288. * Binds all textures and uniforms to the shader, this will be run on every pass.
  74289. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  74290. */
  74291. PostProcess.prototype.apply = function () {
  74292. // Check
  74293. if (!this._effect || !this._effect.isReady())
  74294. return null;
  74295. // States
  74296. this._engine.enableEffect(this._effect);
  74297. this._engine.setState(false);
  74298. this._engine.setDepthBuffer(false);
  74299. this._engine.setDepthWrite(false);
  74300. // Alpha
  74301. this._engine.setAlphaMode(this.alphaMode);
  74302. if (this.alphaConstants) {
  74303. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  74304. }
  74305. // Bind the output texture of the preivous post process as the input to this post process.
  74306. var source;
  74307. if (this._shareOutputWithPostProcess) {
  74308. source = this._shareOutputWithPostProcess.inputTexture;
  74309. }
  74310. else if (this._forcedOutputTexture) {
  74311. source = this._forcedOutputTexture;
  74312. }
  74313. else {
  74314. source = this.inputTexture;
  74315. }
  74316. this._effect._bindTexture("textureSampler", source);
  74317. // Parameters
  74318. this._effect.setVector2("scale", this._scaleRatio);
  74319. this.onApplyObservable.notifyObservers(this._effect);
  74320. return this._effect;
  74321. };
  74322. PostProcess.prototype._disposeTextures = function () {
  74323. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  74324. return;
  74325. }
  74326. if (this._textures.length > 0) {
  74327. for (var i = 0; i < this._textures.length; i++) {
  74328. this._engine._releaseTexture(this._textures.data[i]);
  74329. }
  74330. }
  74331. this._textures.dispose();
  74332. };
  74333. /**
  74334. * Disposes the post process.
  74335. * @param camera The camera to dispose the post process on.
  74336. */
  74337. PostProcess.prototype.dispose = function (camera) {
  74338. camera = camera || this._camera;
  74339. this._disposeTextures();
  74340. if (this._scene) {
  74341. var index_1 = this._scene.postProcesses.indexOf(this);
  74342. if (index_1 !== -1) {
  74343. this._scene.postProcesses.splice(index_1, 1);
  74344. }
  74345. }
  74346. else {
  74347. var index_2 = this._engine.postProcesses.indexOf(this);
  74348. if (index_2 !== -1) {
  74349. this._engine.postProcesses.splice(index_2, 1);
  74350. }
  74351. }
  74352. if (!camera) {
  74353. return;
  74354. }
  74355. camera.detachPostProcess(this);
  74356. var index = camera._postProcesses.indexOf(this);
  74357. if (index === 0 && camera._postProcesses.length > 0) {
  74358. var firstPostProcess = this._camera._getFirstPostProcess();
  74359. if (firstPostProcess) {
  74360. firstPostProcess.markTextureDirty();
  74361. }
  74362. }
  74363. this.onActivateObservable.clear();
  74364. this.onAfterRenderObservable.clear();
  74365. this.onApplyObservable.clear();
  74366. this.onBeforeRenderObservable.clear();
  74367. this.onSizeChangedObservable.clear();
  74368. };
  74369. return PostProcess;
  74370. }());
  74371. BABYLON.PostProcess = PostProcess;
  74372. })(BABYLON || (BABYLON = {}));
  74373. //# sourceMappingURL=babylon.postProcess.js.map
  74374. var BABYLON;
  74375. (function (BABYLON) {
  74376. /**
  74377. * PassPostProcess which produces an output the same as it's input
  74378. */
  74379. var PassPostProcess = /** @class */ (function (_super) {
  74380. __extends(PassPostProcess, _super);
  74381. /**
  74382. * Creates the PassPostProcess
  74383. * @param name The name of the effect.
  74384. * @param options The required width/height ratio to downsize to before computing the render pass.
  74385. * @param camera The camera to apply the render pass to.
  74386. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74387. * @param engine The engine which the post process will be applied. (default: current engine)
  74388. * @param reusable If the post process can be reused on the same frame. (default: false)
  74389. * @param textureType The type of texture to be used when performing the post processing.
  74390. * @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)
  74391. */
  74392. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74393. if (camera === void 0) { camera = null; }
  74394. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74395. if (blockCompilation === void 0) { blockCompilation = false; }
  74396. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  74397. }
  74398. return PassPostProcess;
  74399. }(BABYLON.PostProcess));
  74400. BABYLON.PassPostProcess = PassPostProcess;
  74401. })(BABYLON || (BABYLON = {}));
  74402. //# sourceMappingURL=babylon.passPostProcess.js.map
  74403. var __assign = (this && this.__assign) || function () {
  74404. __assign = Object.assign || function(t) {
  74405. for (var s, i = 1, n = arguments.length; i < n; i++) {
  74406. s = arguments[i];
  74407. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  74408. t[p] = s[p];
  74409. }
  74410. return t;
  74411. };
  74412. return __assign.apply(this, arguments);
  74413. };
  74414. var BABYLON;
  74415. (function (BABYLON) {
  74416. /**
  74417. * Default implementation IShadowGenerator.
  74418. * This is the main object responsible of generating shadows in the framework.
  74419. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  74420. */
  74421. var ShadowGenerator = /** @class */ (function () {
  74422. /**
  74423. * Creates a ShadowGenerator object.
  74424. * A ShadowGenerator is the required tool to use the shadows.
  74425. * Each light casting shadows needs to use its own ShadowGenerator.
  74426. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  74427. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  74428. * @param light The light object generating the shadows.
  74429. * @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.
  74430. */
  74431. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  74432. this._bias = 0.00005;
  74433. this._normalBias = 0;
  74434. this._blurBoxOffset = 1;
  74435. this._blurScale = 2;
  74436. this._blurKernel = 1;
  74437. this._useKernelBlur = false;
  74438. this._filter = ShadowGenerator.FILTER_NONE;
  74439. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  74440. this._contactHardeningLightSizeUVRatio = 0.1;
  74441. this._darkness = 0;
  74442. this._transparencyShadow = false;
  74443. /**
  74444. * Controls the extent to which the shadows fade out at the edge of the frustum
  74445. * Used only by directionals and spots
  74446. */
  74447. this.frustumEdgeFalloff = 0;
  74448. /**
  74449. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  74450. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  74451. * It might on the other hand introduce peter panning.
  74452. */
  74453. this.forceBackFacesOnly = false;
  74454. this._lightDirection = BABYLON.Vector3.Zero();
  74455. this._viewMatrix = BABYLON.Matrix.Zero();
  74456. this._projectionMatrix = BABYLON.Matrix.Zero();
  74457. this._transformMatrix = BABYLON.Matrix.Zero();
  74458. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  74459. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  74460. this._currentFaceIndex = 0;
  74461. this._currentFaceIndexCache = 0;
  74462. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  74463. this._mapSize = mapSize;
  74464. this._light = light;
  74465. this._scene = light.getScene();
  74466. light._shadowGenerator = this;
  74467. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR);
  74468. if (!component) {
  74469. component = new BABYLON.ShadowGeneratorSceneComponent(this._scene);
  74470. this._scene._addComponent(component);
  74471. }
  74472. // Texture type fallback from float to int if not supported.
  74473. var caps = this._scene.getEngine().getCaps();
  74474. if (!useFullFloatFirst) {
  74475. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  74476. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  74477. }
  74478. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  74479. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  74480. }
  74481. else {
  74482. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  74483. }
  74484. }
  74485. else {
  74486. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  74487. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  74488. }
  74489. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  74490. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  74491. }
  74492. else {
  74493. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  74494. }
  74495. }
  74496. this._initializeGenerator();
  74497. this._applyFilterValues();
  74498. }
  74499. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  74500. /**
  74501. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  74502. */
  74503. get: function () {
  74504. return this._bias;
  74505. },
  74506. /**
  74507. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  74508. */
  74509. set: function (bias) {
  74510. this._bias = bias;
  74511. },
  74512. enumerable: true,
  74513. configurable: true
  74514. });
  74515. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  74516. /**
  74517. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  74518. */
  74519. get: function () {
  74520. return this._normalBias;
  74521. },
  74522. /**
  74523. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  74524. */
  74525. set: function (normalBias) {
  74526. this._normalBias = normalBias;
  74527. },
  74528. enumerable: true,
  74529. configurable: true
  74530. });
  74531. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  74532. /**
  74533. * Gets the blur box offset: offset applied during the blur pass.
  74534. * Only usefull if useKernelBlur = false
  74535. */
  74536. get: function () {
  74537. return this._blurBoxOffset;
  74538. },
  74539. /**
  74540. * Sets the blur box offset: offset applied during the blur pass.
  74541. * Only usefull if useKernelBlur = false
  74542. */
  74543. set: function (value) {
  74544. if (this._blurBoxOffset === value) {
  74545. return;
  74546. }
  74547. this._blurBoxOffset = value;
  74548. this._disposeBlurPostProcesses();
  74549. },
  74550. enumerable: true,
  74551. configurable: true
  74552. });
  74553. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  74554. /**
  74555. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  74556. * 2 means half of the size.
  74557. */
  74558. get: function () {
  74559. return this._blurScale;
  74560. },
  74561. /**
  74562. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  74563. * 2 means half of the size.
  74564. */
  74565. set: function (value) {
  74566. if (this._blurScale === value) {
  74567. return;
  74568. }
  74569. this._blurScale = value;
  74570. this._disposeBlurPostProcesses();
  74571. },
  74572. enumerable: true,
  74573. configurable: true
  74574. });
  74575. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  74576. /**
  74577. * Gets the blur kernel: kernel size of the blur pass.
  74578. * Only usefull if useKernelBlur = true
  74579. */
  74580. get: function () {
  74581. return this._blurKernel;
  74582. },
  74583. /**
  74584. * Sets the blur kernel: kernel size of the blur pass.
  74585. * Only usefull if useKernelBlur = true
  74586. */
  74587. set: function (value) {
  74588. if (this._blurKernel === value) {
  74589. return;
  74590. }
  74591. this._blurKernel = value;
  74592. this._disposeBlurPostProcesses();
  74593. },
  74594. enumerable: true,
  74595. configurable: true
  74596. });
  74597. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  74598. /**
  74599. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  74600. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  74601. */
  74602. get: function () {
  74603. return this._useKernelBlur;
  74604. },
  74605. /**
  74606. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  74607. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  74608. */
  74609. set: function (value) {
  74610. if (this._useKernelBlur === value) {
  74611. return;
  74612. }
  74613. this._useKernelBlur = value;
  74614. this._disposeBlurPostProcesses();
  74615. },
  74616. enumerable: true,
  74617. configurable: true
  74618. });
  74619. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  74620. /**
  74621. * Gets the depth scale used in ESM mode.
  74622. */
  74623. get: function () {
  74624. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  74625. },
  74626. /**
  74627. * Sets the depth scale used in ESM mode.
  74628. * This can override the scale stored on the light.
  74629. */
  74630. set: function (value) {
  74631. this._depthScale = value;
  74632. },
  74633. enumerable: true,
  74634. configurable: true
  74635. });
  74636. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  74637. /**
  74638. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  74639. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  74640. */
  74641. get: function () {
  74642. return this._filter;
  74643. },
  74644. /**
  74645. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  74646. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  74647. */
  74648. set: function (value) {
  74649. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  74650. if (this._light.needCube()) {
  74651. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  74652. this.useExponentialShadowMap = true;
  74653. return;
  74654. }
  74655. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  74656. this.useCloseExponentialShadowMap = true;
  74657. return;
  74658. }
  74659. // PCF on cubemap would also be expensive
  74660. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  74661. this.usePoissonSampling = true;
  74662. return;
  74663. }
  74664. }
  74665. // Weblg1 fallback for PCF.
  74666. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  74667. if (this._scene.getEngine().webGLVersion === 1) {
  74668. this.usePoissonSampling = true;
  74669. return;
  74670. }
  74671. }
  74672. if (this._filter === value) {
  74673. return;
  74674. }
  74675. this._filter = value;
  74676. this._disposeBlurPostProcesses();
  74677. this._applyFilterValues();
  74678. this._light._markMeshesAsLightDirty();
  74679. },
  74680. enumerable: true,
  74681. configurable: true
  74682. });
  74683. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  74684. /**
  74685. * Gets if the current filter is set to Poisson Sampling.
  74686. */
  74687. get: function () {
  74688. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  74689. },
  74690. /**
  74691. * Sets the current filter to Poisson Sampling.
  74692. */
  74693. set: function (value) {
  74694. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  74695. return;
  74696. }
  74697. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  74698. },
  74699. enumerable: true,
  74700. configurable: true
  74701. });
  74702. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  74703. /**
  74704. * Gets if the current filter is set to VSM.
  74705. * DEPRECATED. Should use useExponentialShadowMap instead.
  74706. */
  74707. get: function () {
  74708. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  74709. return this.useExponentialShadowMap;
  74710. },
  74711. /**
  74712. * Sets the current filter is to VSM.
  74713. * DEPRECATED. Should use useExponentialShadowMap instead.
  74714. */
  74715. set: function (value) {
  74716. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  74717. this.useExponentialShadowMap = value;
  74718. },
  74719. enumerable: true,
  74720. configurable: true
  74721. });
  74722. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  74723. /**
  74724. * Gets if the current filter is set to blurred VSM.
  74725. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  74726. */
  74727. get: function () {
  74728. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  74729. return this.useBlurExponentialShadowMap;
  74730. },
  74731. /**
  74732. * Sets the current filter is to blurred VSM.
  74733. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  74734. */
  74735. set: function (value) {
  74736. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  74737. this.useBlurExponentialShadowMap = value;
  74738. },
  74739. enumerable: true,
  74740. configurable: true
  74741. });
  74742. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  74743. /**
  74744. * Gets if the current filter is set to ESM.
  74745. */
  74746. get: function () {
  74747. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  74748. },
  74749. /**
  74750. * Sets the current filter is to ESM.
  74751. */
  74752. set: function (value) {
  74753. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  74754. return;
  74755. }
  74756. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  74757. },
  74758. enumerable: true,
  74759. configurable: true
  74760. });
  74761. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  74762. /**
  74763. * Gets if the current filter is set to filtered ESM.
  74764. */
  74765. get: function () {
  74766. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  74767. },
  74768. /**
  74769. * Gets if the current filter is set to filtered ESM.
  74770. */
  74771. set: function (value) {
  74772. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  74773. return;
  74774. }
  74775. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  74776. },
  74777. enumerable: true,
  74778. configurable: true
  74779. });
  74780. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  74781. /**
  74782. * Gets if the current filter is set to "close ESM" (using the inverse of the
  74783. * exponential to prevent steep falloff artifacts).
  74784. */
  74785. get: function () {
  74786. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  74787. },
  74788. /**
  74789. * Sets the current filter to "close ESM" (using the inverse of the
  74790. * exponential to prevent steep falloff artifacts).
  74791. */
  74792. set: function (value) {
  74793. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  74794. return;
  74795. }
  74796. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  74797. },
  74798. enumerable: true,
  74799. configurable: true
  74800. });
  74801. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  74802. /**
  74803. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  74804. * exponential to prevent steep falloff artifacts).
  74805. */
  74806. get: function () {
  74807. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  74808. },
  74809. /**
  74810. * Sets the current filter to filtered "close ESM" (using the inverse of the
  74811. * exponential to prevent steep falloff artifacts).
  74812. */
  74813. set: function (value) {
  74814. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  74815. return;
  74816. }
  74817. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  74818. },
  74819. enumerable: true,
  74820. configurable: true
  74821. });
  74822. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  74823. /**
  74824. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  74825. */
  74826. get: function () {
  74827. return this.filter === ShadowGenerator.FILTER_PCF;
  74828. },
  74829. /**
  74830. * Sets the current filter to "PCF" (percentage closer filtering).
  74831. */
  74832. set: function (value) {
  74833. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  74834. return;
  74835. }
  74836. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  74837. },
  74838. enumerable: true,
  74839. configurable: true
  74840. });
  74841. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  74842. /**
  74843. * Gets the PCF or PCSS Quality.
  74844. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  74845. */
  74846. get: function () {
  74847. return this._filteringQuality;
  74848. },
  74849. /**
  74850. * Sets the PCF or PCSS Quality.
  74851. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  74852. */
  74853. set: function (filteringQuality) {
  74854. this._filteringQuality = filteringQuality;
  74855. },
  74856. enumerable: true,
  74857. configurable: true
  74858. });
  74859. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  74860. /**
  74861. * Gets if the current filter is set to "PCSS" (contact hardening).
  74862. */
  74863. get: function () {
  74864. return this.filter === ShadowGenerator.FILTER_PCSS;
  74865. },
  74866. /**
  74867. * Sets the current filter to "PCSS" (contact hardening).
  74868. */
  74869. set: function (value) {
  74870. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  74871. return;
  74872. }
  74873. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  74874. },
  74875. enumerable: true,
  74876. configurable: true
  74877. });
  74878. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  74879. /**
  74880. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  74881. * Using a ratio helps keeping shape stability independently of the map size.
  74882. *
  74883. * It does not account for the light projection as it was having too much
  74884. * instability during the light setup or during light position changes.
  74885. *
  74886. * Only valid if useContactHardeningShadow is true.
  74887. */
  74888. get: function () {
  74889. return this._contactHardeningLightSizeUVRatio;
  74890. },
  74891. /**
  74892. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  74893. * Using a ratio helps keeping shape stability independently of the map size.
  74894. *
  74895. * It does not account for the light projection as it was having too much
  74896. * instability during the light setup or during light position changes.
  74897. *
  74898. * Only valid if useContactHardeningShadow is true.
  74899. */
  74900. set: function (contactHardeningLightSizeUVRatio) {
  74901. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  74902. },
  74903. enumerable: true,
  74904. configurable: true
  74905. });
  74906. /**
  74907. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  74908. * 0 means strongest and 1 would means no shadow.
  74909. * @returns the darkness.
  74910. */
  74911. ShadowGenerator.prototype.getDarkness = function () {
  74912. return this._darkness;
  74913. };
  74914. /**
  74915. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  74916. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  74917. * @returns the shadow generator allowing fluent coding.
  74918. */
  74919. ShadowGenerator.prototype.setDarkness = function (darkness) {
  74920. if (darkness >= 1.0)
  74921. this._darkness = 1.0;
  74922. else if (darkness <= 0.0)
  74923. this._darkness = 0.0;
  74924. else
  74925. this._darkness = darkness;
  74926. return this;
  74927. };
  74928. /**
  74929. * Sets the ability to have transparent shadow (boolean).
  74930. * @param transparent True if transparent else False
  74931. * @returns the shadow generator allowing fluent coding
  74932. */
  74933. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  74934. this._transparencyShadow = transparent;
  74935. return this;
  74936. };
  74937. /**
  74938. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  74939. * @returns The render target texture if present otherwise, null
  74940. */
  74941. ShadowGenerator.prototype.getShadowMap = function () {
  74942. return this._shadowMap;
  74943. };
  74944. /**
  74945. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  74946. * @returns The render target texture if the shadow map is present otherwise, null
  74947. */
  74948. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  74949. if (this._shadowMap2) {
  74950. return this._shadowMap2;
  74951. }
  74952. return this._shadowMap;
  74953. };
  74954. /**
  74955. * Helper function to add a mesh and its descendants to the list of shadow casters.
  74956. * @param mesh Mesh to add
  74957. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  74958. * @returns the Shadow Generator itself
  74959. */
  74960. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  74961. if (includeDescendants === void 0) { includeDescendants = true; }
  74962. var _a;
  74963. if (!this._shadowMap) {
  74964. return this;
  74965. }
  74966. if (!this._shadowMap.renderList) {
  74967. this._shadowMap.renderList = [];
  74968. }
  74969. this._shadowMap.renderList.push(mesh);
  74970. if (includeDescendants) {
  74971. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  74972. }
  74973. return this;
  74974. };
  74975. /**
  74976. * Helper function to remove a mesh and its descendants from the list of shadow casters
  74977. * @param mesh Mesh to remove
  74978. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  74979. * @returns the Shadow Generator itself
  74980. */
  74981. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  74982. if (includeDescendants === void 0) { includeDescendants = true; }
  74983. if (!this._shadowMap || !this._shadowMap.renderList) {
  74984. return this;
  74985. }
  74986. var index = this._shadowMap.renderList.indexOf(mesh);
  74987. if (index !== -1) {
  74988. this._shadowMap.renderList.splice(index, 1);
  74989. }
  74990. if (includeDescendants) {
  74991. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  74992. var child = _a[_i];
  74993. this.removeShadowCaster(child);
  74994. }
  74995. }
  74996. return this;
  74997. };
  74998. /**
  74999. * Returns the associated light object.
  75000. * @returns the light generating the shadow
  75001. */
  75002. ShadowGenerator.prototype.getLight = function () {
  75003. return this._light;
  75004. };
  75005. ShadowGenerator.prototype._initializeGenerator = function () {
  75006. this._light._markMeshesAsLightDirty();
  75007. this._initializeShadowMap();
  75008. };
  75009. ShadowGenerator.prototype._initializeShadowMap = function () {
  75010. var _this = this;
  75011. // Render target
  75012. var engine = this._scene.getEngine();
  75013. if (engine.webGLVersion > 1) {
  75014. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  75015. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  75016. }
  75017. else {
  75018. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  75019. }
  75020. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75021. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75022. this._shadowMap.anisotropicFilteringLevel = 1;
  75023. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  75024. this._shadowMap.renderParticles = false;
  75025. this._shadowMap.ignoreCameraViewport = true;
  75026. // Record Face Index before render.
  75027. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  75028. _this._currentFaceIndex = faceIndex;
  75029. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  75030. engine.setColorWrite(false);
  75031. }
  75032. });
  75033. // Custom render function.
  75034. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  75035. // Blur if required afer render.
  75036. this._shadowMap.onAfterUnbindObservable.add(function () {
  75037. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  75038. engine.setColorWrite(true);
  75039. }
  75040. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  75041. return;
  75042. }
  75043. var shadowMap = _this.getShadowMapForRendering();
  75044. if (shadowMap) {
  75045. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  75046. }
  75047. });
  75048. // Clear according to the chosen filter.
  75049. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  75050. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  75051. this._shadowMap.onClearObservable.add(function (engine) {
  75052. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  75053. engine.clear(clearOne, false, true, false);
  75054. }
  75055. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  75056. engine.clear(clearZero, true, true, false);
  75057. }
  75058. else {
  75059. engine.clear(clearOne, true, true, false);
  75060. }
  75061. });
  75062. };
  75063. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  75064. var _this = this;
  75065. var engine = this._scene.getEngine();
  75066. var targetSize = this._mapSize / this.blurScale;
  75067. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  75068. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  75069. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75070. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75071. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  75072. }
  75073. if (this.useKernelBlur) {
  75074. 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);
  75075. this._kernelBlurXPostprocess.width = targetSize;
  75076. this._kernelBlurXPostprocess.height = targetSize;
  75077. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  75078. effect.setTexture("textureSampler", _this._shadowMap);
  75079. });
  75080. 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);
  75081. this._kernelBlurXPostprocess.autoClear = false;
  75082. this._kernelBlurYPostprocess.autoClear = false;
  75083. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  75084. this._kernelBlurXPostprocess.packedFloat = true;
  75085. this._kernelBlurYPostprocess.packedFloat = true;
  75086. }
  75087. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  75088. }
  75089. else {
  75090. 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);
  75091. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  75092. effect.setFloat2("screenSize", targetSize, targetSize);
  75093. effect.setTexture("textureSampler", _this._shadowMap);
  75094. });
  75095. this._boxBlurPostprocess.autoClear = false;
  75096. this._blurPostProcesses = [this._boxBlurPostprocess];
  75097. }
  75098. };
  75099. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  75100. var index;
  75101. var engine = this._scene.getEngine();
  75102. if (depthOnlySubMeshes.length) {
  75103. engine.setColorWrite(false);
  75104. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  75105. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  75106. }
  75107. engine.setColorWrite(true);
  75108. }
  75109. for (index = 0; index < opaqueSubMeshes.length; index++) {
  75110. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  75111. }
  75112. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  75113. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  75114. }
  75115. if (this._transparencyShadow) {
  75116. for (index = 0; index < transparentSubMeshes.length; index++) {
  75117. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  75118. }
  75119. }
  75120. };
  75121. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  75122. var _this = this;
  75123. var mesh = subMesh.getRenderingMesh();
  75124. var scene = this._scene;
  75125. var engine = scene.getEngine();
  75126. var material = subMesh.getMaterial();
  75127. if (!material) {
  75128. return;
  75129. }
  75130. // Culling
  75131. engine.setState(material.backFaceCulling);
  75132. // Managing instances
  75133. var batch = mesh._getInstancesRenderList(subMesh._id);
  75134. if (batch.mustReturn) {
  75135. return;
  75136. }
  75137. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  75138. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  75139. engine.enableEffect(this._effect);
  75140. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  75141. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  75142. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  75143. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  75144. this._effect.setVector3("lightData", this._cachedDirection);
  75145. }
  75146. else {
  75147. this._effect.setVector3("lightData", this._cachedPosition);
  75148. }
  75149. if (scene.activeCamera) {
  75150. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  75151. }
  75152. // Alpha test
  75153. if (material && material.needAlphaTesting()) {
  75154. var alphaTexture = material.getAlphaTestTexture();
  75155. if (alphaTexture) {
  75156. this._effect.setTexture("diffuseSampler", alphaTexture);
  75157. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  75158. }
  75159. }
  75160. // Bones
  75161. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  75162. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  75163. }
  75164. // Morph targets
  75165. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  75166. if (this.forceBackFacesOnly) {
  75167. engine.setState(true, 0, false, true);
  75168. }
  75169. // Draw
  75170. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  75171. if (this.forceBackFacesOnly) {
  75172. engine.setState(true, 0, false, false);
  75173. }
  75174. }
  75175. else {
  75176. // Need to reset refresh rate of the shadowMap
  75177. if (this._shadowMap) {
  75178. this._shadowMap.resetRefreshCounter();
  75179. }
  75180. }
  75181. };
  75182. ShadowGenerator.prototype._applyFilterValues = function () {
  75183. if (!this._shadowMap) {
  75184. return;
  75185. }
  75186. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  75187. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  75188. }
  75189. else {
  75190. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  75191. }
  75192. };
  75193. /**
  75194. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  75195. * @param onCompiled Callback triggered at the and of the effects compilation
  75196. * @param options Sets of optional options forcing the compilation with different modes
  75197. */
  75198. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  75199. var _this = this;
  75200. var localOptions = __assign({ useInstances: false }, options);
  75201. var shadowMap = this.getShadowMap();
  75202. if (!shadowMap) {
  75203. if (onCompiled) {
  75204. onCompiled(this);
  75205. }
  75206. return;
  75207. }
  75208. var renderList = shadowMap.renderList;
  75209. if (!renderList) {
  75210. if (onCompiled) {
  75211. onCompiled(this);
  75212. }
  75213. return;
  75214. }
  75215. var subMeshes = new Array();
  75216. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  75217. var mesh = renderList_1[_i];
  75218. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  75219. }
  75220. if (subMeshes.length === 0) {
  75221. if (onCompiled) {
  75222. onCompiled(this);
  75223. }
  75224. return;
  75225. }
  75226. var currentIndex = 0;
  75227. var checkReady = function () {
  75228. if (!_this._scene || !_this._scene.getEngine()) {
  75229. return;
  75230. }
  75231. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  75232. currentIndex++;
  75233. if (currentIndex >= subMeshes.length) {
  75234. if (onCompiled) {
  75235. onCompiled(_this);
  75236. }
  75237. return;
  75238. }
  75239. }
  75240. setTimeout(checkReady, 16);
  75241. };
  75242. checkReady();
  75243. };
  75244. /**
  75245. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  75246. * @param options Sets of optional options forcing the compilation with different modes
  75247. * @returns A promise that resolves when the compilation completes
  75248. */
  75249. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  75250. var _this = this;
  75251. return new Promise(function (resolve) {
  75252. _this.forceCompilation(function () {
  75253. resolve();
  75254. }, options);
  75255. });
  75256. };
  75257. /**
  75258. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  75259. * @param subMesh The submesh we want to render in the shadow map
  75260. * @param useInstances Defines wether will draw in the map using instances
  75261. * @returns true if ready otherwise, false
  75262. */
  75263. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  75264. var defines = [];
  75265. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  75266. defines.push("#define FLOAT");
  75267. }
  75268. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  75269. defines.push("#define ESM");
  75270. }
  75271. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  75272. defines.push("#define DEPTHTEXTURE");
  75273. }
  75274. var attribs = [BABYLON.VertexBuffer.PositionKind];
  75275. var mesh = subMesh.getMesh();
  75276. var material = subMesh.getMaterial();
  75277. // Normal bias.
  75278. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  75279. attribs.push(BABYLON.VertexBuffer.NormalKind);
  75280. defines.push("#define NORMAL");
  75281. if (mesh.nonUniformScaling) {
  75282. defines.push("#define NONUNIFORMSCALING");
  75283. }
  75284. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  75285. defines.push("#define DIRECTIONINLIGHTDATA");
  75286. }
  75287. }
  75288. // Alpha test
  75289. if (material && material.needAlphaTesting()) {
  75290. var alphaTexture = material.getAlphaTestTexture();
  75291. if (alphaTexture) {
  75292. defines.push("#define ALPHATEST");
  75293. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  75294. attribs.push(BABYLON.VertexBuffer.UVKind);
  75295. defines.push("#define UV1");
  75296. }
  75297. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  75298. if (alphaTexture.coordinatesIndex === 1) {
  75299. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  75300. defines.push("#define UV2");
  75301. }
  75302. }
  75303. }
  75304. }
  75305. // Bones
  75306. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  75307. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  75308. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  75309. if (mesh.numBoneInfluencers > 4) {
  75310. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  75311. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  75312. }
  75313. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  75314. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  75315. }
  75316. else {
  75317. defines.push("#define NUM_BONE_INFLUENCERS 0");
  75318. }
  75319. // Morph targets
  75320. var manager = mesh.morphTargetManager;
  75321. var morphInfluencers = 0;
  75322. if (manager) {
  75323. if (manager.numInfluencers > 0) {
  75324. defines.push("#define MORPHTARGETS");
  75325. morphInfluencers = manager.numInfluencers;
  75326. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  75327. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  75328. }
  75329. }
  75330. // Instances
  75331. if (useInstances) {
  75332. defines.push("#define INSTANCES");
  75333. attribs.push("world0");
  75334. attribs.push("world1");
  75335. attribs.push("world2");
  75336. attribs.push("world3");
  75337. }
  75338. // Get correct effect
  75339. var join = defines.join("\n");
  75340. if (this._cachedDefines !== join) {
  75341. this._cachedDefines = join;
  75342. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  75343. }
  75344. if (!this._effect.isReady()) {
  75345. return false;
  75346. }
  75347. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  75348. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  75349. this._initializeBlurRTTAndPostProcesses();
  75350. }
  75351. }
  75352. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  75353. return false;
  75354. }
  75355. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  75356. return false;
  75357. }
  75358. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  75359. return false;
  75360. }
  75361. return true;
  75362. };
  75363. /**
  75364. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  75365. * @param defines Defines of the material we want to update
  75366. * @param lightIndex Index of the light in the enabled light list of the material
  75367. */
  75368. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  75369. var scene = this._scene;
  75370. var light = this._light;
  75371. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  75372. return;
  75373. }
  75374. defines["SHADOW" + lightIndex] = true;
  75375. if (this.useContactHardeningShadow) {
  75376. defines["SHADOWPCSS" + lightIndex] = true;
  75377. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  75378. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  75379. }
  75380. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  75381. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  75382. }
  75383. // else default to high.
  75384. }
  75385. if (this.usePercentageCloserFiltering) {
  75386. defines["SHADOWPCF" + lightIndex] = true;
  75387. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  75388. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  75389. }
  75390. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  75391. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  75392. }
  75393. // else default to high.
  75394. }
  75395. else if (this.usePoissonSampling) {
  75396. defines["SHADOWPOISSON" + lightIndex] = true;
  75397. }
  75398. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  75399. defines["SHADOWESM" + lightIndex] = true;
  75400. }
  75401. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  75402. defines["SHADOWCLOSEESM" + lightIndex] = true;
  75403. }
  75404. if (light.needCube()) {
  75405. defines["SHADOWCUBE" + lightIndex] = true;
  75406. }
  75407. };
  75408. /**
  75409. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  75410. * defined in the generator but impacting the effect).
  75411. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  75412. * @param effect The effect we are binfing the information for
  75413. */
  75414. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  75415. var light = this._light;
  75416. var scene = this._scene;
  75417. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  75418. return;
  75419. }
  75420. var camera = scene.activeCamera;
  75421. if (!camera) {
  75422. return;
  75423. }
  75424. var shadowMap = this.getShadowMap();
  75425. if (!shadowMap) {
  75426. return;
  75427. }
  75428. if (!light.needCube()) {
  75429. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  75430. }
  75431. // Only PCF uses depth stencil texture.
  75432. if (this._filter === ShadowGenerator.FILTER_PCF) {
  75433. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  75434. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  75435. }
  75436. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  75437. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  75438. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  75439. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  75440. }
  75441. else {
  75442. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  75443. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  75444. }
  75445. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  75446. };
  75447. /**
  75448. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  75449. * (eq to shadow prjection matrix * light transform matrix)
  75450. * @returns The transform matrix used to create the shadow map
  75451. */
  75452. ShadowGenerator.prototype.getTransformMatrix = function () {
  75453. var scene = this._scene;
  75454. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  75455. return this._transformMatrix;
  75456. }
  75457. this._currentRenderID = scene.getRenderId();
  75458. this._currentFaceIndexCache = this._currentFaceIndex;
  75459. var lightPosition = this._light.position;
  75460. if (this._light.computeTransformedInformation()) {
  75461. lightPosition = this._light.transformedPosition;
  75462. }
  75463. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  75464. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  75465. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  75466. }
  75467. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  75468. this._cachedPosition.copyFrom(lightPosition);
  75469. this._cachedDirection.copyFrom(this._lightDirection);
  75470. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  75471. var shadowMap = this.getShadowMap();
  75472. if (shadowMap) {
  75473. var renderList = shadowMap.renderList;
  75474. if (renderList) {
  75475. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  75476. }
  75477. }
  75478. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  75479. }
  75480. return this._transformMatrix;
  75481. };
  75482. /**
  75483. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  75484. * Cube and 2D textures for instance.
  75485. */
  75486. ShadowGenerator.prototype.recreateShadowMap = function () {
  75487. var shadowMap = this._shadowMap;
  75488. if (!shadowMap) {
  75489. return;
  75490. }
  75491. // Track render list.
  75492. var renderList = shadowMap.renderList;
  75493. // Clean up existing data.
  75494. this._disposeRTTandPostProcesses();
  75495. // Reinitializes.
  75496. this._initializeGenerator();
  75497. // Reaffect the filter to ensure a correct fallback if necessary.
  75498. this.filter = this.filter;
  75499. // Reaffect the filter.
  75500. this._applyFilterValues();
  75501. // Reaffect Render List.
  75502. this._shadowMap.renderList = renderList;
  75503. };
  75504. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  75505. if (this._shadowMap2) {
  75506. this._shadowMap2.dispose();
  75507. this._shadowMap2 = null;
  75508. }
  75509. if (this._boxBlurPostprocess) {
  75510. this._boxBlurPostprocess.dispose();
  75511. this._boxBlurPostprocess = null;
  75512. }
  75513. if (this._kernelBlurXPostprocess) {
  75514. this._kernelBlurXPostprocess.dispose();
  75515. this._kernelBlurXPostprocess = null;
  75516. }
  75517. if (this._kernelBlurYPostprocess) {
  75518. this._kernelBlurYPostprocess.dispose();
  75519. this._kernelBlurYPostprocess = null;
  75520. }
  75521. this._blurPostProcesses = [];
  75522. };
  75523. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  75524. if (this._shadowMap) {
  75525. this._shadowMap.dispose();
  75526. this._shadowMap = null;
  75527. }
  75528. this._disposeBlurPostProcesses();
  75529. };
  75530. /**
  75531. * Disposes the ShadowGenerator.
  75532. * Returns nothing.
  75533. */
  75534. ShadowGenerator.prototype.dispose = function () {
  75535. this._disposeRTTandPostProcesses();
  75536. if (this._light) {
  75537. this._light._shadowGenerator = null;
  75538. this._light._markMeshesAsLightDirty();
  75539. }
  75540. };
  75541. /**
  75542. * Serializes the shadow generator setup to a json object.
  75543. * @returns The serialized JSON object
  75544. */
  75545. ShadowGenerator.prototype.serialize = function () {
  75546. var serializationObject = {};
  75547. var shadowMap = this.getShadowMap();
  75548. if (!shadowMap) {
  75549. return serializationObject;
  75550. }
  75551. serializationObject.lightId = this._light.id;
  75552. serializationObject.mapSize = shadowMap.getRenderSize();
  75553. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  75554. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  75555. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  75556. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  75557. serializationObject.usePoissonSampling = this.usePoissonSampling;
  75558. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  75559. serializationObject.depthScale = this.depthScale;
  75560. serializationObject.darkness = this.getDarkness();
  75561. serializationObject.blurBoxOffset = this.blurBoxOffset;
  75562. serializationObject.blurKernel = this.blurKernel;
  75563. serializationObject.blurScale = this.blurScale;
  75564. serializationObject.useKernelBlur = this.useKernelBlur;
  75565. serializationObject.transparencyShadow = this._transparencyShadow;
  75566. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  75567. serializationObject.bias = this.bias;
  75568. serializationObject.normalBias = this.normalBias;
  75569. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  75570. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  75571. serializationObject.filteringQuality = this.filteringQuality;
  75572. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  75573. serializationObject.renderList = [];
  75574. if (shadowMap.renderList) {
  75575. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  75576. var mesh = shadowMap.renderList[meshIndex];
  75577. serializationObject.renderList.push(mesh.id);
  75578. }
  75579. }
  75580. return serializationObject;
  75581. };
  75582. /**
  75583. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  75584. * @param parsedShadowGenerator The JSON object to parse
  75585. * @param scene The scene to create the shadow map for
  75586. * @returns The parsed shadow generator
  75587. */
  75588. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  75589. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  75590. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  75591. var shadowMap = shadowGenerator.getShadowMap();
  75592. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  75593. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  75594. meshes.forEach(function (mesh) {
  75595. if (!shadowMap) {
  75596. return;
  75597. }
  75598. if (!shadowMap.renderList) {
  75599. shadowMap.renderList = [];
  75600. }
  75601. shadowMap.renderList.push(mesh);
  75602. });
  75603. }
  75604. if (parsedShadowGenerator.usePoissonSampling) {
  75605. shadowGenerator.usePoissonSampling = true;
  75606. }
  75607. else if (parsedShadowGenerator.useExponentialShadowMap) {
  75608. shadowGenerator.useExponentialShadowMap = true;
  75609. }
  75610. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  75611. shadowGenerator.useBlurExponentialShadowMap = true;
  75612. }
  75613. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  75614. shadowGenerator.useCloseExponentialShadowMap = true;
  75615. }
  75616. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  75617. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  75618. }
  75619. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  75620. shadowGenerator.usePercentageCloserFiltering = true;
  75621. }
  75622. else if (parsedShadowGenerator.useContactHardeningShadow) {
  75623. shadowGenerator.useContactHardeningShadow = true;
  75624. }
  75625. if (parsedShadowGenerator.filteringQuality) {
  75626. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  75627. }
  75628. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  75629. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  75630. }
  75631. // Backward compat
  75632. else if (parsedShadowGenerator.useVarianceShadowMap) {
  75633. shadowGenerator.useExponentialShadowMap = true;
  75634. }
  75635. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  75636. shadowGenerator.useBlurExponentialShadowMap = true;
  75637. }
  75638. if (parsedShadowGenerator.depthScale) {
  75639. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  75640. }
  75641. if (parsedShadowGenerator.blurScale) {
  75642. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  75643. }
  75644. if (parsedShadowGenerator.blurBoxOffset) {
  75645. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  75646. }
  75647. if (parsedShadowGenerator.useKernelBlur) {
  75648. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  75649. }
  75650. if (parsedShadowGenerator.blurKernel) {
  75651. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  75652. }
  75653. if (parsedShadowGenerator.bias !== undefined) {
  75654. shadowGenerator.bias = parsedShadowGenerator.bias;
  75655. }
  75656. if (parsedShadowGenerator.normalBias !== undefined) {
  75657. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  75658. }
  75659. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  75660. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  75661. }
  75662. if (parsedShadowGenerator.darkness) {
  75663. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  75664. }
  75665. if (parsedShadowGenerator.transparencyShadow) {
  75666. shadowGenerator.setTransparencyShadow(true);
  75667. }
  75668. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  75669. return shadowGenerator;
  75670. };
  75671. /**
  75672. * Shadow generator mode None: no filtering applied.
  75673. */
  75674. ShadowGenerator.FILTER_NONE = 0;
  75675. /**
  75676. * Shadow generator mode ESM: Exponential Shadow Mapping.
  75677. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  75678. */
  75679. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  75680. /**
  75681. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  75682. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  75683. */
  75684. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  75685. /**
  75686. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  75687. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  75688. */
  75689. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  75690. /**
  75691. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  75692. * edge artifacts on steep falloff.
  75693. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  75694. */
  75695. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  75696. /**
  75697. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  75698. * edge artifacts on steep falloff.
  75699. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  75700. */
  75701. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  75702. /**
  75703. * Shadow generator mode PCF: Percentage Closer Filtering
  75704. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  75705. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  75706. */
  75707. ShadowGenerator.FILTER_PCF = 6;
  75708. /**
  75709. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  75710. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  75711. * Contact Hardening
  75712. */
  75713. ShadowGenerator.FILTER_PCSS = 7;
  75714. /**
  75715. * Reserved for PCF and PCSS
  75716. * Highest Quality.
  75717. *
  75718. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  75719. *
  75720. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  75721. */
  75722. ShadowGenerator.QUALITY_HIGH = 0;
  75723. /**
  75724. * Reserved for PCF and PCSS
  75725. * Good tradeoff for quality/perf cross devices
  75726. *
  75727. * Execute PCF on a 3*3 kernel.
  75728. *
  75729. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  75730. */
  75731. ShadowGenerator.QUALITY_MEDIUM = 1;
  75732. /**
  75733. * Reserved for PCF and PCSS
  75734. * The lowest quality but the fastest.
  75735. *
  75736. * Execute PCF on a 1*1 kernel.
  75737. *
  75738. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  75739. */
  75740. ShadowGenerator.QUALITY_LOW = 2;
  75741. return ShadowGenerator;
  75742. }());
  75743. BABYLON.ShadowGenerator = ShadowGenerator;
  75744. })(BABYLON || (BABYLON = {}));
  75745. //# sourceMappingURL=babylon.shadowGenerator.js.map
  75746. var BABYLON;
  75747. (function (BABYLON) {
  75748. // Adds the parser to the scene parsers.
  75749. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR, function (parsedData, scene, container, rootUrl) {
  75750. // Shadows
  75751. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  75752. for (var index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  75753. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  75754. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  75755. // SG would be available on their associated lights
  75756. }
  75757. }
  75758. });
  75759. /**
  75760. * Defines the shadow generator component responsible to manage any shadow generators
  75761. * in a given scene.
  75762. */
  75763. var ShadowGeneratorSceneComponent = /** @class */ (function () {
  75764. /**
  75765. * Creates a new instance of the component for the given scene
  75766. * @param scene Defines the scene to register the component in
  75767. */
  75768. function ShadowGeneratorSceneComponent(scene) {
  75769. /**
  75770. * The component name helpfull to identify the component in the list of scene components.
  75771. */
  75772. this.name = BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR;
  75773. this.scene = scene;
  75774. }
  75775. /**
  75776. * Registers the component in a given scene
  75777. */
  75778. ShadowGeneratorSceneComponent.prototype.register = function () {
  75779. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR, this, this._gatherRenderTargets);
  75780. };
  75781. /**
  75782. * Rebuilds the elements related to this component in case of
  75783. * context lost for instance.
  75784. */
  75785. ShadowGeneratorSceneComponent.prototype.rebuild = function () {
  75786. // Nothing To Do Here.
  75787. };
  75788. /**
  75789. * Serializes the component data to the specified json object
  75790. * @param serializationObject The object to serialize to
  75791. */
  75792. ShadowGeneratorSceneComponent.prototype.serialize = function (serializationObject) {
  75793. // Shadows
  75794. serializationObject.shadowGenerators = [];
  75795. var lights = this.scene.lights;
  75796. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  75797. var light = lights_1[_i];
  75798. var shadowGenerator = light.getShadowGenerator();
  75799. if (shadowGenerator) {
  75800. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  75801. }
  75802. }
  75803. };
  75804. /**
  75805. * Adds all the element from the container to the scene
  75806. * @param container the container holding the elements
  75807. */
  75808. ShadowGeneratorSceneComponent.prototype.addFromContainer = function (container) {
  75809. // Nothing To Do Here. (directly attached to a light)
  75810. };
  75811. /**
  75812. * Removes all the elements in the container from the scene
  75813. * @param container contains the elements to remove
  75814. */
  75815. ShadowGeneratorSceneComponent.prototype.removeFromContainer = function (container) {
  75816. // Nothing To Do Here. (directly attached to a light)
  75817. };
  75818. /**
  75819. * Rebuilds the elements related to this component in case of
  75820. * context lost for instance.
  75821. */
  75822. ShadowGeneratorSceneComponent.prototype.dispose = function () {
  75823. // Nothing To Do Here.
  75824. };
  75825. ShadowGeneratorSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  75826. // Shadows
  75827. var scene = this.scene;
  75828. if (this.scene.shadowsEnabled) {
  75829. for (var lightIndex = 0; lightIndex < scene.lights.length; lightIndex++) {
  75830. var light = scene.lights[lightIndex];
  75831. var shadowGenerator = light.getShadowGenerator();
  75832. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  75833. var shadowMap = (shadowGenerator.getShadowMap());
  75834. if (scene.textures.indexOf(shadowMap) !== -1) {
  75835. renderTargets.push(shadowMap);
  75836. }
  75837. }
  75838. }
  75839. }
  75840. };
  75841. return ShadowGeneratorSceneComponent;
  75842. }());
  75843. BABYLON.ShadowGeneratorSceneComponent = ShadowGeneratorSceneComponent;
  75844. })(BABYLON || (BABYLON = {}));
  75845. //# sourceMappingURL=babylon.shadowGeneratorSceneComponent.js.map
  75846. var BABYLON;
  75847. (function (BABYLON) {
  75848. /**
  75849. * Class used for the default loading screen
  75850. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  75851. */
  75852. var DefaultLoadingScreen = /** @class */ (function () {
  75853. /**
  75854. * Creates a new default loading screen
  75855. * @param _renderingCanvas defines the canvas used to render the scene
  75856. * @param _loadingText defines the default text to display
  75857. * @param _loadingDivBackgroundColor defines the default background color
  75858. */
  75859. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  75860. if (_loadingText === void 0) { _loadingText = ""; }
  75861. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  75862. var _this = this;
  75863. this._renderingCanvas = _renderingCanvas;
  75864. this._loadingText = _loadingText;
  75865. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  75866. // Resize
  75867. this._resizeLoadingUI = function () {
  75868. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  75869. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  75870. if (!_this._loadingDiv) {
  75871. return;
  75872. }
  75873. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  75874. _this._loadingDiv.style.left = canvasRect.left + "px";
  75875. _this._loadingDiv.style.top = canvasRect.top + "px";
  75876. _this._loadingDiv.style.width = canvasRect.width + "px";
  75877. _this._loadingDiv.style.height = canvasRect.height + "px";
  75878. };
  75879. }
  75880. /**
  75881. * Function called to display the loading screen
  75882. */
  75883. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  75884. if (this._loadingDiv) {
  75885. // Do not add a loading screen if there is already one
  75886. return;
  75887. }
  75888. this._loadingDiv = document.createElement("div");
  75889. this._loadingDiv.id = "babylonjsLoadingDiv";
  75890. this._loadingDiv.style.opacity = "0";
  75891. this._loadingDiv.style.transition = "opacity 1.5s ease";
  75892. this._loadingDiv.style.pointerEvents = "none";
  75893. // Loading text
  75894. this._loadingTextDiv = document.createElement("div");
  75895. this._loadingTextDiv.style.position = "absolute";
  75896. this._loadingTextDiv.style.left = "0";
  75897. this._loadingTextDiv.style.top = "50%";
  75898. this._loadingTextDiv.style.marginTop = "80px";
  75899. this._loadingTextDiv.style.width = "100%";
  75900. this._loadingTextDiv.style.height = "20px";
  75901. this._loadingTextDiv.style.fontFamily = "Arial";
  75902. this._loadingTextDiv.style.fontSize = "14px";
  75903. this._loadingTextDiv.style.color = "white";
  75904. this._loadingTextDiv.style.textAlign = "center";
  75905. this._loadingTextDiv.innerHTML = "Loading";
  75906. this._loadingDiv.appendChild(this._loadingTextDiv);
  75907. //set the predefined text
  75908. this._loadingTextDiv.innerHTML = this._loadingText;
  75909. // Generating keyframes
  75910. var style = document.createElement('style');
  75911. style.type = 'text/css';
  75912. 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 }";
  75913. style.innerHTML = keyFrames;
  75914. document.getElementsByTagName('head')[0].appendChild(style);
  75915. // Loading img
  75916. var imgBack = new Image();
  75917. 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";
  75918. imgBack.style.position = "absolute";
  75919. imgBack.style.left = "50%";
  75920. imgBack.style.top = "50%";
  75921. imgBack.style.marginLeft = "-60px";
  75922. imgBack.style.marginTop = "-60px";
  75923. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  75924. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  75925. imgBack.style.transformOrigin = "50% 50%";
  75926. imgBack.style.webkitTransformOrigin = "50% 50%";
  75927. this._loadingDiv.appendChild(imgBack);
  75928. this._resizeLoadingUI();
  75929. window.addEventListener("resize", this._resizeLoadingUI);
  75930. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  75931. document.body.appendChild(this._loadingDiv);
  75932. this._loadingDiv.style.opacity = "1";
  75933. };
  75934. /**
  75935. * Function called to hide the loading screen
  75936. */
  75937. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  75938. var _this = this;
  75939. if (!this._loadingDiv) {
  75940. return;
  75941. }
  75942. var onTransitionEnd = function () {
  75943. if (!_this._loadingDiv) {
  75944. return;
  75945. }
  75946. document.body.removeChild(_this._loadingDiv);
  75947. window.removeEventListener("resize", _this._resizeLoadingUI);
  75948. _this._loadingDiv = null;
  75949. };
  75950. this._loadingDiv.style.opacity = "0";
  75951. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  75952. };
  75953. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  75954. get: function () {
  75955. return this._loadingText;
  75956. },
  75957. /**
  75958. * Gets or sets the text to display while loading
  75959. */
  75960. set: function (text) {
  75961. this._loadingText = text;
  75962. if (this._loadingTextDiv) {
  75963. this._loadingTextDiv.innerHTML = this._loadingText;
  75964. }
  75965. },
  75966. enumerable: true,
  75967. configurable: true
  75968. });
  75969. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  75970. /**
  75971. * Gets or sets the color to use for the background
  75972. */
  75973. get: function () {
  75974. return this._loadingDivBackgroundColor;
  75975. },
  75976. set: function (color) {
  75977. this._loadingDivBackgroundColor = color;
  75978. if (!this._loadingDiv) {
  75979. return;
  75980. }
  75981. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  75982. },
  75983. enumerable: true,
  75984. configurable: true
  75985. });
  75986. return DefaultLoadingScreen;
  75987. }());
  75988. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  75989. })(BABYLON || (BABYLON = {}));
  75990. //# sourceMappingURL=babylon.loadingScreen.js.map
  75991. var BABYLON;
  75992. (function (BABYLON) {
  75993. /**
  75994. * Class used to represent data loading progression
  75995. */
  75996. var SceneLoaderProgressEvent = /** @class */ (function () {
  75997. /**
  75998. * Create a new progress event
  75999. * @param lengthComputable defines if data length to load can be evaluated
  76000. * @param loaded defines the loaded data length
  76001. * @param total defines the data length to load
  76002. */
  76003. function SceneLoaderProgressEvent(
  76004. /** defines if data length to load can be evaluated */
  76005. lengthComputable,
  76006. /** defines the loaded data length */
  76007. loaded,
  76008. /** defines the data length to load */
  76009. total) {
  76010. this.lengthComputable = lengthComputable;
  76011. this.loaded = loaded;
  76012. this.total = total;
  76013. }
  76014. /**
  76015. * Creates a new SceneLoaderProgressEvent from a ProgressEvent
  76016. * @param event defines the source event
  76017. * @returns a new SceneLoaderProgressEvent
  76018. */
  76019. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  76020. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  76021. };
  76022. return SceneLoaderProgressEvent;
  76023. }());
  76024. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  76025. /**
  76026. * Class used to load scene from various file formats using registered plugins
  76027. * @see http://doc.babylonjs.com/how_to/load_from_any_file_type
  76028. */
  76029. var SceneLoader = /** @class */ (function () {
  76030. function SceneLoader() {
  76031. }
  76032. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  76033. /**
  76034. * Gets or sets a boolean indicating if entire scene must be loaded even if scene contains incremental data
  76035. */
  76036. get: function () {
  76037. return SceneLoader._ForceFullSceneLoadingForIncremental;
  76038. },
  76039. set: function (value) {
  76040. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  76041. },
  76042. enumerable: true,
  76043. configurable: true
  76044. });
  76045. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  76046. /**
  76047. * Gets or sets a boolean indicating if loading screen must be displayed while loading a scene
  76048. */
  76049. get: function () {
  76050. return SceneLoader._ShowLoadingScreen;
  76051. },
  76052. set: function (value) {
  76053. SceneLoader._ShowLoadingScreen = value;
  76054. },
  76055. enumerable: true,
  76056. configurable: true
  76057. });
  76058. Object.defineProperty(SceneLoader, "loggingLevel", {
  76059. /**
  76060. * Defines the current logging level (while loading the scene)
  76061. * @ignorenaming
  76062. */
  76063. get: function () {
  76064. return SceneLoader._loggingLevel;
  76065. },
  76066. set: function (value) {
  76067. SceneLoader._loggingLevel = value;
  76068. },
  76069. enumerable: true,
  76070. configurable: true
  76071. });
  76072. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  76073. /**
  76074. * Gets or set a boolean indicating if matrix weights must be cleaned upon loading
  76075. */
  76076. get: function () {
  76077. return SceneLoader._CleanBoneMatrixWeights;
  76078. },
  76079. set: function (value) {
  76080. SceneLoader._CleanBoneMatrixWeights = value;
  76081. },
  76082. enumerable: true,
  76083. configurable: true
  76084. });
  76085. SceneLoader._getDefaultPlugin = function () {
  76086. return SceneLoader._registeredPlugins[".babylon"];
  76087. };
  76088. SceneLoader._getPluginForExtension = function (extension) {
  76089. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  76090. if (registeredPlugin) {
  76091. return registeredPlugin;
  76092. }
  76093. 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");
  76094. return SceneLoader._getDefaultPlugin();
  76095. };
  76096. SceneLoader._getPluginForDirectLoad = function (data) {
  76097. for (var extension in SceneLoader._registeredPlugins) {
  76098. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  76099. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  76100. return SceneLoader._registeredPlugins[extension];
  76101. }
  76102. }
  76103. return SceneLoader._getDefaultPlugin();
  76104. };
  76105. SceneLoader._getPluginForFilename = function (sceneFilename) {
  76106. var queryStringPosition = sceneFilename.indexOf("?");
  76107. if (queryStringPosition !== -1) {
  76108. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  76109. }
  76110. var dotPosition = sceneFilename.lastIndexOf(".");
  76111. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  76112. return SceneLoader._getPluginForExtension(extension);
  76113. };
  76114. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  76115. SceneLoader._getDirectLoad = function (sceneFilename) {
  76116. if (sceneFilename.substr(0, 5) === "data:") {
  76117. return sceneFilename.substr(5);
  76118. }
  76119. return null;
  76120. };
  76121. SceneLoader._loadData = function (fileInfo, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  76122. var directLoad = SceneLoader._getDirectLoad(fileInfo.name);
  76123. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(fileInfo.name) : SceneLoader._getPluginForFilename(fileInfo.name));
  76124. var plugin;
  76125. if (registeredPlugin.plugin.createPlugin) {
  76126. plugin = registeredPlugin.plugin.createPlugin();
  76127. }
  76128. else {
  76129. plugin = registeredPlugin.plugin;
  76130. }
  76131. var useArrayBuffer = registeredPlugin.isBinary;
  76132. var database;
  76133. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  76134. var dataCallback = function (data, responseURL) {
  76135. if (scene.isDisposed) {
  76136. onError("Scene has been disposed");
  76137. return;
  76138. }
  76139. scene.database = database;
  76140. onSuccess(plugin, data, responseURL);
  76141. };
  76142. var request = null;
  76143. var pluginDisposed = false;
  76144. var onDisposeObservable = plugin.onDisposeObservable;
  76145. if (onDisposeObservable) {
  76146. onDisposeObservable.add(function () {
  76147. pluginDisposed = true;
  76148. if (request) {
  76149. request.abort();
  76150. request = null;
  76151. }
  76152. onDispose();
  76153. });
  76154. }
  76155. var manifestChecked = function () {
  76156. if (pluginDisposed) {
  76157. return;
  76158. }
  76159. request = BABYLON.Tools.LoadFile(fileInfo.url, dataCallback, onProgress ? function (event) {
  76160. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  76161. } : undefined, database, useArrayBuffer, function (request, exception) {
  76162. onError("Failed to load scene." + (exception ? " " + exception.message : ""), exception);
  76163. });
  76164. };
  76165. if (directLoad) {
  76166. dataCallback(directLoad);
  76167. return plugin;
  76168. }
  76169. if (fileInfo.rootUrl.indexOf("file:") === -1) {
  76170. var engine = scene.getEngine();
  76171. var canUseOfflineSupport = engine.enableOfflineSupport;
  76172. if (canUseOfflineSupport) {
  76173. // Also check for exceptions
  76174. var exceptionFound = false;
  76175. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  76176. var regex = _a[_i];
  76177. if (regex.test(fileInfo.url)) {
  76178. exceptionFound = true;
  76179. break;
  76180. }
  76181. }
  76182. canUseOfflineSupport = !exceptionFound;
  76183. }
  76184. if (canUseOfflineSupport) {
  76185. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  76186. database = new BABYLON.Database(fileInfo.url, manifestChecked, engine.disableManifestCheck);
  76187. }
  76188. else {
  76189. manifestChecked();
  76190. }
  76191. }
  76192. // Loading file from disk via input file or drag'n'drop
  76193. else {
  76194. var file = BABYLON.FilesInput.FilesToLoad[fileInfo.name.toLowerCase()];
  76195. if (file) {
  76196. request = BABYLON.Tools.ReadFile(file, dataCallback, onProgress, useArrayBuffer);
  76197. }
  76198. else {
  76199. onError("Unable to find file named " + fileInfo.name);
  76200. }
  76201. }
  76202. return plugin;
  76203. };
  76204. SceneLoader._getFileInfo = function (rootUrl, sceneFilename) {
  76205. var url;
  76206. var name;
  76207. if (!sceneFilename) {
  76208. url = rootUrl;
  76209. name = BABYLON.Tools.GetFilename(rootUrl);
  76210. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  76211. }
  76212. else {
  76213. if (sceneFilename.substr(0, 1) === "/") {
  76214. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  76215. return null;
  76216. }
  76217. url = rootUrl + sceneFilename;
  76218. name = sceneFilename;
  76219. }
  76220. ;
  76221. return {
  76222. url: url,
  76223. rootUrl: rootUrl,
  76224. name: name
  76225. };
  76226. };
  76227. // Public functions
  76228. /**
  76229. * Gets a plugin that can load the given extension
  76230. * @param extension defines the extension to load
  76231. * @returns a plugin or null if none works
  76232. */
  76233. SceneLoader.GetPluginForExtension = function (extension) {
  76234. return SceneLoader._getPluginForExtension(extension).plugin;
  76235. };
  76236. /**
  76237. * Gets a boolean indicating that the given extension can be loaded
  76238. * @param extension defines the extension to load
  76239. * @returns true if the extension is supported
  76240. */
  76241. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  76242. return !!SceneLoader._registeredPlugins[extension];
  76243. };
  76244. /**
  76245. * Adds a new plugin to the list of registered plugins
  76246. * @param plugin defines the plugin to add
  76247. */
  76248. SceneLoader.RegisterPlugin = function (plugin) {
  76249. if (typeof plugin.extensions === "string") {
  76250. var extension = plugin.extensions;
  76251. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  76252. plugin: plugin,
  76253. isBinary: false
  76254. };
  76255. }
  76256. else {
  76257. var extensions = plugin.extensions;
  76258. Object.keys(extensions).forEach(function (extension) {
  76259. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  76260. plugin: plugin,
  76261. isBinary: extensions[extension].isBinary
  76262. };
  76263. });
  76264. }
  76265. };
  76266. /**
  76267. * Import meshes into a scene
  76268. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  76269. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  76270. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  76271. * @param scene the instance of BABYLON.Scene to append to
  76272. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  76273. * @param onProgress a callback with a progress event for each file being loaded
  76274. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  76275. * @param pluginExtension the extension used to determine the plugin
  76276. * @returns The loaded plugin
  76277. */
  76278. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  76279. if (sceneFilename === void 0) { sceneFilename = ""; }
  76280. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  76281. if (onSuccess === void 0) { onSuccess = null; }
  76282. if (onProgress === void 0) { onProgress = null; }
  76283. if (onError === void 0) { onError = null; }
  76284. if (pluginExtension === void 0) { pluginExtension = null; }
  76285. if (!scene) {
  76286. BABYLON.Tools.Error("No scene available to import mesh to");
  76287. return null;
  76288. }
  76289. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  76290. if (!fileInfo) {
  76291. return null;
  76292. }
  76293. var loadingToken = {};
  76294. scene._addPendingData(loadingToken);
  76295. var disposeHandler = function () {
  76296. scene._removePendingData(loadingToken);
  76297. };
  76298. var errorHandler = function (message, exception) {
  76299. var errorMessage = "Unable to import meshes from " + fileInfo.url + ": " + message;
  76300. if (onError) {
  76301. onError(scene, errorMessage, exception);
  76302. }
  76303. else {
  76304. BABYLON.Tools.Error(errorMessage);
  76305. // should the exception be thrown?
  76306. }
  76307. disposeHandler();
  76308. };
  76309. var progressHandler = onProgress ? function (event) {
  76310. try {
  76311. onProgress(event);
  76312. }
  76313. catch (e) {
  76314. errorHandler("Error in onProgress callback", e);
  76315. }
  76316. } : undefined;
  76317. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  76318. scene.importedMeshesFiles.push(fileInfo.url);
  76319. if (onSuccess) {
  76320. try {
  76321. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  76322. }
  76323. catch (e) {
  76324. errorHandler("Error in onSuccess callback", e);
  76325. }
  76326. }
  76327. scene._removePendingData(loadingToken);
  76328. };
  76329. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  76330. if (plugin.rewriteRootURL) {
  76331. fileInfo.rootUrl = plugin.rewriteRootURL(fileInfo.rootUrl, responseURL);
  76332. }
  76333. if (plugin.importMesh) {
  76334. var syncedPlugin = plugin;
  76335. var meshes = new Array();
  76336. var particleSystems = new Array();
  76337. var skeletons = new Array();
  76338. if (!syncedPlugin.importMesh(meshNames, scene, data, fileInfo.rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  76339. return;
  76340. }
  76341. scene.loadingPluginName = plugin.name;
  76342. successHandler(meshes, particleSystems, skeletons, []);
  76343. }
  76344. else {
  76345. var asyncedPlugin = plugin;
  76346. asyncedPlugin.importMeshAsync(meshNames, scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function (result) {
  76347. scene.loadingPluginName = plugin.name;
  76348. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  76349. }).catch(function (error) {
  76350. errorHandler(error.message, error);
  76351. });
  76352. }
  76353. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  76354. };
  76355. /**
  76356. * Import meshes into a scene
  76357. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  76358. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  76359. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  76360. * @param scene the instance of BABYLON.Scene to append to
  76361. * @param onProgress a callback with a progress event for each file being loaded
  76362. * @param pluginExtension the extension used to determine the plugin
  76363. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  76364. */
  76365. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  76366. if (sceneFilename === void 0) { sceneFilename = ""; }
  76367. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  76368. if (onProgress === void 0) { onProgress = null; }
  76369. if (pluginExtension === void 0) { pluginExtension = null; }
  76370. return new Promise(function (resolve, reject) {
  76371. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  76372. resolve({
  76373. meshes: meshes,
  76374. particleSystems: particleSystems,
  76375. skeletons: skeletons,
  76376. animationGroups: animationGroups
  76377. });
  76378. }, onProgress, function (scene, message, exception) {
  76379. reject(exception || new Error(message));
  76380. }, pluginExtension);
  76381. });
  76382. };
  76383. /**
  76384. * Load a scene
  76385. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  76386. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  76387. * @param engine is the instance of BABYLON.Engine to use to create the scene
  76388. * @param onSuccess a callback with the scene when import succeeds
  76389. * @param onProgress a callback with a progress event for each file being loaded
  76390. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  76391. * @param pluginExtension the extension used to determine the plugin
  76392. * @returns The loaded plugin
  76393. */
  76394. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  76395. if (onSuccess === void 0) { onSuccess = null; }
  76396. if (onProgress === void 0) { onProgress = null; }
  76397. if (onError === void 0) { onError = null; }
  76398. if (pluginExtension === void 0) { pluginExtension = null; }
  76399. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  76400. };
  76401. /**
  76402. * Load a scene
  76403. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  76404. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  76405. * @param engine is the instance of BABYLON.Engine to use to create the scene
  76406. * @param onProgress a callback with a progress event for each file being loaded
  76407. * @param pluginExtension the extension used to determine the plugin
  76408. * @returns The loaded scene
  76409. */
  76410. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  76411. if (onProgress === void 0) { onProgress = null; }
  76412. if (pluginExtension === void 0) { pluginExtension = null; }
  76413. return new Promise(function (resolve, reject) {
  76414. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  76415. resolve(scene);
  76416. }, onProgress, function (scene, message, exception) {
  76417. reject(exception || new Error(message));
  76418. }, pluginExtension);
  76419. });
  76420. };
  76421. /**
  76422. * Append a scene
  76423. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  76424. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  76425. * @param scene is the instance of BABYLON.Scene to append to
  76426. * @param onSuccess a callback with the scene when import succeeds
  76427. * @param onProgress a callback with a progress event for each file being loaded
  76428. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  76429. * @param pluginExtension the extension used to determine the plugin
  76430. * @returns The loaded plugin
  76431. */
  76432. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  76433. if (sceneFilename === void 0) { sceneFilename = ""; }
  76434. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  76435. if (onSuccess === void 0) { onSuccess = null; }
  76436. if (onProgress === void 0) { onProgress = null; }
  76437. if (onError === void 0) { onError = null; }
  76438. if (pluginExtension === void 0) { pluginExtension = null; }
  76439. if (!scene) {
  76440. BABYLON.Tools.Error("No scene available to append to");
  76441. return null;
  76442. }
  76443. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  76444. if (!fileInfo) {
  76445. return null;
  76446. }
  76447. if (SceneLoader.ShowLoadingScreen) {
  76448. scene.getEngine().displayLoadingUI();
  76449. }
  76450. var loadingToken = {};
  76451. scene._addPendingData(loadingToken);
  76452. var disposeHandler = function () {
  76453. scene._removePendingData(loadingToken);
  76454. scene.getEngine().hideLoadingUI();
  76455. };
  76456. var errorHandler = function (message, exception) {
  76457. var errorMessage = "Unable to load from " + fileInfo.url + (message ? ": " + message : "");
  76458. if (onError) {
  76459. onError(scene, errorMessage, exception);
  76460. }
  76461. else {
  76462. BABYLON.Tools.Error(errorMessage);
  76463. // should the exception be thrown?
  76464. }
  76465. disposeHandler();
  76466. };
  76467. var progressHandler = onProgress ? function (event) {
  76468. try {
  76469. onProgress(event);
  76470. }
  76471. catch (e) {
  76472. errorHandler("Error in onProgress callback", e);
  76473. }
  76474. } : undefined;
  76475. var successHandler = function () {
  76476. if (onSuccess) {
  76477. try {
  76478. onSuccess(scene);
  76479. }
  76480. catch (e) {
  76481. errorHandler("Error in onSuccess callback", e);
  76482. }
  76483. }
  76484. scene._removePendingData(loadingToken);
  76485. };
  76486. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  76487. if (plugin.load) {
  76488. var syncedPlugin = plugin;
  76489. if (!syncedPlugin.load(scene, data, fileInfo.rootUrl, errorHandler)) {
  76490. return;
  76491. }
  76492. scene.loadingPluginName = plugin.name;
  76493. successHandler();
  76494. }
  76495. else {
  76496. var asyncedPlugin = plugin;
  76497. asyncedPlugin.loadAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function () {
  76498. scene.loadingPluginName = plugin.name;
  76499. successHandler();
  76500. }).catch(function (error) {
  76501. errorHandler(error.message, error);
  76502. });
  76503. }
  76504. if (SceneLoader.ShowLoadingScreen) {
  76505. scene.executeWhenReady(function () {
  76506. scene.getEngine().hideLoadingUI();
  76507. });
  76508. }
  76509. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  76510. };
  76511. /**
  76512. * Append a scene
  76513. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  76514. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  76515. * @param scene is the instance of BABYLON.Scene to append to
  76516. * @param onProgress a callback with a progress event for each file being loaded
  76517. * @param pluginExtension the extension used to determine the plugin
  76518. * @returns The given scene
  76519. */
  76520. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  76521. if (sceneFilename === void 0) { sceneFilename = ""; }
  76522. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  76523. if (onProgress === void 0) { onProgress = null; }
  76524. if (pluginExtension === void 0) { pluginExtension = null; }
  76525. return new Promise(function (resolve, reject) {
  76526. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  76527. resolve(scene);
  76528. }, onProgress, function (scene, message, exception) {
  76529. reject(exception || new Error(message));
  76530. }, pluginExtension);
  76531. });
  76532. };
  76533. /**
  76534. * Load a scene into an asset container
  76535. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  76536. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  76537. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  76538. * @param onSuccess a callback with the scene when import succeeds
  76539. * @param onProgress a callback with a progress event for each file being loaded
  76540. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  76541. * @param pluginExtension the extension used to determine the plugin
  76542. * @returns The loaded plugin
  76543. */
  76544. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  76545. if (sceneFilename === void 0) { sceneFilename = ""; }
  76546. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  76547. if (onSuccess === void 0) { onSuccess = null; }
  76548. if (onProgress === void 0) { onProgress = null; }
  76549. if (onError === void 0) { onError = null; }
  76550. if (pluginExtension === void 0) { pluginExtension = null; }
  76551. if (!scene) {
  76552. BABYLON.Tools.Error("No scene available to load asset container to");
  76553. return null;
  76554. }
  76555. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  76556. if (!fileInfo) {
  76557. return null;
  76558. }
  76559. var loadingToken = {};
  76560. scene._addPendingData(loadingToken);
  76561. var disposeHandler = function () {
  76562. scene._removePendingData(loadingToken);
  76563. };
  76564. var errorHandler = function (message, exception) {
  76565. var errorMessage = "Unable to load assets from " + fileInfo.url + (message ? ": " + message : "");
  76566. if (onError) {
  76567. onError(scene, errorMessage, exception);
  76568. }
  76569. else {
  76570. BABYLON.Tools.Error(errorMessage);
  76571. // should the exception be thrown?
  76572. }
  76573. disposeHandler();
  76574. };
  76575. var progressHandler = onProgress ? function (event) {
  76576. try {
  76577. onProgress(event);
  76578. }
  76579. catch (e) {
  76580. errorHandler("Error in onProgress callback", e);
  76581. }
  76582. } : undefined;
  76583. var successHandler = function (assets) {
  76584. if (onSuccess) {
  76585. try {
  76586. onSuccess(assets);
  76587. }
  76588. catch (e) {
  76589. errorHandler("Error in onSuccess callback", e);
  76590. }
  76591. }
  76592. scene._removePendingData(loadingToken);
  76593. };
  76594. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  76595. if (plugin.loadAssetContainer) {
  76596. var syncedPlugin = plugin;
  76597. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, fileInfo.rootUrl, errorHandler);
  76598. if (!assetContainer) {
  76599. return;
  76600. }
  76601. scene.loadingPluginName = plugin.name;
  76602. successHandler(assetContainer);
  76603. }
  76604. else if (plugin.loadAssetContainerAsync) {
  76605. var asyncedPlugin = plugin;
  76606. asyncedPlugin.loadAssetContainerAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function (assetContainer) {
  76607. scene.loadingPluginName = plugin.name;
  76608. successHandler(assetContainer);
  76609. }).catch(function (error) {
  76610. errorHandler(error.message, error);
  76611. });
  76612. }
  76613. else {
  76614. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  76615. }
  76616. if (SceneLoader.ShowLoadingScreen) {
  76617. scene.executeWhenReady(function () {
  76618. scene.getEngine().hideLoadingUI();
  76619. });
  76620. }
  76621. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  76622. };
  76623. /**
  76624. * Load a scene into an asset container
  76625. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  76626. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  76627. * @param scene is the instance of BABYLON.Scene to append to
  76628. * @param onProgress a callback with a progress event for each file being loaded
  76629. * @param pluginExtension the extension used to determine the plugin
  76630. * @returns The loaded asset container
  76631. */
  76632. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  76633. if (sceneFilename === void 0) { sceneFilename = ""; }
  76634. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  76635. if (onProgress === void 0) { onProgress = null; }
  76636. if (pluginExtension === void 0) { pluginExtension = null; }
  76637. return new Promise(function (resolve, reject) {
  76638. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  76639. resolve(assetContainer);
  76640. }, onProgress, function (scene, message, exception) {
  76641. reject(exception || new Error(message));
  76642. }, pluginExtension);
  76643. });
  76644. };
  76645. // Flags
  76646. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  76647. SceneLoader._ShowLoadingScreen = true;
  76648. SceneLoader._CleanBoneMatrixWeights = false;
  76649. /**
  76650. * No logging while loading
  76651. */
  76652. SceneLoader.NO_LOGGING = 0;
  76653. /**
  76654. * Minimal logging while loading
  76655. */
  76656. SceneLoader.MINIMAL_LOGGING = 1;
  76657. /**
  76658. * Summary logging while loading
  76659. */
  76660. SceneLoader.SUMMARY_LOGGING = 2;
  76661. /**
  76662. * Detailled logging while loading
  76663. */
  76664. SceneLoader.DETAILED_LOGGING = 3;
  76665. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  76666. // Members
  76667. /**
  76668. * Event raised when a plugin is used to load a scene
  76669. */
  76670. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  76671. SceneLoader._registeredPlugins = {};
  76672. return SceneLoader;
  76673. }());
  76674. BABYLON.SceneLoader = SceneLoader;
  76675. ;
  76676. })(BABYLON || (BABYLON = {}));
  76677. //# sourceMappingURL=babylon.sceneLoader.js.map
  76678. var BABYLON;
  76679. (function (BABYLON) {
  76680. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  76681. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  76682. var parsedMaterial = parsedData.materials[index];
  76683. if (parsedMaterial.id === id) {
  76684. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  76685. }
  76686. }
  76687. return null;
  76688. };
  76689. var isDescendantOf = function (mesh, names, hierarchyIds) {
  76690. for (var i in names) {
  76691. if (mesh.name === names[i]) {
  76692. hierarchyIds.push(mesh.id);
  76693. return true;
  76694. }
  76695. }
  76696. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  76697. hierarchyIds.push(mesh.id);
  76698. return true;
  76699. }
  76700. return false;
  76701. };
  76702. var logOperation = function (operation, producer) {
  76703. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  76704. };
  76705. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  76706. if (addToScene === void 0) { addToScene = false; }
  76707. var container = new BABYLON.AssetContainer(scene);
  76708. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  76709. // when SceneLoader.debugLogging = true (default), or exception encountered.
  76710. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  76711. // and avoid problems with multiple concurrent .babylon loads.
  76712. var log = "importScene has failed JSON parse";
  76713. try {
  76714. var parsedData = JSON.parse(data);
  76715. log = "";
  76716. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  76717. var index;
  76718. var cache;
  76719. // Lights
  76720. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  76721. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  76722. var parsedLight = parsedData.lights[index];
  76723. var light = BABYLON.Light.Parse(parsedLight, scene);
  76724. if (light) {
  76725. container.lights.push(light);
  76726. log += (index === 0 ? "\n\tLights:" : "");
  76727. log += "\n\t\t" + light.toString(fullDetails);
  76728. }
  76729. }
  76730. }
  76731. // Animations
  76732. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  76733. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  76734. var parsedAnimation = parsedData.animations[index];
  76735. var animation = BABYLON.Animation.Parse(parsedAnimation);
  76736. scene.animations.push(animation);
  76737. container.animations.push(animation);
  76738. log += (index === 0 ? "\n\tAnimations:" : "");
  76739. log += "\n\t\t" + animation.toString(fullDetails);
  76740. }
  76741. }
  76742. // Materials
  76743. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  76744. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  76745. var parsedMaterial = parsedData.materials[index];
  76746. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  76747. container.materials.push(mat);
  76748. log += (index === 0 ? "\n\tMaterials:" : "");
  76749. log += "\n\t\t" + mat.toString(fullDetails);
  76750. }
  76751. }
  76752. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  76753. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  76754. var parsedMultiMaterial = parsedData.multiMaterials[index];
  76755. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  76756. container.multiMaterials.push(mmat);
  76757. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  76758. log += "\n\t\t" + mmat.toString(fullDetails);
  76759. }
  76760. }
  76761. // Morph targets
  76762. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  76763. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  76764. var managerData = _a[_i];
  76765. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  76766. }
  76767. }
  76768. // Skeletons
  76769. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  76770. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  76771. var parsedSkeleton = parsedData.skeletons[index];
  76772. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  76773. container.skeletons.push(skeleton);
  76774. log += (index === 0 ? "\n\tSkeletons:" : "");
  76775. log += "\n\t\t" + skeleton.toString(fullDetails);
  76776. }
  76777. }
  76778. // Geometries
  76779. var geometries = parsedData.geometries;
  76780. if (geometries !== undefined && geometries !== null) {
  76781. var addedGeometry = new Array();
  76782. // Boxes
  76783. var boxes = geometries.boxes;
  76784. if (boxes !== undefined && boxes !== null) {
  76785. for (index = 0, cache = boxes.length; index < cache; index++) {
  76786. var parsedBox = boxes[index];
  76787. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  76788. }
  76789. }
  76790. // Spheres
  76791. var spheres = geometries.spheres;
  76792. if (spheres !== undefined && spheres !== null) {
  76793. for (index = 0, cache = spheres.length; index < cache; index++) {
  76794. var parsedSphere = spheres[index];
  76795. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  76796. }
  76797. }
  76798. // Cylinders
  76799. var cylinders = geometries.cylinders;
  76800. if (cylinders !== undefined && cylinders !== null) {
  76801. for (index = 0, cache = cylinders.length; index < cache; index++) {
  76802. var parsedCylinder = cylinders[index];
  76803. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  76804. }
  76805. }
  76806. // Toruses
  76807. var toruses = geometries.toruses;
  76808. if (toruses !== undefined && toruses !== null) {
  76809. for (index = 0, cache = toruses.length; index < cache; index++) {
  76810. var parsedTorus = toruses[index];
  76811. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  76812. }
  76813. }
  76814. // Grounds
  76815. var grounds = geometries.grounds;
  76816. if (grounds !== undefined && grounds !== null) {
  76817. for (index = 0, cache = grounds.length; index < cache; index++) {
  76818. var parsedGround = grounds[index];
  76819. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  76820. }
  76821. }
  76822. // Planes
  76823. var planes = geometries.planes;
  76824. if (planes !== undefined && planes !== null) {
  76825. for (index = 0, cache = planes.length; index < cache; index++) {
  76826. var parsedPlane = planes[index];
  76827. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  76828. }
  76829. }
  76830. // TorusKnots
  76831. var torusKnots = geometries.torusKnots;
  76832. if (torusKnots !== undefined && torusKnots !== null) {
  76833. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  76834. var parsedTorusKnot = torusKnots[index];
  76835. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  76836. }
  76837. }
  76838. // VertexData
  76839. var vertexData = geometries.vertexData;
  76840. if (vertexData !== undefined && vertexData !== null) {
  76841. for (index = 0, cache = vertexData.length; index < cache; index++) {
  76842. var parsedVertexData = vertexData[index];
  76843. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  76844. }
  76845. }
  76846. addedGeometry.forEach(function (g) {
  76847. if (g) {
  76848. container.geometries.push(g);
  76849. }
  76850. });
  76851. }
  76852. // Transform nodes
  76853. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  76854. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  76855. var parsedTransformNode = parsedData.transformNodes[index];
  76856. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  76857. container.transformNodes.push(node);
  76858. }
  76859. }
  76860. // Meshes
  76861. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  76862. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  76863. var parsedMesh = parsedData.meshes[index];
  76864. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  76865. container.meshes.push(mesh);
  76866. log += (index === 0 ? "\n\tMeshes:" : "");
  76867. log += "\n\t\t" + mesh.toString(fullDetails);
  76868. }
  76869. }
  76870. // Cameras
  76871. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  76872. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  76873. var parsedCamera = parsedData.cameras[index];
  76874. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  76875. container.cameras.push(camera);
  76876. log += (index === 0 ? "\n\tCameras:" : "");
  76877. log += "\n\t\t" + camera.toString(fullDetails);
  76878. }
  76879. }
  76880. // Animation Groups
  76881. if (parsedData.animationGroups !== undefined && parsedData.animationGroups !== null) {
  76882. for (index = 0, cache = parsedData.animationGroups.length; index < cache; index++) {
  76883. var parsedAnimationGroup = parsedData.animationGroups[index];
  76884. var animationGroup = BABYLON.AnimationGroup.Parse(parsedAnimationGroup, scene);
  76885. container.animationGroups.push(animationGroup);
  76886. log += (index === 0 ? "\n\tAnimationGroups:" : "");
  76887. log += "\n\t\t" + animationGroup.toString(fullDetails);
  76888. }
  76889. }
  76890. // Browsing all the graph to connect the dots
  76891. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  76892. var camera = scene.cameras[index];
  76893. if (camera._waitingParentId) {
  76894. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  76895. camera._waitingParentId = null;
  76896. }
  76897. }
  76898. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  76899. var light_1 = scene.lights[index];
  76900. if (light_1 && light_1._waitingParentId) {
  76901. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  76902. light_1._waitingParentId = null;
  76903. }
  76904. }
  76905. // Connect parents & children and parse actions
  76906. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  76907. var transformNode = scene.transformNodes[index];
  76908. if (transformNode._waitingParentId) {
  76909. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  76910. transformNode._waitingParentId = null;
  76911. }
  76912. }
  76913. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  76914. var mesh = scene.meshes[index];
  76915. if (mesh._waitingParentId) {
  76916. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  76917. mesh._waitingParentId = null;
  76918. }
  76919. }
  76920. // freeze world matrix application
  76921. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  76922. var currentMesh = scene.meshes[index];
  76923. if (currentMesh._waitingFreezeWorldMatrix) {
  76924. currentMesh.freezeWorldMatrix();
  76925. currentMesh._waitingFreezeWorldMatrix = null;
  76926. }
  76927. else {
  76928. currentMesh.computeWorldMatrix(true);
  76929. }
  76930. }
  76931. // Lights exclusions / inclusions
  76932. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  76933. var light_2 = scene.lights[index];
  76934. // Excluded check
  76935. if (light_2._excludedMeshesIds.length > 0) {
  76936. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  76937. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  76938. if (excludedMesh) {
  76939. light_2.excludedMeshes.push(excludedMesh);
  76940. }
  76941. }
  76942. light_2._excludedMeshesIds = [];
  76943. }
  76944. // Included check
  76945. if (light_2._includedOnlyMeshesIds.length > 0) {
  76946. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  76947. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  76948. if (includedOnlyMesh) {
  76949. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  76950. }
  76951. }
  76952. light_2._includedOnlyMeshesIds = [];
  76953. }
  76954. }
  76955. BABYLON.AbstractScene.Parse(parsedData, scene, container, rootUrl);
  76956. // Actions (scene) Done last as it can access other objects.
  76957. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  76958. var mesh = scene.meshes[index];
  76959. if (mesh._waitingActions) {
  76960. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  76961. mesh._waitingActions = null;
  76962. }
  76963. }
  76964. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  76965. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  76966. }
  76967. if (!addToScene) {
  76968. container.removeAllFromScene();
  76969. }
  76970. }
  76971. catch (err) {
  76972. var msg = logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + log;
  76973. if (onError) {
  76974. onError(msg, err);
  76975. }
  76976. else {
  76977. BABYLON.Tools.Log(msg);
  76978. throw err;
  76979. }
  76980. }
  76981. finally {
  76982. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  76983. BABYLON.Tools.Log(logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  76984. }
  76985. }
  76986. return container;
  76987. };
  76988. BABYLON.SceneLoader.RegisterPlugin({
  76989. name: "babylon.js",
  76990. extensions: ".babylon",
  76991. canDirectLoad: function (data) {
  76992. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  76993. return true;
  76994. }
  76995. return false;
  76996. },
  76997. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  76998. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  76999. // when SceneLoader.debugLogging = true (default), or exception encountered.
  77000. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  77001. // and avoid problems with multiple concurrent .babylon loads.
  77002. var log = "importMesh has failed JSON parse";
  77003. try {
  77004. var parsedData = JSON.parse(data);
  77005. log = "";
  77006. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  77007. if (!meshesNames) {
  77008. meshesNames = null;
  77009. }
  77010. else if (!Array.isArray(meshesNames)) {
  77011. meshesNames = [meshesNames];
  77012. }
  77013. var hierarchyIds = new Array();
  77014. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  77015. var loadedSkeletonsIds = [];
  77016. var loadedMaterialsIds = [];
  77017. var index;
  77018. var cache;
  77019. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  77020. var parsedMesh = parsedData.meshes[index];
  77021. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  77022. if (meshesNames !== null) {
  77023. // Remove found mesh name from list.
  77024. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  77025. }
  77026. //Geometry?
  77027. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  77028. //does the file contain geometries?
  77029. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  77030. //find the correct geometry and add it to the scene
  77031. var found = false;
  77032. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  77033. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  77034. return;
  77035. }
  77036. else {
  77037. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  77038. if (parsedGeometryData.id === parsedMesh.geometryId) {
  77039. switch (geometryType) {
  77040. case "boxes":
  77041. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  77042. break;
  77043. case "spheres":
  77044. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  77045. break;
  77046. case "cylinders":
  77047. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  77048. break;
  77049. case "toruses":
  77050. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  77051. break;
  77052. case "grounds":
  77053. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  77054. break;
  77055. case "planes":
  77056. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  77057. break;
  77058. case "torusKnots":
  77059. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  77060. break;
  77061. case "vertexData":
  77062. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  77063. break;
  77064. }
  77065. found = true;
  77066. }
  77067. });
  77068. }
  77069. });
  77070. if (found === false) {
  77071. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  77072. }
  77073. }
  77074. }
  77075. // Material ?
  77076. if (parsedMesh.materialId) {
  77077. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  77078. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  77079. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  77080. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  77081. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  77082. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  77083. var subMatId = parsedMultiMaterial.materials[matIndex];
  77084. loadedMaterialsIds.push(subMatId);
  77085. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  77086. if (mat) {
  77087. log += "\n\tMaterial " + mat.toString(fullDetails);
  77088. }
  77089. }
  77090. loadedMaterialsIds.push(parsedMultiMaterial.id);
  77091. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  77092. if (mmat) {
  77093. materialFound = true;
  77094. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  77095. }
  77096. break;
  77097. }
  77098. }
  77099. }
  77100. if (materialFound === false) {
  77101. loadedMaterialsIds.push(parsedMesh.materialId);
  77102. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  77103. if (!mat) {
  77104. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  77105. }
  77106. else {
  77107. log += "\n\tMaterial " + mat.toString(fullDetails);
  77108. }
  77109. }
  77110. }
  77111. // Skeleton ?
  77112. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  77113. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  77114. if (skeletonAlreadyLoaded === false) {
  77115. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  77116. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  77117. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  77118. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  77119. skeletons.push(skeleton);
  77120. loadedSkeletonsIds.push(parsedSkeleton.id);
  77121. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  77122. }
  77123. }
  77124. }
  77125. }
  77126. // Morph targets ?
  77127. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  77128. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  77129. var managerData = _a[_i];
  77130. BABYLON.MorphTargetManager.Parse(managerData, scene);
  77131. }
  77132. }
  77133. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  77134. meshes.push(mesh);
  77135. log += "\n\tMesh " + mesh.toString(fullDetails);
  77136. }
  77137. }
  77138. // Connecting parents
  77139. var currentMesh;
  77140. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  77141. currentMesh = scene.meshes[index];
  77142. if (currentMesh._waitingParentId) {
  77143. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  77144. currentMesh._waitingParentId = null;
  77145. }
  77146. }
  77147. // freeze and compute world matrix application
  77148. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  77149. currentMesh = scene.meshes[index];
  77150. if (currentMesh._waitingFreezeWorldMatrix) {
  77151. currentMesh.freezeWorldMatrix();
  77152. currentMesh._waitingFreezeWorldMatrix = null;
  77153. }
  77154. else {
  77155. currentMesh.computeWorldMatrix(true);
  77156. }
  77157. }
  77158. }
  77159. // Particles
  77160. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  77161. var parser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  77162. if (parser) {
  77163. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  77164. var parsedParticleSystem = parsedData.particleSystems[index];
  77165. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  77166. particleSystems.push(parser(parsedParticleSystem, scene, rootUrl));
  77167. }
  77168. }
  77169. }
  77170. }
  77171. return true;
  77172. }
  77173. catch (err) {
  77174. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  77175. if (onError) {
  77176. onError(msg, err);
  77177. }
  77178. else {
  77179. BABYLON.Tools.Log(msg);
  77180. throw err;
  77181. }
  77182. }
  77183. finally {
  77184. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  77185. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  77186. }
  77187. }
  77188. return false;
  77189. },
  77190. load: function (scene, data, rootUrl, onError) {
  77191. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  77192. // when SceneLoader.debugLogging = true (default), or exception encountered.
  77193. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  77194. // and avoid problems with multiple concurrent .babylon loads.
  77195. var log = "importScene has failed JSON parse";
  77196. try {
  77197. var parsedData = JSON.parse(data);
  77198. log = "";
  77199. // Scene
  77200. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  77201. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  77202. }
  77203. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  77204. scene.autoClear = parsedData.autoClear;
  77205. }
  77206. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  77207. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  77208. }
  77209. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  77210. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  77211. }
  77212. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  77213. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  77214. }
  77215. // Fog
  77216. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  77217. scene.fogMode = parsedData.fogMode;
  77218. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  77219. scene.fogStart = parsedData.fogStart;
  77220. scene.fogEnd = parsedData.fogEnd;
  77221. scene.fogDensity = parsedData.fogDensity;
  77222. log += "\tFog mode for scene: ";
  77223. switch (scene.fogMode) {
  77224. // getters not compiling, so using hardcoded
  77225. case 1:
  77226. log += "exp\n";
  77227. break;
  77228. case 2:
  77229. log += "exp2\n";
  77230. break;
  77231. case 3:
  77232. log += "linear\n";
  77233. break;
  77234. }
  77235. }
  77236. //Physics
  77237. if (parsedData.physicsEnabled) {
  77238. var physicsPlugin;
  77239. if (parsedData.physicsEngine === "cannon") {
  77240. physicsPlugin = new BABYLON.CannonJSPlugin();
  77241. }
  77242. else if (parsedData.physicsEngine === "oimo") {
  77243. physicsPlugin = new BABYLON.OimoJSPlugin();
  77244. }
  77245. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  77246. //else - default engine, which is currently oimo
  77247. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  77248. scene.enablePhysics(physicsGravity, physicsPlugin);
  77249. }
  77250. // Metadata
  77251. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  77252. scene.metadata = parsedData.metadata;
  77253. }
  77254. //collisions, if defined. otherwise, default is true
  77255. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  77256. scene.collisionsEnabled = parsedData.collisionsEnabled;
  77257. }
  77258. scene.workerCollisions = !!parsedData.workerCollisions;
  77259. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  77260. if (!container) {
  77261. return false;
  77262. }
  77263. if (parsedData.autoAnimate) {
  77264. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  77265. }
  77266. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  77267. scene.setActiveCameraByID(parsedData.activeCameraID);
  77268. }
  77269. // Environment texture
  77270. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  77271. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  77272. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  77273. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  77274. if (parsedData.environmentTextureRotationY) {
  77275. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  77276. }
  77277. scene.environmentTexture = hdrTexture;
  77278. }
  77279. else {
  77280. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  77281. if (parsedData.environmentTextureRotationY) {
  77282. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  77283. }
  77284. scene.environmentTexture = cubeTexture;
  77285. }
  77286. if (parsedData.createDefaultSkybox === true) {
  77287. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  77288. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  77289. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  77290. }
  77291. }
  77292. // Finish
  77293. return true;
  77294. }
  77295. catch (err) {
  77296. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  77297. if (onError) {
  77298. onError(msg, err);
  77299. }
  77300. else {
  77301. BABYLON.Tools.Log(msg);
  77302. throw err;
  77303. }
  77304. }
  77305. finally {
  77306. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  77307. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  77308. }
  77309. }
  77310. return false;
  77311. },
  77312. loadAssetContainer: function (scene, data, rootUrl, onError) {
  77313. var container = loadAssetContainer(scene, data, rootUrl, onError);
  77314. return container;
  77315. }
  77316. });
  77317. })(BABYLON || (BABYLON = {}));
  77318. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  77319. var BABYLON;
  77320. (function (BABYLON) {
  77321. /**
  77322. * Class used to help managing file picking and drag'n'drop
  77323. */
  77324. var FilesInput = /** @class */ (function () {
  77325. /**
  77326. * Creates a new FilesInput
  77327. * @param engine defines the rendering engine
  77328. * @param scene defines the hosting scene
  77329. * @param sceneLoadedCallback callback called when scene is loaded
  77330. * @param progressCallback callback called to track progress
  77331. * @param additionalRenderLoopLogicCallback callback called to add user logic to the rendering loop
  77332. * @param textureLoadingCallback callback called when a texture is loading
  77333. * @param startingProcessingFilesCallback callback called when the system is about to process all files
  77334. * @param onReloadCallback callback called when a reload is requested
  77335. * @param errorCallback callback call if an error occurs
  77336. */
  77337. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  77338. /**
  77339. * Callback called when a file is processed
  77340. */
  77341. this.onProcessFileCallback = function () { return true; };
  77342. this._engine = engine;
  77343. this._currentScene = scene;
  77344. this._sceneLoadedCallback = sceneLoadedCallback;
  77345. this._progressCallback = progressCallback;
  77346. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  77347. this._textureLoadingCallback = textureLoadingCallback;
  77348. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  77349. this._onReloadCallback = onReloadCallback;
  77350. this._errorCallback = errorCallback;
  77351. }
  77352. /**
  77353. * Calls this function to listen to drag'n'drop events on a specific DOM element
  77354. * @param elementToMonitor defines the DOM element to track
  77355. */
  77356. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  77357. var _this = this;
  77358. if (elementToMonitor) {
  77359. this._elementToMonitor = elementToMonitor;
  77360. this._dragEnterHandler = function (e) { _this.drag(e); };
  77361. this._dragOverHandler = function (e) { _this.drag(e); };
  77362. this._dropHandler = function (e) { _this.drop(e); };
  77363. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  77364. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  77365. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  77366. }
  77367. };
  77368. /**
  77369. * Release all associated resources
  77370. */
  77371. FilesInput.prototype.dispose = function () {
  77372. if (!this._elementToMonitor) {
  77373. return;
  77374. }
  77375. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  77376. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  77377. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  77378. };
  77379. FilesInput.prototype.renderFunction = function () {
  77380. if (this._additionalRenderLoopLogicCallback) {
  77381. this._additionalRenderLoopLogicCallback();
  77382. }
  77383. if (this._currentScene) {
  77384. if (this._textureLoadingCallback) {
  77385. var remaining = this._currentScene.getWaitingItemsCount();
  77386. if (remaining > 0) {
  77387. this._textureLoadingCallback(remaining);
  77388. }
  77389. }
  77390. this._currentScene.render();
  77391. }
  77392. };
  77393. FilesInput.prototype.drag = function (e) {
  77394. e.stopPropagation();
  77395. e.preventDefault();
  77396. };
  77397. FilesInput.prototype.drop = function (eventDrop) {
  77398. eventDrop.stopPropagation();
  77399. eventDrop.preventDefault();
  77400. this.loadFiles(eventDrop);
  77401. };
  77402. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  77403. var _this = this;
  77404. var reader = folder.createReader();
  77405. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  77406. reader.readEntries(function (entries) {
  77407. remaining.count += entries.length;
  77408. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  77409. var entry = entries_1[_i];
  77410. if (entry.isFile) {
  77411. entry.file(function (file) {
  77412. file.correctName = relativePath + file.name;
  77413. files.push(file);
  77414. if (--remaining.count === 0) {
  77415. callback();
  77416. }
  77417. });
  77418. }
  77419. else if (entry.isDirectory) {
  77420. _this._traverseFolder(entry, files, remaining, callback);
  77421. }
  77422. }
  77423. if (--remaining.count) {
  77424. callback();
  77425. }
  77426. });
  77427. };
  77428. FilesInput.prototype._processFiles = function (files) {
  77429. for (var i = 0; i < files.length; i++) {
  77430. var name = files[i].correctName.toLowerCase();
  77431. var extension = name.split('.').pop();
  77432. if (!this.onProcessFileCallback(files[i], name, extension)) {
  77433. continue;
  77434. }
  77435. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  77436. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  77437. this._sceneFileToLoad = files[i];
  77438. }
  77439. FilesInput.FilesToLoad[name] = files[i];
  77440. }
  77441. };
  77442. /**
  77443. * Load files from a drop event
  77444. * @param event defines the drop event to use as source
  77445. */
  77446. FilesInput.prototype.loadFiles = function (event) {
  77447. var _this = this;
  77448. // Handling data transfer via drag'n'drop
  77449. if (event && event.dataTransfer && event.dataTransfer.files) {
  77450. this._filesToLoad = event.dataTransfer.files;
  77451. }
  77452. // Handling files from input files
  77453. if (event && event.target && event.target.files) {
  77454. this._filesToLoad = event.target.files;
  77455. }
  77456. if (!this._filesToLoad || this._filesToLoad.length === 0) {
  77457. return;
  77458. }
  77459. if (this._startingProcessingFilesCallback) {
  77460. this._startingProcessingFilesCallback(this._filesToLoad);
  77461. }
  77462. if (this._filesToLoad && this._filesToLoad.length > 0) {
  77463. var files_1 = new Array();
  77464. var folders = [];
  77465. var items = event.dataTransfer ? event.dataTransfer.items : null;
  77466. for (var i = 0; i < this._filesToLoad.length; i++) {
  77467. var fileToLoad = this._filesToLoad[i];
  77468. var name_1 = fileToLoad.name.toLowerCase();
  77469. var entry = void 0;
  77470. fileToLoad.correctName = name_1;
  77471. if (items) {
  77472. var item = items[i];
  77473. if (item.getAsEntry) {
  77474. entry = item.getAsEntry();
  77475. }
  77476. else if (item.webkitGetAsEntry) {
  77477. entry = item.webkitGetAsEntry();
  77478. }
  77479. }
  77480. if (!entry) {
  77481. files_1.push(fileToLoad);
  77482. }
  77483. else {
  77484. if (entry.isDirectory) {
  77485. folders.push(entry);
  77486. }
  77487. else {
  77488. files_1.push(fileToLoad);
  77489. }
  77490. }
  77491. }
  77492. if (folders.length === 0) {
  77493. this._processFiles(files_1);
  77494. this._processReload();
  77495. }
  77496. else {
  77497. var remaining = { count: folders.length };
  77498. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  77499. var folder = folders_1[_i];
  77500. this._traverseFolder(folder, files_1, remaining, function () {
  77501. _this._processFiles(files_1);
  77502. if (remaining.count === 0) {
  77503. _this._processReload();
  77504. }
  77505. });
  77506. }
  77507. }
  77508. }
  77509. };
  77510. FilesInput.prototype._processReload = function () {
  77511. if (this._onReloadCallback) {
  77512. this._onReloadCallback(this._sceneFileToLoad);
  77513. }
  77514. else {
  77515. this.reload();
  77516. }
  77517. };
  77518. /**
  77519. * Reload the current scene from the loaded files
  77520. */
  77521. FilesInput.prototype.reload = function () {
  77522. var _this = this;
  77523. // If a scene file has been provided
  77524. if (this._sceneFileToLoad) {
  77525. if (this._currentScene) {
  77526. if (BABYLON.Tools.errorsCount > 0) {
  77527. BABYLON.Tools.ClearLogCache();
  77528. }
  77529. this._engine.stopRenderLoop();
  77530. }
  77531. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad.name, this._engine, function (progress) {
  77532. if (_this._progressCallback) {
  77533. _this._progressCallback(progress);
  77534. }
  77535. }).then(function (scene) {
  77536. if (_this._currentScene) {
  77537. _this._currentScene.dispose();
  77538. }
  77539. _this._currentScene = scene;
  77540. if (_this._sceneLoadedCallback) {
  77541. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  77542. }
  77543. // Wait for textures and shaders to be ready
  77544. _this._currentScene.executeWhenReady(function () {
  77545. _this._engine.runRenderLoop(function () {
  77546. _this.renderFunction();
  77547. });
  77548. });
  77549. }).catch(function (error) {
  77550. if (_this._errorCallback) {
  77551. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  77552. }
  77553. });
  77554. }
  77555. else {
  77556. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  77557. }
  77558. };
  77559. /**
  77560. * List of files ready to be loaded
  77561. */
  77562. FilesInput.FilesToLoad = {};
  77563. return FilesInput;
  77564. }());
  77565. BABYLON.FilesInput = FilesInput;
  77566. })(BABYLON || (BABYLON = {}));
  77567. //# sourceMappingURL=babylon.filesInput.js.map
  77568. var BABYLON;
  77569. (function (BABYLON) {
  77570. /**
  77571. * Class used to store custom tags
  77572. */
  77573. var Tags = /** @class */ (function () {
  77574. function Tags() {
  77575. }
  77576. /**
  77577. * Adds support for tags on the given object
  77578. * @param obj defines the object to use
  77579. */
  77580. Tags.EnableFor = function (obj) {
  77581. obj._tags = obj._tags || {};
  77582. obj.hasTags = function () {
  77583. return Tags.HasTags(obj);
  77584. };
  77585. obj.addTags = function (tagsString) {
  77586. return Tags.AddTagsTo(obj, tagsString);
  77587. };
  77588. obj.removeTags = function (tagsString) {
  77589. return Tags.RemoveTagsFrom(obj, tagsString);
  77590. };
  77591. obj.matchesTagsQuery = function (tagsQuery) {
  77592. return Tags.MatchesQuery(obj, tagsQuery);
  77593. };
  77594. };
  77595. /**
  77596. * Removes tags support
  77597. * @param obj defines the object to use
  77598. */
  77599. Tags.DisableFor = function (obj) {
  77600. delete obj._tags;
  77601. delete obj.hasTags;
  77602. delete obj.addTags;
  77603. delete obj.removeTags;
  77604. delete obj.matchesTagsQuery;
  77605. };
  77606. /**
  77607. * Gets a boolean indicating if the given object has tags
  77608. * @param obj defines the object to use
  77609. * @returns a boolean
  77610. */
  77611. Tags.HasTags = function (obj) {
  77612. if (!obj._tags) {
  77613. return false;
  77614. }
  77615. return !BABYLON.Tools.IsEmpty(obj._tags);
  77616. };
  77617. /**
  77618. * Gets the tags available on a given object
  77619. * @param obj defines the object to use
  77620. * @param asString defines if the tags must be returned as a string instead of an array of strings
  77621. * @returns the tags
  77622. */
  77623. Tags.GetTags = function (obj, asString) {
  77624. if (asString === void 0) { asString = true; }
  77625. if (!obj._tags) {
  77626. return null;
  77627. }
  77628. if (asString) {
  77629. var tagsArray = [];
  77630. for (var tag in obj._tags) {
  77631. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  77632. tagsArray.push(tag);
  77633. }
  77634. }
  77635. return tagsArray.join(" ");
  77636. }
  77637. else {
  77638. return obj._tags;
  77639. }
  77640. };
  77641. /**
  77642. * Adds tags to an object
  77643. * @param obj defines the object to use
  77644. * @param tagsString defines the tag string. The tags 'true' and 'false' are reserved and cannot be used as tags.
  77645. * A tag cannot start with '||', '&&', and '!'. It cannot contain whitespaces
  77646. */
  77647. Tags.AddTagsTo = function (obj, tagsString) {
  77648. if (!tagsString) {
  77649. return;
  77650. }
  77651. if (typeof tagsString !== "string") {
  77652. return;
  77653. }
  77654. var tags = tagsString.split(" ");
  77655. tags.forEach(function (tag, index, array) {
  77656. Tags._AddTagTo(obj, tag);
  77657. });
  77658. };
  77659. /**
  77660. * @hidden
  77661. */
  77662. Tags._AddTagTo = function (obj, tag) {
  77663. tag = tag.trim();
  77664. if (tag === "" || tag === "true" || tag === "false") {
  77665. return;
  77666. }
  77667. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  77668. return;
  77669. }
  77670. Tags.EnableFor(obj);
  77671. obj._tags[tag] = true;
  77672. };
  77673. /**
  77674. * Removes specific tags from a specific object
  77675. * @param obj defines the object to use
  77676. * @param tagsString defines the tags to remove
  77677. */
  77678. Tags.RemoveTagsFrom = function (obj, tagsString) {
  77679. if (!Tags.HasTags(obj)) {
  77680. return;
  77681. }
  77682. var tags = tagsString.split(" ");
  77683. for (var t in tags) {
  77684. Tags._RemoveTagFrom(obj, tags[t]);
  77685. }
  77686. };
  77687. /**
  77688. * @hidden
  77689. */
  77690. Tags._RemoveTagFrom = function (obj, tag) {
  77691. delete obj._tags[tag];
  77692. };
  77693. /**
  77694. * Defines if tags hosted on an object match a given query
  77695. * @param obj defines the object to use
  77696. * @param tagsQuery defines the tag query
  77697. * @returns a boolean
  77698. */
  77699. Tags.MatchesQuery = function (obj, tagsQuery) {
  77700. if (tagsQuery === undefined) {
  77701. return true;
  77702. }
  77703. if (tagsQuery === "") {
  77704. return Tags.HasTags(obj);
  77705. }
  77706. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  77707. };
  77708. return Tags;
  77709. }());
  77710. BABYLON.Tags = Tags;
  77711. })(BABYLON || (BABYLON = {}));
  77712. //# sourceMappingURL=babylon.tags.js.map
  77713. var BABYLON;
  77714. (function (BABYLON) {
  77715. /**
  77716. * Class used to evalaute queries containing `and` and `or` operators
  77717. */
  77718. var AndOrNotEvaluator = /** @class */ (function () {
  77719. function AndOrNotEvaluator() {
  77720. }
  77721. /**
  77722. * Evaluate a query
  77723. * @param query defines the query to evaluate
  77724. * @param evaluateCallback defines the callback used to filter result
  77725. * @returns true if the query matches
  77726. */
  77727. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  77728. if (!query.match(/\([^\(\)]*\)/g)) {
  77729. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  77730. }
  77731. else {
  77732. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  77733. // remove parenthesis
  77734. r = r.slice(1, r.length - 1);
  77735. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  77736. });
  77737. }
  77738. if (query === "true") {
  77739. return true;
  77740. }
  77741. if (query === "false") {
  77742. return false;
  77743. }
  77744. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  77745. };
  77746. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  77747. evaluateCallback = evaluateCallback || (function (r) {
  77748. return r === "true" ? true : false;
  77749. });
  77750. var result;
  77751. var or = parenthesisContent.split("||");
  77752. for (var i in or) {
  77753. if (or.hasOwnProperty(i)) {
  77754. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  77755. var and = ori.split("&&");
  77756. if (and.length > 1) {
  77757. for (var j = 0; j < and.length; ++j) {
  77758. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  77759. if (andj !== "true" && andj !== "false") {
  77760. if (andj[0] === "!") {
  77761. result = !evaluateCallback(andj.substring(1));
  77762. }
  77763. else {
  77764. result = evaluateCallback(andj);
  77765. }
  77766. }
  77767. else {
  77768. result = andj === "true" ? true : false;
  77769. }
  77770. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  77771. ori = "false";
  77772. break;
  77773. }
  77774. }
  77775. }
  77776. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  77777. result = true;
  77778. break;
  77779. }
  77780. // result equals false (or undefined)
  77781. if (ori !== "true" && ori !== "false") {
  77782. if (ori[0] === "!") {
  77783. result = !evaluateCallback(ori.substring(1));
  77784. }
  77785. else {
  77786. result = evaluateCallback(ori);
  77787. }
  77788. }
  77789. else {
  77790. result = ori === "true" ? true : false;
  77791. }
  77792. }
  77793. }
  77794. // the whole parenthesis scope is replaced by 'true' or 'false'
  77795. return result ? "true" : "false";
  77796. };
  77797. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  77798. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  77799. // remove whitespaces
  77800. r = r.replace(/[\s]/g, function () { return ""; });
  77801. return r.length % 2 ? "!" : "";
  77802. });
  77803. booleanString = booleanString.trim();
  77804. if (booleanString === "!true") {
  77805. booleanString = "false";
  77806. }
  77807. else if (booleanString === "!false") {
  77808. booleanString = "true";
  77809. }
  77810. return booleanString;
  77811. };
  77812. return AndOrNotEvaluator;
  77813. }());
  77814. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  77815. })(BABYLON || (BABYLON = {}));
  77816. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  77817. var BABYLON;
  77818. (function (BABYLON) {
  77819. /**
  77820. * Class used to enable access to IndexedDB
  77821. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  77822. */
  77823. var Database = /** @class */ (function () {
  77824. /**
  77825. * Creates a new Database
  77826. * @param urlToScene defines the url to load the scene
  77827. * @param callbackManifestChecked defines the callback to use when manifest is checked
  77828. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  77829. */
  77830. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  77831. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  77832. var _this = this;
  77833. // Handling various flavors of prefixed version of IndexedDB
  77834. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  77835. this.callbackManifestChecked = callbackManifestChecked;
  77836. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  77837. this.db = null;
  77838. this._enableSceneOffline = false;
  77839. this._enableTexturesOffline = false;
  77840. this.manifestVersionFound = 0;
  77841. this.mustUpdateRessources = false;
  77842. this.hasReachedQuota = false;
  77843. if (!Database.IDBStorageEnabled) {
  77844. this.callbackManifestChecked(true);
  77845. }
  77846. else {
  77847. if (disableManifestCheck) {
  77848. this._enableSceneOffline = true;
  77849. this._enableTexturesOffline = true;
  77850. this.manifestVersionFound = 1;
  77851. BABYLON.Tools.SetImmediate(function () {
  77852. _this.callbackManifestChecked(true);
  77853. });
  77854. }
  77855. else {
  77856. this._checkManifestFile();
  77857. }
  77858. }
  77859. }
  77860. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  77861. /**
  77862. * Gets a boolean indicating if scene must be saved in the database
  77863. */
  77864. get: function () {
  77865. return this._enableSceneOffline;
  77866. },
  77867. enumerable: true,
  77868. configurable: true
  77869. });
  77870. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  77871. /**
  77872. * Gets a boolean indicating if textures must be saved in the database
  77873. */
  77874. get: function () {
  77875. return this._enableTexturesOffline;
  77876. },
  77877. enumerable: true,
  77878. configurable: true
  77879. });
  77880. Database.prototype._checkManifestFile = function () {
  77881. var _this = this;
  77882. var noManifestFile = function () {
  77883. _this._enableSceneOffline = false;
  77884. _this._enableTexturesOffline = false;
  77885. _this.callbackManifestChecked(false);
  77886. };
  77887. var timeStampUsed = false;
  77888. var manifestURL = this.currentSceneUrl + ".manifest";
  77889. var xhr = new XMLHttpRequest();
  77890. if (navigator.onLine) {
  77891. // Adding a timestamp to by-pass browsers' cache
  77892. timeStampUsed = true;
  77893. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  77894. }
  77895. xhr.open("GET", manifestURL, true);
  77896. xhr.addEventListener("load", function () {
  77897. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  77898. try {
  77899. var manifestFile = JSON.parse(xhr.response);
  77900. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  77901. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  77902. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  77903. _this.manifestVersionFound = manifestFile.version;
  77904. }
  77905. if (_this.callbackManifestChecked) {
  77906. _this.callbackManifestChecked(true);
  77907. }
  77908. }
  77909. catch (ex) {
  77910. noManifestFile();
  77911. }
  77912. }
  77913. else {
  77914. noManifestFile();
  77915. }
  77916. }, false);
  77917. xhr.addEventListener("error", function (event) {
  77918. if (timeStampUsed) {
  77919. timeStampUsed = false;
  77920. // Let's retry without the timeStamp
  77921. // It could fail when coupled with HTML5 Offline API
  77922. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  77923. xhr.open("GET", retryManifestURL, true);
  77924. xhr.send();
  77925. }
  77926. else {
  77927. noManifestFile();
  77928. }
  77929. }, false);
  77930. try {
  77931. xhr.send();
  77932. }
  77933. catch (ex) {
  77934. BABYLON.Tools.Error("Error on XHR send request.");
  77935. this.callbackManifestChecked(false);
  77936. }
  77937. };
  77938. /**
  77939. * Open the database and make it available
  77940. * @param successCallback defines the callback to call on success
  77941. * @param errorCallback defines the callback to call on error
  77942. */
  77943. Database.prototype.openAsync = function (successCallback, errorCallback) {
  77944. var _this = this;
  77945. var handleError = function () {
  77946. _this.isSupported = false;
  77947. if (errorCallback)
  77948. errorCallback();
  77949. };
  77950. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  77951. // Your browser doesn't support IndexedDB
  77952. this.isSupported = false;
  77953. if (errorCallback)
  77954. errorCallback();
  77955. }
  77956. else {
  77957. // If the DB hasn't been opened or created yet
  77958. if (!this.db) {
  77959. this.hasReachedQuota = false;
  77960. this.isSupported = true;
  77961. var request = this.idbFactory.open("babylonjs", 1);
  77962. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  77963. request.onerror = function (event) {
  77964. handleError();
  77965. };
  77966. // executes when a version change transaction cannot complete due to other active transactions
  77967. request.onblocked = function (event) {
  77968. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  77969. handleError();
  77970. };
  77971. // DB has been opened successfully
  77972. request.onsuccess = function (event) {
  77973. _this.db = request.result;
  77974. successCallback();
  77975. };
  77976. // Initialization of the DB. Creating Scenes & Textures stores
  77977. request.onupgradeneeded = function (event) {
  77978. _this.db = (event.target).result;
  77979. if (_this.db) {
  77980. try {
  77981. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  77982. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  77983. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  77984. }
  77985. catch (ex) {
  77986. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  77987. handleError();
  77988. }
  77989. }
  77990. };
  77991. }
  77992. // DB has already been created and opened
  77993. else {
  77994. if (successCallback)
  77995. successCallback();
  77996. }
  77997. }
  77998. };
  77999. /**
  78000. * Loads an image from the database
  78001. * @param url defines the url to load from
  78002. * @param image defines the target DOM image
  78003. */
  78004. Database.prototype.loadImageFromDB = function (url, image) {
  78005. var _this = this;
  78006. var completeURL = Database._ReturnFullUrlLocation(url);
  78007. var saveAndLoadImage = function () {
  78008. if (!_this.hasReachedQuota && _this.db !== null) {
  78009. // the texture is not yet in the DB, let's try to save it
  78010. _this._saveImageIntoDBAsync(completeURL, image);
  78011. }
  78012. // If the texture is not in the DB and we've reached the DB quota limit
  78013. // let's load it directly from the web
  78014. else {
  78015. image.src = url;
  78016. }
  78017. };
  78018. if (!this.mustUpdateRessources) {
  78019. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  78020. }
  78021. // First time we're download the images or update requested in the manifest file by a version change
  78022. else {
  78023. saveAndLoadImage();
  78024. }
  78025. };
  78026. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  78027. if (this.isSupported && this.db !== null) {
  78028. var texture;
  78029. var transaction = this.db.transaction(["textures"]);
  78030. transaction.onabort = function (event) {
  78031. image.src = url;
  78032. };
  78033. transaction.oncomplete = function (event) {
  78034. var blobTextureURL;
  78035. if (texture) {
  78036. var URL = window.URL || window.webkitURL;
  78037. blobTextureURL = URL.createObjectURL(texture.data);
  78038. image.onerror = function () {
  78039. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  78040. image.src = url;
  78041. };
  78042. image.src = blobTextureURL;
  78043. }
  78044. else {
  78045. notInDBCallback();
  78046. }
  78047. };
  78048. var getRequest = transaction.objectStore("textures").get(url);
  78049. getRequest.onsuccess = function (event) {
  78050. texture = (event.target).result;
  78051. };
  78052. getRequest.onerror = function (event) {
  78053. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  78054. image.src = url;
  78055. };
  78056. }
  78057. else {
  78058. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  78059. image.src = url;
  78060. }
  78061. };
  78062. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  78063. var _this = this;
  78064. if (this.isSupported) {
  78065. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  78066. var generateBlobUrl = function () {
  78067. var blobTextureURL;
  78068. if (blob) {
  78069. var URL = window.URL || window.webkitURL;
  78070. try {
  78071. blobTextureURL = URL.createObjectURL(blob);
  78072. }
  78073. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  78074. catch (ex) {
  78075. blobTextureURL = URL.createObjectURL(blob);
  78076. }
  78077. }
  78078. if (blobTextureURL) {
  78079. image.src = blobTextureURL;
  78080. }
  78081. };
  78082. if (Database.IsUASupportingBlobStorage) { // Create XHR
  78083. var xhr = new XMLHttpRequest(), blob;
  78084. xhr.open("GET", url, true);
  78085. xhr.responseType = "blob";
  78086. xhr.addEventListener("load", function () {
  78087. if (xhr.status === 200 && _this.db) {
  78088. // Blob as response (XHR2)
  78089. blob = xhr.response;
  78090. var transaction = _this.db.transaction(["textures"], "readwrite");
  78091. // the transaction could abort because of a QuotaExceededError error
  78092. transaction.onabort = function (event) {
  78093. try {
  78094. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  78095. var srcElement = (event.srcElement || event.target);
  78096. var error = srcElement.error;
  78097. if (error && error.name === "QuotaExceededError") {
  78098. _this.hasReachedQuota = true;
  78099. }
  78100. }
  78101. catch (ex) { }
  78102. generateBlobUrl();
  78103. };
  78104. transaction.oncomplete = function (event) {
  78105. generateBlobUrl();
  78106. };
  78107. var newTexture = { textureUrl: url, data: blob };
  78108. try {
  78109. // Put the blob into the dabase
  78110. var addRequest = transaction.objectStore("textures").put(newTexture);
  78111. addRequest.onsuccess = function (event) {
  78112. };
  78113. addRequest.onerror = function (event) {
  78114. generateBlobUrl();
  78115. };
  78116. }
  78117. catch (ex) {
  78118. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  78119. if (ex.code === 25) {
  78120. Database.IsUASupportingBlobStorage = false;
  78121. }
  78122. image.src = url;
  78123. }
  78124. }
  78125. else {
  78126. image.src = url;
  78127. }
  78128. }, false);
  78129. xhr.addEventListener("error", function (event) {
  78130. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  78131. image.src = url;
  78132. }, false);
  78133. xhr.send();
  78134. }
  78135. else {
  78136. image.src = url;
  78137. }
  78138. }
  78139. else {
  78140. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  78141. image.src = url;
  78142. }
  78143. };
  78144. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  78145. var _this = this;
  78146. var updateVersion = function () {
  78147. // the version is not yet in the DB or we need to update it
  78148. _this._saveVersionIntoDBAsync(url, versionLoaded);
  78149. };
  78150. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  78151. };
  78152. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  78153. var _this = this;
  78154. if (this.isSupported && this.db) {
  78155. var version;
  78156. try {
  78157. var transaction = this.db.transaction(["versions"]);
  78158. transaction.oncomplete = function (event) {
  78159. if (version) {
  78160. // If the version in the JSON file is different from the version in DB
  78161. if (_this.manifestVersionFound !== version.data) {
  78162. _this.mustUpdateRessources = true;
  78163. updateInDBCallback();
  78164. }
  78165. else {
  78166. callback(version.data);
  78167. }
  78168. }
  78169. // version was not found in DB
  78170. else {
  78171. _this.mustUpdateRessources = true;
  78172. updateInDBCallback();
  78173. }
  78174. };
  78175. transaction.onabort = function (event) {
  78176. callback(-1);
  78177. };
  78178. var getRequest = transaction.objectStore("versions").get(url);
  78179. getRequest.onsuccess = function (event) {
  78180. version = (event.target).result;
  78181. };
  78182. getRequest.onerror = function (event) {
  78183. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  78184. callback(-1);
  78185. };
  78186. }
  78187. catch (ex) {
  78188. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  78189. callback(-1);
  78190. }
  78191. }
  78192. else {
  78193. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  78194. callback(-1);
  78195. }
  78196. };
  78197. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  78198. var _this = this;
  78199. if (this.isSupported && !this.hasReachedQuota && this.db) {
  78200. try {
  78201. // Open a transaction to the database
  78202. var transaction = this.db.transaction(["versions"], "readwrite");
  78203. // the transaction could abort because of a QuotaExceededError error
  78204. transaction.onabort = function (event) {
  78205. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  78206. var error = event.srcElement['error'];
  78207. if (error && error.name === "QuotaExceededError") {
  78208. _this.hasReachedQuota = true;
  78209. }
  78210. }
  78211. catch (ex) { }
  78212. callback(-1);
  78213. };
  78214. transaction.oncomplete = function (event) {
  78215. callback(_this.manifestVersionFound);
  78216. };
  78217. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  78218. // Put the scene into the database
  78219. var addRequest = transaction.objectStore("versions").put(newVersion);
  78220. addRequest.onsuccess = function (event) {
  78221. };
  78222. addRequest.onerror = function (event) {
  78223. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  78224. };
  78225. }
  78226. catch (ex) {
  78227. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  78228. callback(-1);
  78229. }
  78230. }
  78231. else {
  78232. callback(-1);
  78233. }
  78234. };
  78235. /**
  78236. * Loads a file from database
  78237. * @param url defines the URL to load from
  78238. * @param sceneLoaded defines a callback to call on success
  78239. * @param progressCallBack defines a callback to call when progress changed
  78240. * @param errorCallback defines a callback to call on error
  78241. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  78242. */
  78243. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  78244. var _this = this;
  78245. var completeUrl = Database._ReturnFullUrlLocation(url);
  78246. var saveAndLoadFile = function () {
  78247. // the scene is not yet in the DB, let's try to save it
  78248. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  78249. };
  78250. this._checkVersionFromDB(completeUrl, function (version) {
  78251. if (version !== -1) {
  78252. if (!_this.mustUpdateRessources) {
  78253. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  78254. }
  78255. else {
  78256. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  78257. }
  78258. }
  78259. else {
  78260. if (errorCallback) {
  78261. errorCallback();
  78262. }
  78263. }
  78264. });
  78265. };
  78266. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  78267. if (this.isSupported && this.db) {
  78268. var targetStore;
  78269. if (url.indexOf(".babylon") !== -1) {
  78270. targetStore = "scenes";
  78271. }
  78272. else {
  78273. targetStore = "textures";
  78274. }
  78275. var file;
  78276. var transaction = this.db.transaction([targetStore]);
  78277. transaction.oncomplete = function (event) {
  78278. if (file) {
  78279. callback(file.data);
  78280. }
  78281. // file was not found in DB
  78282. else {
  78283. notInDBCallback();
  78284. }
  78285. };
  78286. transaction.onabort = function (event) {
  78287. notInDBCallback();
  78288. };
  78289. var getRequest = transaction.objectStore(targetStore).get(url);
  78290. getRequest.onsuccess = function (event) {
  78291. file = (event.target).result;
  78292. };
  78293. getRequest.onerror = function (event) {
  78294. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  78295. notInDBCallback();
  78296. };
  78297. }
  78298. else {
  78299. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  78300. callback();
  78301. }
  78302. };
  78303. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer, errorCallback) {
  78304. var _this = this;
  78305. if (this.isSupported) {
  78306. var targetStore;
  78307. if (url.indexOf(".babylon") !== -1) {
  78308. targetStore = "scenes";
  78309. }
  78310. else {
  78311. targetStore = "textures";
  78312. }
  78313. // Create XHR
  78314. var xhr = new XMLHttpRequest();
  78315. var fileData;
  78316. xhr.open("GET", url + "?" + Date.now(), true);
  78317. if (useArrayBuffer) {
  78318. xhr.responseType = "arraybuffer";
  78319. }
  78320. if (progressCallback) {
  78321. xhr.onprogress = progressCallback;
  78322. }
  78323. xhr.addEventListener("load", function () {
  78324. if (xhr.status === 200 || (xhr.status < 400 && BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6))) {
  78325. // Blob as response (XHR2)
  78326. //fileData = xhr.responseText;
  78327. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  78328. if (!_this.hasReachedQuota && _this.db) {
  78329. // Open a transaction to the database
  78330. var transaction = _this.db.transaction([targetStore], "readwrite");
  78331. // the transaction could abort because of a QuotaExceededError error
  78332. transaction.onabort = function (event) {
  78333. try {
  78334. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  78335. var error = event.srcElement['error'];
  78336. if (error && error.name === "QuotaExceededError") {
  78337. _this.hasReachedQuota = true;
  78338. }
  78339. }
  78340. catch (ex) { }
  78341. callback(fileData);
  78342. };
  78343. transaction.oncomplete = function (event) {
  78344. callback(fileData);
  78345. };
  78346. var newFile;
  78347. if (targetStore === "scenes") {
  78348. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  78349. }
  78350. else {
  78351. newFile = { textureUrl: url, data: fileData };
  78352. }
  78353. try {
  78354. // Put the scene into the database
  78355. var addRequest = transaction.objectStore(targetStore).put(newFile);
  78356. addRequest.onsuccess = function (event) {
  78357. };
  78358. addRequest.onerror = function (event) {
  78359. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  78360. };
  78361. }
  78362. catch (ex) {
  78363. callback(fileData);
  78364. }
  78365. }
  78366. else {
  78367. callback(fileData);
  78368. }
  78369. }
  78370. else {
  78371. if (xhr.status >= 400 && errorCallback) {
  78372. errorCallback(xhr);
  78373. }
  78374. else {
  78375. callback();
  78376. }
  78377. }
  78378. }, false);
  78379. xhr.addEventListener("error", function (event) {
  78380. BABYLON.Tools.Error("error on XHR request.");
  78381. callback();
  78382. }, false);
  78383. xhr.send();
  78384. }
  78385. else {
  78386. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  78387. callback();
  78388. }
  78389. };
  78390. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  78391. Database.IsUASupportingBlobStorage = true;
  78392. /** Gets a boolean indicating if Database storate is enabled */
  78393. Database.IDBStorageEnabled = true;
  78394. Database._ParseURL = function (url) {
  78395. var a = document.createElement('a');
  78396. a.href = url;
  78397. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  78398. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  78399. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  78400. return absLocation;
  78401. };
  78402. Database._ReturnFullUrlLocation = function (url) {
  78403. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  78404. return (Database._ParseURL(window.location.href) + url);
  78405. }
  78406. else {
  78407. return url;
  78408. }
  78409. };
  78410. return Database;
  78411. }());
  78412. BABYLON.Database = Database;
  78413. })(BABYLON || (BABYLON = {}));
  78414. //# sourceMappingURL=babylon.database.js.map
  78415. var BABYLON;
  78416. (function (BABYLON) {
  78417. /**
  78418. * This represents all the required information to add a fresnel effect on a material:
  78419. * @see http://doc.babylonjs.com/how_to/how_to_use_fresnelparameters
  78420. */
  78421. var FresnelParameters = /** @class */ (function () {
  78422. function FresnelParameters() {
  78423. this._isEnabled = true;
  78424. /**
  78425. * Define the color used on edges (grazing angle)
  78426. */
  78427. this.leftColor = BABYLON.Color3.White();
  78428. /**
  78429. * Define the color used on center
  78430. */
  78431. this.rightColor = BABYLON.Color3.Black();
  78432. /**
  78433. * Define bias applied to computed fresnel term
  78434. */
  78435. this.bias = 0;
  78436. /**
  78437. * Defined the power exponent applied to fresnel term
  78438. */
  78439. this.power = 1;
  78440. }
  78441. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  78442. /**
  78443. * Define if the fresnel effect is enable or not.
  78444. */
  78445. get: function () {
  78446. return this._isEnabled;
  78447. },
  78448. set: function (value) {
  78449. if (this._isEnabled === value) {
  78450. return;
  78451. }
  78452. this._isEnabled = value;
  78453. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  78454. },
  78455. enumerable: true,
  78456. configurable: true
  78457. });
  78458. /**
  78459. * Clones the current fresnel and its valuues
  78460. * @returns a clone fresnel configuration
  78461. */
  78462. FresnelParameters.prototype.clone = function () {
  78463. var newFresnelParameters = new FresnelParameters();
  78464. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  78465. return newFresnelParameters;
  78466. };
  78467. /**
  78468. * Serializes the current fresnel parameters to a JSON representation.
  78469. * @return the JSON serialization
  78470. */
  78471. FresnelParameters.prototype.serialize = function () {
  78472. var serializationObject = {};
  78473. serializationObject.isEnabled = this.isEnabled;
  78474. serializationObject.leftColor = this.leftColor.asArray();
  78475. serializationObject.rightColor = this.rightColor.asArray();
  78476. serializationObject.bias = this.bias;
  78477. serializationObject.power = this.power;
  78478. return serializationObject;
  78479. };
  78480. /**
  78481. * Parse a JSON object and deserialize it to a new Fresnel parameter object.
  78482. * @param parsedFresnelParameters Define the JSON representation
  78483. * @returns the parsed parameters
  78484. */
  78485. FresnelParameters.Parse = function (parsedFresnelParameters) {
  78486. var fresnelParameters = new FresnelParameters();
  78487. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  78488. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  78489. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  78490. fresnelParameters.bias = parsedFresnelParameters.bias;
  78491. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  78492. return fresnelParameters;
  78493. };
  78494. return FresnelParameters;
  78495. }());
  78496. BABYLON.FresnelParameters = FresnelParameters;
  78497. })(BABYLON || (BABYLON = {}));
  78498. //# sourceMappingURL=babylon.fresnelParameters.js.map
  78499. var BABYLON;
  78500. (function (BABYLON) {
  78501. /**
  78502. * A multi-material is used to apply different materials to different parts of the same object without the need of
  78503. * separate meshes. This can be use to improve performances.
  78504. * @see http://doc.babylonjs.com/how_to/multi_materials
  78505. */
  78506. var MultiMaterial = /** @class */ (function (_super) {
  78507. __extends(MultiMaterial, _super);
  78508. /**
  78509. * Instantiates a new Multi Material
  78510. * A multi-material is used to apply different materials to different parts of the same object without the need of
  78511. * separate meshes. This can be use to improve performances.
  78512. * @see http://doc.babylonjs.com/how_to/multi_materials
  78513. * @param name Define the name in the scene
  78514. * @param scene Define the scene the material belongs to
  78515. */
  78516. function MultiMaterial(name, scene) {
  78517. var _this = _super.call(this, name, scene, true) || this;
  78518. scene.multiMaterials.push(_this);
  78519. _this.subMaterials = new Array();
  78520. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  78521. return _this;
  78522. }
  78523. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  78524. /**
  78525. * Gets or Sets the list of Materials used within the multi material.
  78526. * They need to be ordered according to the submeshes order in the associated mesh
  78527. */
  78528. get: function () {
  78529. return this._subMaterials;
  78530. },
  78531. set: function (value) {
  78532. this._subMaterials = value;
  78533. this._hookArray(value);
  78534. },
  78535. enumerable: true,
  78536. configurable: true
  78537. });
  78538. MultiMaterial.prototype._hookArray = function (array) {
  78539. var _this = this;
  78540. var oldPush = array.push;
  78541. array.push = function () {
  78542. var items = [];
  78543. for (var _i = 0; _i < arguments.length; _i++) {
  78544. items[_i] = arguments[_i];
  78545. }
  78546. var result = oldPush.apply(array, items);
  78547. _this._markAllSubMeshesAsTexturesDirty();
  78548. return result;
  78549. };
  78550. var oldSplice = array.splice;
  78551. array.splice = function (index, deleteCount) {
  78552. var deleted = oldSplice.apply(array, [index, deleteCount]);
  78553. _this._markAllSubMeshesAsTexturesDirty();
  78554. return deleted;
  78555. };
  78556. };
  78557. /**
  78558. * Get one of the submaterial by its index in the submaterials array
  78559. * @param index The index to look the sub material at
  78560. * @returns The Material if the index has been defined
  78561. */
  78562. MultiMaterial.prototype.getSubMaterial = function (index) {
  78563. if (index < 0 || index >= this.subMaterials.length) {
  78564. return this.getScene().defaultMaterial;
  78565. }
  78566. return this.subMaterials[index];
  78567. };
  78568. /**
  78569. * Get the list of active textures for the whole sub materials list.
  78570. * @returns All the textures that will be used during the rendering
  78571. */
  78572. MultiMaterial.prototype.getActiveTextures = function () {
  78573. var _a;
  78574. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  78575. if (subMaterial) {
  78576. return subMaterial.getActiveTextures();
  78577. }
  78578. else {
  78579. return [];
  78580. }
  78581. }));
  78582. };
  78583. /**
  78584. * Gets the current class name of the material e.g. "MultiMaterial"
  78585. * Mainly use in serialization.
  78586. * @returns the class name
  78587. */
  78588. MultiMaterial.prototype.getClassName = function () {
  78589. return "MultiMaterial";
  78590. };
  78591. /**
  78592. * Checks if the material is ready to render the requested sub mesh
  78593. * @param mesh Define the mesh the submesh belongs to
  78594. * @param subMesh Define the sub mesh to look readyness for
  78595. * @param useInstances Define whether or not the material is used with instances
  78596. * @returns true if ready, otherwise false
  78597. */
  78598. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  78599. for (var index = 0; index < this.subMaterials.length; index++) {
  78600. var subMaterial = this.subMaterials[index];
  78601. if (subMaterial) {
  78602. if (subMaterial.storeEffectOnSubMeshes) {
  78603. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  78604. return false;
  78605. }
  78606. continue;
  78607. }
  78608. if (!subMaterial.isReady(mesh)) {
  78609. return false;
  78610. }
  78611. }
  78612. }
  78613. return true;
  78614. };
  78615. /**
  78616. * Clones the current material and its related sub materials
  78617. * @param name Define the name of the newly cloned material
  78618. * @param cloneChildren Define if submaterial will be cloned or shared with the parent instance
  78619. * @returns the cloned material
  78620. */
  78621. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  78622. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  78623. for (var index = 0; index < this.subMaterials.length; index++) {
  78624. var subMaterial = null;
  78625. var current = this.subMaterials[index];
  78626. if (cloneChildren && current) {
  78627. subMaterial = current.clone(name + "-" + current.name);
  78628. }
  78629. else {
  78630. subMaterial = this.subMaterials[index];
  78631. }
  78632. newMultiMaterial.subMaterials.push(subMaterial);
  78633. }
  78634. return newMultiMaterial;
  78635. };
  78636. /**
  78637. * Serializes the materials into a JSON representation.
  78638. * @returns the JSON representation
  78639. */
  78640. MultiMaterial.prototype.serialize = function () {
  78641. var serializationObject = {};
  78642. serializationObject.name = this.name;
  78643. serializationObject.id = this.id;
  78644. if (BABYLON.Tags) {
  78645. serializationObject.tags = BABYLON.Tags.GetTags(this);
  78646. }
  78647. serializationObject.materials = [];
  78648. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  78649. var subMat = this.subMaterials[matIndex];
  78650. if (subMat) {
  78651. serializationObject.materials.push(subMat.id);
  78652. }
  78653. else {
  78654. serializationObject.materials.push(null);
  78655. }
  78656. }
  78657. return serializationObject;
  78658. };
  78659. /**
  78660. * Dispose the material and release its associated resources
  78661. * @param forceDisposeEffect Define if we want to force disposing the associated effect (if false the shader is not released and could be reuse later on)
  78662. * @param forceDisposeTextures Define if we want to force disposing the associated textures (if false, they will not be disposed and can still be use elsewhere in the app)
  78663. */
  78664. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  78665. var scene = this.getScene();
  78666. if (!scene) {
  78667. return;
  78668. }
  78669. var index = scene.multiMaterials.indexOf(this);
  78670. if (index >= 0) {
  78671. scene.multiMaterials.splice(index, 1);
  78672. }
  78673. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  78674. };
  78675. return MultiMaterial;
  78676. }(BABYLON.Material));
  78677. BABYLON.MultiMaterial = MultiMaterial;
  78678. })(BABYLON || (BABYLON = {}));
  78679. //# sourceMappingURL=babylon.multiMaterial.js.map
  78680. var BABYLON;
  78681. (function (BABYLON) {
  78682. /**
  78683. * Manage the touch inputs to control the movement of a free camera.
  78684. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  78685. */
  78686. var FreeCameraTouchInput = /** @class */ (function () {
  78687. function FreeCameraTouchInput() {
  78688. /**
  78689. * Defines the touch sensibility for rotation.
  78690. * The higher the faster.
  78691. */
  78692. this.touchAngularSensibility = 200000.0;
  78693. /**
  78694. * Defines the touch sensibility for move.
  78695. * The higher the faster.
  78696. */
  78697. this.touchMoveSensibility = 250.0;
  78698. this._offsetX = null;
  78699. this._offsetY = null;
  78700. this._pointerPressed = new Array();
  78701. }
  78702. /**
  78703. * Attach the input controls to a specific dom element to get the input from.
  78704. * @param element Defines the element the controls should be listened from
  78705. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  78706. */
  78707. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  78708. var _this = this;
  78709. var previousPosition = null;
  78710. if (this._pointerInput === undefined) {
  78711. this._onLostFocus = function (evt) {
  78712. _this._offsetX = null;
  78713. _this._offsetY = null;
  78714. };
  78715. this._pointerInput = function (p, s) {
  78716. var evt = p.event;
  78717. if (evt.pointerType === "mouse") {
  78718. return;
  78719. }
  78720. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  78721. if (!noPreventDefault) {
  78722. evt.preventDefault();
  78723. }
  78724. _this._pointerPressed.push(evt.pointerId);
  78725. if (_this._pointerPressed.length !== 1) {
  78726. return;
  78727. }
  78728. previousPosition = {
  78729. x: evt.clientX,
  78730. y: evt.clientY
  78731. };
  78732. }
  78733. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  78734. if (!noPreventDefault) {
  78735. evt.preventDefault();
  78736. }
  78737. var index = _this._pointerPressed.indexOf(evt.pointerId);
  78738. if (index === -1) {
  78739. return;
  78740. }
  78741. _this._pointerPressed.splice(index, 1);
  78742. if (index != 0) {
  78743. return;
  78744. }
  78745. previousPosition = null;
  78746. _this._offsetX = null;
  78747. _this._offsetY = null;
  78748. }
  78749. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  78750. if (!noPreventDefault) {
  78751. evt.preventDefault();
  78752. }
  78753. if (!previousPosition) {
  78754. return;
  78755. }
  78756. var index = _this._pointerPressed.indexOf(evt.pointerId);
  78757. if (index != 0) {
  78758. return;
  78759. }
  78760. _this._offsetX = evt.clientX - previousPosition.x;
  78761. _this._offsetY = -(evt.clientY - previousPosition.y);
  78762. }
  78763. };
  78764. }
  78765. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  78766. if (this._onLostFocus) {
  78767. element.addEventListener("blur", this._onLostFocus);
  78768. }
  78769. };
  78770. /**
  78771. * Detach the current controls from the specified dom element.
  78772. * @param element Defines the element to stop listening the inputs from
  78773. */
  78774. FreeCameraTouchInput.prototype.detachControl = function (element) {
  78775. if (this._pointerInput && element) {
  78776. if (this._observer) {
  78777. this.camera.getScene().onPointerObservable.remove(this._observer);
  78778. this._observer = null;
  78779. }
  78780. if (this._onLostFocus) {
  78781. element.removeEventListener("blur", this._onLostFocus);
  78782. this._onLostFocus = null;
  78783. }
  78784. this._pointerPressed = [];
  78785. this._offsetX = null;
  78786. this._offsetY = null;
  78787. }
  78788. };
  78789. /**
  78790. * Update the current camera state depending on the inputs that have been used this frame.
  78791. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  78792. */
  78793. FreeCameraTouchInput.prototype.checkInputs = function () {
  78794. if (this._offsetX && this._offsetY) {
  78795. var camera = this.camera;
  78796. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  78797. if (this._pointerPressed.length > 1) {
  78798. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  78799. }
  78800. else {
  78801. var speed = camera._computeLocalCameraSpeed();
  78802. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  78803. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  78804. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  78805. }
  78806. }
  78807. };
  78808. /**
  78809. * Gets the class name of the current intput.
  78810. * @returns the class name
  78811. */
  78812. FreeCameraTouchInput.prototype.getClassName = function () {
  78813. return "FreeCameraTouchInput";
  78814. };
  78815. /**
  78816. * Get the friendly name associated with the input class.
  78817. * @returns the input friendly name
  78818. */
  78819. FreeCameraTouchInput.prototype.getSimpleName = function () {
  78820. return "touch";
  78821. };
  78822. __decorate([
  78823. BABYLON.serialize()
  78824. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  78825. __decorate([
  78826. BABYLON.serialize()
  78827. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  78828. return FreeCameraTouchInput;
  78829. }());
  78830. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  78831. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  78832. })(BABYLON || (BABYLON = {}));
  78833. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  78834. var BABYLON;
  78835. (function (BABYLON) {
  78836. BABYLON.Node.AddNodeConstructor("TouchCamera", function (name, scene) {
  78837. return function () { return new TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  78838. });
  78839. /**
  78840. * This represents a FPS type of camera controlled by touch.
  78841. * This is like a universal camera minus the Gamepad controls.
  78842. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  78843. */
  78844. var TouchCamera = /** @class */ (function (_super) {
  78845. __extends(TouchCamera, _super);
  78846. /**
  78847. * Instantiates a new touch camera.
  78848. * This represents a FPS type of camera controlled by touch.
  78849. * This is like a universal camera minus the Gamepad controls.
  78850. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  78851. * @param name Define the name of the camera in the scene
  78852. * @param position Define the start position of the camera in the scene
  78853. * @param scene Define the scene the camera belongs to
  78854. */
  78855. function TouchCamera(name, position, scene) {
  78856. var _this = _super.call(this, name, position, scene) || this;
  78857. _this.inputs.addTouch();
  78858. _this._setupInputs();
  78859. return _this;
  78860. }
  78861. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  78862. /**
  78863. * Defines the touch sensibility for rotation.
  78864. * The higher the faster.
  78865. */
  78866. get: function () {
  78867. var touch = this.inputs.attached["touch"];
  78868. if (touch)
  78869. return touch.touchAngularSensibility;
  78870. return 0;
  78871. },
  78872. set: function (value) {
  78873. var touch = this.inputs.attached["touch"];
  78874. if (touch)
  78875. touch.touchAngularSensibility = value;
  78876. },
  78877. enumerable: true,
  78878. configurable: true
  78879. });
  78880. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  78881. /**
  78882. * Defines the touch sensibility for move.
  78883. * The higher the faster.
  78884. */
  78885. get: function () {
  78886. var touch = this.inputs.attached["touch"];
  78887. if (touch)
  78888. return touch.touchMoveSensibility;
  78889. return 0;
  78890. },
  78891. set: function (value) {
  78892. var touch = this.inputs.attached["touch"];
  78893. if (touch)
  78894. touch.touchMoveSensibility = value;
  78895. },
  78896. enumerable: true,
  78897. configurable: true
  78898. });
  78899. /**
  78900. * Gets the current object class name.
  78901. * @return the class name
  78902. */
  78903. TouchCamera.prototype.getClassName = function () {
  78904. return "TouchCamera";
  78905. };
  78906. /** @hidden */
  78907. TouchCamera.prototype._setupInputs = function () {
  78908. var mouse = this.inputs.attached["mouse"];
  78909. if (mouse) {
  78910. mouse.touchEnabled = false;
  78911. }
  78912. };
  78913. return TouchCamera;
  78914. }(BABYLON.FreeCamera));
  78915. BABYLON.TouchCamera = TouchCamera;
  78916. })(BABYLON || (BABYLON = {}));
  78917. //# sourceMappingURL=babylon.touchCamera.js.map
  78918. var BABYLON;
  78919. (function (BABYLON) {
  78920. /**
  78921. * Procedural texturing is a way to programmatically create a texture. There are 2 types of procedural textures: code-only, and code that references some classic 2D images, sometimes called 'refMaps' or 'sampler' images.
  78922. * This is the base class of any Procedural texture and contains most of the shareable code.
  78923. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  78924. */
  78925. var ProceduralTexture = /** @class */ (function (_super) {
  78926. __extends(ProceduralTexture, _super);
  78927. /**
  78928. * Instantiates a new procedural texture.
  78929. * Procedural texturing is a way to programmatically create a texture. There are 2 types of procedural textures: code-only, and code that references some classic 2D images, sometimes called 'refMaps' or 'sampler' images.
  78930. * This is the base class of any Procedural texture and contains most of the shareable code.
  78931. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  78932. * @param name Define the name of the texture
  78933. * @param size Define the size of the texture to create
  78934. * @param fragment Define the fragment shader to use to generate the texture or null if it is defined later
  78935. * @param scene Define the scene the texture belongs to
  78936. * @param fallbackTexture Define a fallback texture in case there were issues to create the custom texture
  78937. * @param generateMipMaps Define if the texture should creates mip maps or not
  78938. * @param isCube Define if the texture is a cube texture or not (this will render each faces of the cube)
  78939. */
  78940. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  78941. if (fallbackTexture === void 0) { fallbackTexture = null; }
  78942. if (generateMipMaps === void 0) { generateMipMaps = true; }
  78943. if (isCube === void 0) { isCube = false; }
  78944. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  78945. _this.isCube = isCube;
  78946. /**
  78947. * Define if the texture is enabled or not (disabled texture will not render)
  78948. */
  78949. _this.isEnabled = true;
  78950. /**
  78951. * Event raised when the texture is generated
  78952. */
  78953. _this.onGeneratedObservable = new BABYLON.Observable();
  78954. /** @hidden */
  78955. _this._textures = {};
  78956. _this._currentRefreshId = -1;
  78957. _this._refreshRate = 1;
  78958. _this._vertexBuffers = {};
  78959. _this._uniforms = new Array();
  78960. _this._samplers = new Array();
  78961. _this._floats = {};
  78962. _this._ints = {};
  78963. _this._floatsArrays = {};
  78964. _this._colors3 = {};
  78965. _this._colors4 = {};
  78966. _this._vectors2 = {};
  78967. _this._vectors3 = {};
  78968. _this._matrices = {};
  78969. _this._fallbackTextureUsed = false;
  78970. _this._cachedDefines = "";
  78971. _this._contentUpdateId = -1;
  78972. scene = _this.getScene();
  78973. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_PROCEDURALTEXTURE);
  78974. if (!component) {
  78975. component = new BABYLON.ProceduralTextureSceneComponent(scene);
  78976. scene._addComponent(component);
  78977. }
  78978. scene.proceduralTextures.push(_this);
  78979. _this._engine = scene.getEngine();
  78980. _this.name = name;
  78981. _this.isRenderTarget = true;
  78982. _this._size = size;
  78983. _this._generateMipMaps = generateMipMaps;
  78984. _this.setFragment(fragment);
  78985. _this._fallbackTexture = fallbackTexture;
  78986. if (isCube) {
  78987. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  78988. _this.setFloat("face", 0);
  78989. }
  78990. else {
  78991. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  78992. }
  78993. // VBO
  78994. var vertices = [];
  78995. vertices.push(1, 1);
  78996. vertices.push(-1, 1);
  78997. vertices.push(-1, -1);
  78998. vertices.push(1, -1);
  78999. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  79000. _this._createIndexBuffer();
  79001. return _this;
  79002. }
  79003. /**
  79004. * Gets texture content (Use this function wisely as reading from a texture can be slow)
  79005. * @returns an ArrayBufferView (Uint8Array or Float32Array)
  79006. */
  79007. ProceduralTexture.prototype.getContent = function () {
  79008. if (this._contentData && this._currentRefreshId == this._contentUpdateId) {
  79009. return this._contentData;
  79010. }
  79011. this._contentData = this.readPixels(0, 0, this._contentData);
  79012. this._contentUpdateId = this._currentRefreshId;
  79013. return this._contentData;
  79014. };
  79015. ProceduralTexture.prototype._createIndexBuffer = function () {
  79016. var engine = this._engine;
  79017. // Indices
  79018. var indices = [];
  79019. indices.push(0);
  79020. indices.push(1);
  79021. indices.push(2);
  79022. indices.push(0);
  79023. indices.push(2);
  79024. indices.push(3);
  79025. this._indexBuffer = engine.createIndexBuffer(indices);
  79026. };
  79027. /** @hidden */
  79028. ProceduralTexture.prototype._rebuild = function () {
  79029. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  79030. if (vb) {
  79031. vb._rebuild();
  79032. }
  79033. this._createIndexBuffer();
  79034. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  79035. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  79036. }
  79037. };
  79038. /**
  79039. * Resets the texture in order to recreate its associated resources.
  79040. * This can be called in case of context loss
  79041. */
  79042. ProceduralTexture.prototype.reset = function () {
  79043. if (this._effect === undefined) {
  79044. return;
  79045. }
  79046. var engine = this._engine;
  79047. engine._releaseEffect(this._effect);
  79048. };
  79049. ProceduralTexture.prototype._getDefines = function () {
  79050. return "";
  79051. };
  79052. /**
  79053. * Is the texture ready to be used ? (rendered at least once)
  79054. * @returns true if ready, otherwise, false.
  79055. */
  79056. ProceduralTexture.prototype.isReady = function () {
  79057. var _this = this;
  79058. var engine = this._engine;
  79059. var shaders;
  79060. if (!this._fragment) {
  79061. return false;
  79062. }
  79063. if (this._fallbackTextureUsed) {
  79064. return true;
  79065. }
  79066. var defines = this._getDefines();
  79067. if (this._effect && defines === this._cachedDefines && this._effect.isReady()) {
  79068. return true;
  79069. }
  79070. if (this._fragment.fragmentElement !== undefined) {
  79071. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  79072. }
  79073. else {
  79074. shaders = { vertex: "procedural", fragment: this._fragment };
  79075. }
  79076. this._cachedDefines = defines;
  79077. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, defines, undefined, undefined, function () {
  79078. _this.releaseInternalTexture();
  79079. if (_this._fallbackTexture) {
  79080. _this._texture = _this._fallbackTexture._texture;
  79081. if (_this._texture) {
  79082. _this._texture.incrementReferences();
  79083. }
  79084. }
  79085. _this._fallbackTextureUsed = true;
  79086. });
  79087. return this._effect.isReady();
  79088. };
  79089. /**
  79090. * Resets the refresh counter of the texture and start bak from scratch.
  79091. * Could be usefull to regenerate the texture if it is setup to render only once.
  79092. */
  79093. ProceduralTexture.prototype.resetRefreshCounter = function () {
  79094. this._currentRefreshId = -1;
  79095. };
  79096. /**
  79097. * Set the fragment shader to use in order to render the texture.
  79098. * @param fragment This can be set to a path (into the shader store) or to a json object containing a fragmentElement property.
  79099. */
  79100. ProceduralTexture.prototype.setFragment = function (fragment) {
  79101. this._fragment = fragment;
  79102. };
  79103. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  79104. /**
  79105. * Define the refresh rate of the texture or the rendering frequency.
  79106. * Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  79107. */
  79108. get: function () {
  79109. return this._refreshRate;
  79110. },
  79111. set: function (value) {
  79112. this._refreshRate = value;
  79113. this.resetRefreshCounter();
  79114. },
  79115. enumerable: true,
  79116. configurable: true
  79117. });
  79118. /** @hidden */
  79119. ProceduralTexture.prototype._shouldRender = function () {
  79120. if (!this.isEnabled || !this.isReady() || !this._texture) {
  79121. if (this._texture) {
  79122. this._texture.isReady = false;
  79123. }
  79124. return false;
  79125. }
  79126. if (this._fallbackTextureUsed) {
  79127. return false;
  79128. }
  79129. if (this._currentRefreshId === -1) { // At least render once
  79130. this._currentRefreshId = 1;
  79131. return true;
  79132. }
  79133. if (this.refreshRate === this._currentRefreshId) {
  79134. this._currentRefreshId = 1;
  79135. return true;
  79136. }
  79137. this._currentRefreshId++;
  79138. return false;
  79139. };
  79140. /**
  79141. * Get the size the texture is rendering at.
  79142. * @returns the size (texture is always squared)
  79143. */
  79144. ProceduralTexture.prototype.getRenderSize = function () {
  79145. return this._size;
  79146. };
  79147. /**
  79148. * Resize the texture to new value.
  79149. * @param size Define the new size the texture should have
  79150. * @param generateMipMaps Define whether the new texture should create mip maps
  79151. */
  79152. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  79153. if (this._fallbackTextureUsed) {
  79154. return;
  79155. }
  79156. this.releaseInternalTexture();
  79157. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  79158. // Update properties
  79159. this._size = size;
  79160. this._generateMipMaps = generateMipMaps;
  79161. };
  79162. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  79163. if (this._uniforms.indexOf(uniformName) === -1) {
  79164. this._uniforms.push(uniformName);
  79165. }
  79166. };
  79167. /**
  79168. * Set a texture in the shader program used to render.
  79169. * @param name Define the name of the uniform samplers as defined in the shader
  79170. * @param texture Define the texture to bind to this sampler
  79171. * @return the texture itself allowing "fluent" like uniform updates
  79172. */
  79173. ProceduralTexture.prototype.setTexture = function (name, texture) {
  79174. if (this._samplers.indexOf(name) === -1) {
  79175. this._samplers.push(name);
  79176. }
  79177. this._textures[name] = texture;
  79178. return this;
  79179. };
  79180. /**
  79181. * Set a float in the shader.
  79182. * @param name Define the name of the uniform as defined in the shader
  79183. * @param value Define the value to give to the uniform
  79184. * @return the texture itself allowing "fluent" like uniform updates
  79185. */
  79186. ProceduralTexture.prototype.setFloat = function (name, value) {
  79187. this._checkUniform(name);
  79188. this._floats[name] = value;
  79189. return this;
  79190. };
  79191. /**
  79192. * Set a int in the shader.
  79193. * @param name Define the name of the uniform as defined in the shader
  79194. * @param value Define the value to give to the uniform
  79195. * @return the texture itself allowing "fluent" like uniform updates
  79196. */
  79197. ProceduralTexture.prototype.setInt = function (name, value) {
  79198. this._checkUniform(name);
  79199. this._ints[name] = value;
  79200. return this;
  79201. };
  79202. /**
  79203. * Set an array of floats in the shader.
  79204. * @param name Define the name of the uniform as defined in the shader
  79205. * @param value Define the value to give to the uniform
  79206. * @return the texture itself allowing "fluent" like uniform updates
  79207. */
  79208. ProceduralTexture.prototype.setFloats = function (name, value) {
  79209. this._checkUniform(name);
  79210. this._floatsArrays[name] = value;
  79211. return this;
  79212. };
  79213. /**
  79214. * Set a vec3 in the shader from a Color3.
  79215. * @param name Define the name of the uniform as defined in the shader
  79216. * @param value Define the value to give to the uniform
  79217. * @return the texture itself allowing "fluent" like uniform updates
  79218. */
  79219. ProceduralTexture.prototype.setColor3 = function (name, value) {
  79220. this._checkUniform(name);
  79221. this._colors3[name] = value;
  79222. return this;
  79223. };
  79224. /**
  79225. * Set a vec4 in the shader from a Color4.
  79226. * @param name Define the name of the uniform as defined in the shader
  79227. * @param value Define the value to give to the uniform
  79228. * @return the texture itself allowing "fluent" like uniform updates
  79229. */
  79230. ProceduralTexture.prototype.setColor4 = function (name, value) {
  79231. this._checkUniform(name);
  79232. this._colors4[name] = value;
  79233. return this;
  79234. };
  79235. /**
  79236. * Set a vec2 in the shader from a Vector2.
  79237. * @param name Define the name of the uniform as defined in the shader
  79238. * @param value Define the value to give to the uniform
  79239. * @return the texture itself allowing "fluent" like uniform updates
  79240. */
  79241. ProceduralTexture.prototype.setVector2 = function (name, value) {
  79242. this._checkUniform(name);
  79243. this._vectors2[name] = value;
  79244. return this;
  79245. };
  79246. /**
  79247. * Set a vec3 in the shader from a Vector3.
  79248. * @param name Define the name of the uniform as defined in the shader
  79249. * @param value Define the value to give to the uniform
  79250. * @return the texture itself allowing "fluent" like uniform updates
  79251. */
  79252. ProceduralTexture.prototype.setVector3 = function (name, value) {
  79253. this._checkUniform(name);
  79254. this._vectors3[name] = value;
  79255. return this;
  79256. };
  79257. /**
  79258. * Set a mat4 in the shader from a MAtrix.
  79259. * @param name Define the name of the uniform as defined in the shader
  79260. * @param value Define the value to give to the uniform
  79261. * @return the texture itself allowing "fluent" like uniform updates
  79262. */
  79263. ProceduralTexture.prototype.setMatrix = function (name, value) {
  79264. this._checkUniform(name);
  79265. this._matrices[name] = value;
  79266. return this;
  79267. };
  79268. /**
  79269. * Render the texture to its associated render target.
  79270. * @param useCameraPostProcess Define if camera post process should be applied to the texture
  79271. */
  79272. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  79273. var scene = this.getScene();
  79274. if (!scene) {
  79275. return;
  79276. }
  79277. var engine = this._engine;
  79278. // Render
  79279. engine.enableEffect(this._effect);
  79280. engine.setState(false);
  79281. // Texture
  79282. for (var name in this._textures) {
  79283. this._effect.setTexture(name, this._textures[name]);
  79284. }
  79285. // Float
  79286. for (name in this._ints) {
  79287. this._effect.setInt(name, this._ints[name]);
  79288. }
  79289. // Float
  79290. for (name in this._floats) {
  79291. this._effect.setFloat(name, this._floats[name]);
  79292. }
  79293. // Floats
  79294. for (name in this._floatsArrays) {
  79295. this._effect.setArray(name, this._floatsArrays[name]);
  79296. }
  79297. // Color3
  79298. for (name in this._colors3) {
  79299. this._effect.setColor3(name, this._colors3[name]);
  79300. }
  79301. // Color4
  79302. for (name in this._colors4) {
  79303. var color = this._colors4[name];
  79304. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  79305. }
  79306. // Vector2
  79307. for (name in this._vectors2) {
  79308. this._effect.setVector2(name, this._vectors2[name]);
  79309. }
  79310. // Vector3
  79311. for (name in this._vectors3) {
  79312. this._effect.setVector3(name, this._vectors3[name]);
  79313. }
  79314. // Matrix
  79315. for (name in this._matrices) {
  79316. this._effect.setMatrix(name, this._matrices[name]);
  79317. }
  79318. if (!this._texture) {
  79319. return;
  79320. }
  79321. if (this.isCube) {
  79322. for (var face = 0; face < 6; face++) {
  79323. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  79324. // VBOs
  79325. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  79326. this._effect.setFloat("face", face);
  79327. // Clear
  79328. engine.clear(scene.clearColor, true, true, true);
  79329. // Draw order
  79330. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  79331. // Mipmaps
  79332. if (face === 5) {
  79333. engine.generateMipMapsForCubemap(this._texture);
  79334. }
  79335. }
  79336. }
  79337. else {
  79338. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  79339. // VBOs
  79340. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  79341. // Clear
  79342. engine.clear(scene.clearColor, true, true, true);
  79343. // Draw order
  79344. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  79345. }
  79346. // Unbind
  79347. engine.unBindFramebuffer(this._texture, this.isCube);
  79348. if (this.onGenerated) {
  79349. this.onGenerated();
  79350. }
  79351. this.onGeneratedObservable.notifyObservers(this);
  79352. };
  79353. /**
  79354. * Clone the texture.
  79355. * @returns the cloned texture
  79356. */
  79357. ProceduralTexture.prototype.clone = function () {
  79358. var textureSize = this.getSize();
  79359. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  79360. // Base texture
  79361. newTexture.hasAlpha = this.hasAlpha;
  79362. newTexture.level = this.level;
  79363. // RenderTarget Texture
  79364. newTexture.coordinatesMode = this.coordinatesMode;
  79365. return newTexture;
  79366. };
  79367. /**
  79368. * Dispose the texture and release its asoociated resources.
  79369. */
  79370. ProceduralTexture.prototype.dispose = function () {
  79371. var scene = this.getScene();
  79372. if (!scene) {
  79373. return;
  79374. }
  79375. var index = scene.proceduralTextures.indexOf(this);
  79376. if (index >= 0) {
  79377. scene.proceduralTextures.splice(index, 1);
  79378. }
  79379. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  79380. if (vertexBuffer) {
  79381. vertexBuffer.dispose();
  79382. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  79383. }
  79384. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  79385. this._indexBuffer = null;
  79386. }
  79387. _super.prototype.dispose.call(this);
  79388. };
  79389. __decorate([
  79390. BABYLON.serialize()
  79391. ], ProceduralTexture.prototype, "isEnabled", void 0);
  79392. __decorate([
  79393. BABYLON.serialize()
  79394. ], ProceduralTexture.prototype, "_generateMipMaps", void 0);
  79395. __decorate([
  79396. BABYLON.serialize()
  79397. ], ProceduralTexture.prototype, "_size", void 0);
  79398. __decorate([
  79399. BABYLON.serialize()
  79400. ], ProceduralTexture.prototype, "refreshRate", null);
  79401. return ProceduralTexture;
  79402. }(BABYLON.Texture));
  79403. BABYLON.ProceduralTexture = ProceduralTexture;
  79404. })(BABYLON || (BABYLON = {}));
  79405. //# sourceMappingURL=babylon.proceduralTexture.js.map
  79406. var BABYLON;
  79407. (function (BABYLON) {
  79408. /**
  79409. * Defines the Procedural Texture scene component responsible to manage any Procedural Texture
  79410. * in a given scene.
  79411. */
  79412. var ProceduralTextureSceneComponent = /** @class */ (function () {
  79413. /**
  79414. * Creates a new instance of the component for the given scene
  79415. * @param scene Defines the scene to register the component in
  79416. */
  79417. function ProceduralTextureSceneComponent(scene) {
  79418. /**
  79419. * The component name helpfull to identify the component in the list of scene components.
  79420. */
  79421. this.name = BABYLON.SceneComponentConstants.NAME_PROCEDURALTEXTURE;
  79422. this.scene = scene;
  79423. this.scene.proceduralTextures = new Array();
  79424. scene.layers = new Array();
  79425. }
  79426. /**
  79427. * Registers the component in a given scene
  79428. */
  79429. ProceduralTextureSceneComponent.prototype.register = function () {
  79430. this.scene._beforeClearStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE, this, this._beforeClear);
  79431. };
  79432. /**
  79433. * Rebuilds the elements related to this component in case of
  79434. * context lost for instance.
  79435. */
  79436. ProceduralTextureSceneComponent.prototype.rebuild = function () {
  79437. // Nothing to do here.
  79438. };
  79439. /**
  79440. * Disposes the component and the associated ressources.
  79441. */
  79442. ProceduralTextureSceneComponent.prototype.dispose = function () {
  79443. // Nothing to do here.
  79444. };
  79445. ProceduralTextureSceneComponent.prototype._beforeClear = function () {
  79446. if (this.scene.proceduralTexturesEnabled) {
  79447. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
  79448. for (var proceduralIndex = 0; proceduralIndex < this.scene.proceduralTextures.length; proceduralIndex++) {
  79449. var proceduralTexture = this.scene.proceduralTextures[proceduralIndex];
  79450. if (proceduralTexture._shouldRender()) {
  79451. proceduralTexture.render();
  79452. }
  79453. }
  79454. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
  79455. }
  79456. };
  79457. return ProceduralTextureSceneComponent;
  79458. }());
  79459. BABYLON.ProceduralTextureSceneComponent = ProceduralTextureSceneComponent;
  79460. })(BABYLON || (BABYLON = {}));
  79461. //# sourceMappingURL=babylon.proceduralTextureSceneComponent.js.map
  79462. var BABYLON;
  79463. (function (BABYLON) {
  79464. /**
  79465. * Procedural texturing is a way to programmatically create a texture. There are 2 types of procedural textures: code-only, and code that references some classic 2D images, sometimes called 'refMaps' or 'sampler' images.
  79466. * Custom Procedural textures are the easiest way to create your own procedural in your application.
  79467. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures#creating-custom-procedural-textures
  79468. */
  79469. var CustomProceduralTexture = /** @class */ (function (_super) {
  79470. __extends(CustomProceduralTexture, _super);
  79471. /**
  79472. * Instantiates a new Custom Procedural Texture.
  79473. * Procedural texturing is a way to programmatically create a texture. There are 2 types of procedural textures: code-only, and code that references some classic 2D images, sometimes called 'refMaps' or 'sampler' images.
  79474. * Custom Procedural textures are the easiest way to create your own procedural in your application.
  79475. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures#creating-custom-procedural-textures
  79476. * @param name Define the name of the texture
  79477. * @param texturePath Define the folder path containing all the cutom texture related files (config, shaders...)
  79478. * @param size Define the size of the texture to create
  79479. * @param scene Define the scene the texture belongs to
  79480. * @param fallbackTexture Define a fallback texture in case there were issues to create the custom texture
  79481. * @param generateMipMaps Define if the texture should creates mip maps or not
  79482. */
  79483. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  79484. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  79485. _this._animate = true;
  79486. _this._time = 0;
  79487. _this._texturePath = texturePath;
  79488. //Try to load json
  79489. _this._loadJson(texturePath);
  79490. _this.refreshRate = 1;
  79491. return _this;
  79492. }
  79493. CustomProceduralTexture.prototype._loadJson = function (jsonUrl) {
  79494. var _this = this;
  79495. var noConfigFile = function () {
  79496. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  79497. try {
  79498. _this.setFragment(_this._texturePath);
  79499. }
  79500. catch (ex) {
  79501. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  79502. }
  79503. };
  79504. var configFileUrl = jsonUrl + "/config.json";
  79505. var xhr = new XMLHttpRequest();
  79506. xhr.open("GET", configFileUrl, true);
  79507. xhr.addEventListener("load", function () {
  79508. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  79509. try {
  79510. _this._config = JSON.parse(xhr.response);
  79511. _this.updateShaderUniforms();
  79512. _this.updateTextures();
  79513. _this.setFragment(_this._texturePath + "/custom");
  79514. _this._animate = _this._config.animate;
  79515. _this.refreshRate = _this._config.refreshrate;
  79516. }
  79517. catch (ex) {
  79518. noConfigFile();
  79519. }
  79520. }
  79521. else {
  79522. noConfigFile();
  79523. }
  79524. }, false);
  79525. xhr.addEventListener("error", function () {
  79526. noConfigFile();
  79527. }, false);
  79528. try {
  79529. xhr.send();
  79530. }
  79531. catch (ex) {
  79532. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  79533. }
  79534. };
  79535. /**
  79536. * Is the texture ready to be used ? (rendered at least once)
  79537. * @returns true if ready, otherwise, false.
  79538. */
  79539. CustomProceduralTexture.prototype.isReady = function () {
  79540. if (!_super.prototype.isReady.call(this)) {
  79541. return false;
  79542. }
  79543. for (var name in this._textures) {
  79544. var texture = this._textures[name];
  79545. if (!texture.isReady()) {
  79546. return false;
  79547. }
  79548. }
  79549. return true;
  79550. };
  79551. /**
  79552. * Render the texture to its associated render target.
  79553. * @param useCameraPostProcess Define if camera post process should be applied to the texture
  79554. */
  79555. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  79556. var scene = this.getScene();
  79557. if (this._animate && scene) {
  79558. this._time += scene.getAnimationRatio() * 0.03;
  79559. this.updateShaderUniforms();
  79560. }
  79561. _super.prototype.render.call(this, useCameraPostProcess);
  79562. };
  79563. /**
  79564. * Update the list of dependant textures samplers in the shader.
  79565. */
  79566. CustomProceduralTexture.prototype.updateTextures = function () {
  79567. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  79568. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  79569. }
  79570. };
  79571. /**
  79572. * Update the uniform values of the procedural texture in the shader.
  79573. */
  79574. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  79575. if (this._config) {
  79576. for (var j = 0; j < this._config.uniforms.length; j++) {
  79577. var uniform = this._config.uniforms[j];
  79578. switch (uniform.type) {
  79579. case "float":
  79580. this.setFloat(uniform.name, uniform.value);
  79581. break;
  79582. case "color3":
  79583. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  79584. break;
  79585. case "color4":
  79586. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  79587. break;
  79588. case "vector2":
  79589. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  79590. break;
  79591. case "vector3":
  79592. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  79593. break;
  79594. }
  79595. }
  79596. }
  79597. this.setFloat("time", this._time);
  79598. };
  79599. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  79600. /**
  79601. * Define if the texture animates or not.
  79602. */
  79603. get: function () {
  79604. return this._animate;
  79605. },
  79606. set: function (value) {
  79607. this._animate = value;
  79608. },
  79609. enumerable: true,
  79610. configurable: true
  79611. });
  79612. return CustomProceduralTexture;
  79613. }(BABYLON.ProceduralTexture));
  79614. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  79615. })(BABYLON || (BABYLON = {}));
  79616. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  79617. var BABYLON;
  79618. (function (BABYLON) {
  79619. /**
  79620. * Manage the gamepad inputs to control a free camera.
  79621. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  79622. */
  79623. var FreeCameraGamepadInput = /** @class */ (function () {
  79624. function FreeCameraGamepadInput() {
  79625. /**
  79626. * Defines the gamepad rotation sensiblity.
  79627. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  79628. */
  79629. this.gamepadAngularSensibility = 200;
  79630. /**
  79631. * Defines the gamepad move sensiblity.
  79632. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  79633. */
  79634. this.gamepadMoveSensibility = 40;
  79635. this._cameraTransform = BABYLON.Matrix.Identity();
  79636. this._deltaTransform = BABYLON.Vector3.Zero();
  79637. this._vector3 = BABYLON.Vector3.Zero();
  79638. this._vector2 = BABYLON.Vector2.Zero();
  79639. }
  79640. /**
  79641. * Attach the input controls to a specific dom element to get the input from.
  79642. * @param element Defines the element the controls should be listened from
  79643. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  79644. */
  79645. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  79646. var _this = this;
  79647. var manager = this.camera.getScene().gamepadManager;
  79648. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  79649. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  79650. // prioritize XBOX gamepads.
  79651. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  79652. _this.gamepad = gamepad;
  79653. }
  79654. }
  79655. });
  79656. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  79657. if (_this.gamepad === gamepad) {
  79658. _this.gamepad = null;
  79659. }
  79660. });
  79661. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  79662. };
  79663. /**
  79664. * Detach the current controls from the specified dom element.
  79665. * @param element Defines the element to stop listening the inputs from
  79666. */
  79667. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  79668. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  79669. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  79670. this.gamepad = null;
  79671. };
  79672. /**
  79673. * Update the current camera state depending on the inputs that have been used this frame.
  79674. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  79675. */
  79676. FreeCameraGamepadInput.prototype.checkInputs = function () {
  79677. if (this.gamepad && this.gamepad.leftStick) {
  79678. var camera = this.camera;
  79679. var LSValues = this.gamepad.leftStick;
  79680. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  79681. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  79682. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  79683. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  79684. var RSValues = this.gamepad.rightStick;
  79685. if (RSValues) {
  79686. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  79687. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  79688. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  79689. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  79690. }
  79691. else {
  79692. RSValues = { x: 0, y: 0 };
  79693. }
  79694. if (!camera.rotationQuaternion) {
  79695. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  79696. }
  79697. else {
  79698. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  79699. }
  79700. var speed = camera._computeLocalCameraSpeed() * 50.0;
  79701. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  79702. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  79703. camera.cameraDirection.addInPlace(this._deltaTransform);
  79704. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  79705. camera.cameraRotation.addInPlace(this._vector2);
  79706. }
  79707. };
  79708. /**
  79709. * Gets the class name of the current intput.
  79710. * @returns the class name
  79711. */
  79712. FreeCameraGamepadInput.prototype.getClassName = function () {
  79713. return "FreeCameraGamepadInput";
  79714. };
  79715. /**
  79716. * Get the friendly name associated with the input class.
  79717. * @returns the input friendly name
  79718. */
  79719. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  79720. return "gamepad";
  79721. };
  79722. __decorate([
  79723. BABYLON.serialize()
  79724. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  79725. __decorate([
  79726. BABYLON.serialize()
  79727. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  79728. return FreeCameraGamepadInput;
  79729. }());
  79730. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  79731. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  79732. })(BABYLON || (BABYLON = {}));
  79733. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  79734. var BABYLON;
  79735. (function (BABYLON) {
  79736. /**
  79737. * Manage the gamepad inputs to control an arc rotate camera.
  79738. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  79739. */
  79740. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  79741. function ArcRotateCameraGamepadInput() {
  79742. /**
  79743. * Defines the gamepad rotation sensiblity.
  79744. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  79745. */
  79746. this.gamepadRotationSensibility = 80;
  79747. /**
  79748. * Defines the gamepad move sensiblity.
  79749. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  79750. */
  79751. this.gamepadMoveSensibility = 40;
  79752. }
  79753. /**
  79754. * Attach the input controls to a specific dom element to get the input from.
  79755. * @param element Defines the element the controls should be listened from
  79756. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  79757. */
  79758. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  79759. var _this = this;
  79760. var manager = this.camera.getScene().gamepadManager;
  79761. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  79762. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  79763. // prioritize XBOX gamepads.
  79764. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  79765. _this.gamepad = gamepad;
  79766. }
  79767. }
  79768. });
  79769. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  79770. if (_this.gamepad === gamepad) {
  79771. _this.gamepad = null;
  79772. }
  79773. });
  79774. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  79775. };
  79776. /**
  79777. * Detach the current controls from the specified dom element.
  79778. * @param element Defines the element to stop listening the inputs from
  79779. */
  79780. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  79781. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  79782. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  79783. this.gamepad = null;
  79784. };
  79785. /**
  79786. * Update the current camera state depending on the inputs that have been used this frame.
  79787. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  79788. */
  79789. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  79790. if (this.gamepad) {
  79791. var camera = this.camera;
  79792. var RSValues = this.gamepad.rightStick;
  79793. if (RSValues) {
  79794. if (RSValues.x != 0) {
  79795. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  79796. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  79797. camera.inertialAlphaOffset += normalizedRX;
  79798. }
  79799. }
  79800. if (RSValues.y != 0) {
  79801. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  79802. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  79803. camera.inertialBetaOffset += normalizedRY;
  79804. }
  79805. }
  79806. }
  79807. var LSValues = this.gamepad.leftStick;
  79808. if (LSValues && LSValues.y != 0) {
  79809. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  79810. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  79811. this.camera.inertialRadiusOffset -= normalizedLY;
  79812. }
  79813. }
  79814. }
  79815. };
  79816. /**
  79817. * Gets the class name of the current intput.
  79818. * @returns the class name
  79819. */
  79820. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  79821. return "ArcRotateCameraGamepadInput";
  79822. };
  79823. /**
  79824. * Get the friendly name associated with the input class.
  79825. * @returns the input friendly name
  79826. */
  79827. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  79828. return "gamepad";
  79829. };
  79830. __decorate([
  79831. BABYLON.serialize()
  79832. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  79833. __decorate([
  79834. BABYLON.serialize()
  79835. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  79836. return ArcRotateCameraGamepadInput;
  79837. }());
  79838. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  79839. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  79840. })(BABYLON || (BABYLON = {}));
  79841. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  79842. var BABYLON;
  79843. (function (BABYLON) {
  79844. /**
  79845. * Manager for handling gamepads
  79846. */
  79847. var GamepadManager = /** @class */ (function () {
  79848. /**
  79849. * Initializes the gamepad manager
  79850. * @param _scene BabylonJS scene
  79851. */
  79852. function GamepadManager(_scene) {
  79853. var _this = this;
  79854. this._scene = _scene;
  79855. this._babylonGamepads = [];
  79856. this._oneGamepadConnected = false;
  79857. /** @hidden */
  79858. this._isMonitoring = false;
  79859. /**
  79860. * observable to be triggered when the gamepad controller has been disconnected
  79861. */
  79862. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  79863. if (!BABYLON.Tools.IsWindowObjectExist()) {
  79864. this._gamepadEventSupported = false;
  79865. }
  79866. else {
  79867. this._gamepadEventSupported = 'GamepadEvent' in window;
  79868. this._gamepadSupport = (navigator.getGamepads ||
  79869. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  79870. }
  79871. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  79872. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  79873. for (var i in _this._babylonGamepads) {
  79874. var gamepad = _this._babylonGamepads[i];
  79875. if (gamepad && gamepad._isConnected) {
  79876. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  79877. }
  79878. }
  79879. });
  79880. this._onGamepadConnectedEvent = function (evt) {
  79881. var gamepad = evt.gamepad;
  79882. if (gamepad.index in _this._babylonGamepads) {
  79883. if (_this._babylonGamepads[gamepad.index].isConnected) {
  79884. return;
  79885. }
  79886. }
  79887. var newGamepad;
  79888. if (_this._babylonGamepads[gamepad.index]) {
  79889. newGamepad = _this._babylonGamepads[gamepad.index];
  79890. newGamepad.browserGamepad = gamepad;
  79891. newGamepad._isConnected = true;
  79892. }
  79893. else {
  79894. newGamepad = _this._addNewGamepad(gamepad);
  79895. }
  79896. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  79897. _this._startMonitoringGamepads();
  79898. };
  79899. this._onGamepadDisconnectedEvent = function (evt) {
  79900. var gamepad = evt.gamepad;
  79901. // Remove the gamepad from the list of gamepads to monitor.
  79902. for (var i in _this._babylonGamepads) {
  79903. if (_this._babylonGamepads[i].index === gamepad.index) {
  79904. var disconnectedGamepad = _this._babylonGamepads[i];
  79905. disconnectedGamepad._isConnected = false;
  79906. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  79907. break;
  79908. }
  79909. }
  79910. };
  79911. if (this._gamepadSupport) {
  79912. //first add already-connected gamepads
  79913. this._updateGamepadObjects();
  79914. if (this._babylonGamepads.length) {
  79915. this._startMonitoringGamepads();
  79916. }
  79917. // Checking if the gamepad connected event is supported (like in Firefox)
  79918. if (this._gamepadEventSupported) {
  79919. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  79920. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  79921. }
  79922. else {
  79923. this._startMonitoringGamepads();
  79924. }
  79925. }
  79926. }
  79927. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  79928. /**
  79929. * The gamepads in the game pad manager
  79930. */
  79931. get: function () {
  79932. return this._babylonGamepads;
  79933. },
  79934. enumerable: true,
  79935. configurable: true
  79936. });
  79937. /**
  79938. * Get the gamepad controllers based on type
  79939. * @param type The type of gamepad controller
  79940. * @returns Nullable gamepad
  79941. */
  79942. GamepadManager.prototype.getGamepadByType = function (type) {
  79943. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  79944. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  79945. var gamepad = _a[_i];
  79946. if (gamepad && gamepad.type === type) {
  79947. return gamepad;
  79948. }
  79949. }
  79950. return null;
  79951. };
  79952. /**
  79953. * Disposes the gamepad manager
  79954. */
  79955. GamepadManager.prototype.dispose = function () {
  79956. if (this._gamepadEventSupported) {
  79957. if (this._onGamepadConnectedEvent) {
  79958. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  79959. }
  79960. if (this._onGamepadDisconnectedEvent) {
  79961. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  79962. }
  79963. this._onGamepadConnectedEvent = null;
  79964. this._onGamepadDisconnectedEvent = null;
  79965. }
  79966. this._babylonGamepads.forEach(function (gamepad) {
  79967. gamepad.dispose();
  79968. });
  79969. this.onGamepadConnectedObservable.clear();
  79970. this.onGamepadDisconnectedObservable.clear();
  79971. this._oneGamepadConnected = false;
  79972. this._stopMonitoringGamepads();
  79973. this._babylonGamepads = [];
  79974. };
  79975. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  79976. if (!this._oneGamepadConnected) {
  79977. this._oneGamepadConnected = true;
  79978. }
  79979. var newGamepad;
  79980. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  79981. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  79982. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  79983. }
  79984. // if pose is supported, use the (WebVR) pose enabled controller
  79985. else if (gamepad.pose) {
  79986. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  79987. }
  79988. else {
  79989. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  79990. }
  79991. this._babylonGamepads[newGamepad.index] = newGamepad;
  79992. return newGamepad;
  79993. };
  79994. GamepadManager.prototype._startMonitoringGamepads = function () {
  79995. if (!this._isMonitoring) {
  79996. this._isMonitoring = true;
  79997. //back-comp
  79998. if (!this._scene) {
  79999. this._checkGamepadsStatus();
  80000. }
  80001. }
  80002. };
  80003. GamepadManager.prototype._stopMonitoringGamepads = function () {
  80004. this._isMonitoring = false;
  80005. };
  80006. /** @hidden */
  80007. GamepadManager.prototype._checkGamepadsStatus = function () {
  80008. var _this = this;
  80009. // Hack to be compatible Chrome
  80010. this._updateGamepadObjects();
  80011. for (var i in this._babylonGamepads) {
  80012. var gamepad = this._babylonGamepads[i];
  80013. if (!gamepad || !gamepad.isConnected) {
  80014. continue;
  80015. }
  80016. gamepad.update();
  80017. }
  80018. if (this._isMonitoring && !this._scene) {
  80019. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  80020. }
  80021. };
  80022. // This function is called only on Chrome, which does not properly support
  80023. // connection/disconnection events and forces you to recopy again the gamepad object
  80024. GamepadManager.prototype._updateGamepadObjects = function () {
  80025. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  80026. for (var i = 0; i < gamepads.length; i++) {
  80027. var gamepad = gamepads[i];
  80028. if (gamepad) {
  80029. if (!this._babylonGamepads[gamepad.index]) {
  80030. var newGamepad = this._addNewGamepad(gamepad);
  80031. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  80032. }
  80033. else {
  80034. // Forced to copy again this object for Chrome for unknown reason
  80035. this._babylonGamepads[i].browserGamepad = gamepad;
  80036. if (!this._babylonGamepads[i].isConnected) {
  80037. this._babylonGamepads[i]._isConnected = true;
  80038. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  80039. }
  80040. }
  80041. }
  80042. }
  80043. };
  80044. return GamepadManager;
  80045. }());
  80046. BABYLON.GamepadManager = GamepadManager;
  80047. })(BABYLON || (BABYLON = {}));
  80048. //# sourceMappingURL=babylon.gamepadManager.js.map
  80049. var BABYLON;
  80050. (function (BABYLON) {
  80051. /**
  80052. * Represents a gamepad control stick position
  80053. */
  80054. var StickValues = /** @class */ (function () {
  80055. /**
  80056. * Initializes the gamepad x and y control stick values
  80057. * @param x The x component of the gamepad control stick value
  80058. * @param y The y component of the gamepad control stick value
  80059. */
  80060. function StickValues(
  80061. /**
  80062. * The x component of the control stick
  80063. */
  80064. x,
  80065. /**
  80066. * The y component of the control stick
  80067. */
  80068. y) {
  80069. this.x = x;
  80070. this.y = y;
  80071. }
  80072. return StickValues;
  80073. }());
  80074. BABYLON.StickValues = StickValues;
  80075. /**
  80076. * Represents a gamepad
  80077. */
  80078. var Gamepad = /** @class */ (function () {
  80079. /**
  80080. * Initializes the gamepad
  80081. * @param id The id of the gamepad
  80082. * @param index The index of the gamepad
  80083. * @param browserGamepad The browser gamepad
  80084. * @param leftStickX The x component of the left joystick
  80085. * @param leftStickY The y component of the left joystick
  80086. * @param rightStickX The x component of the right joystick
  80087. * @param rightStickY The y component of the right joystick
  80088. */
  80089. function Gamepad(
  80090. /**
  80091. * The id of the gamepad
  80092. */
  80093. id,
  80094. /**
  80095. * The index of the gamepad
  80096. */
  80097. index,
  80098. /**
  80099. * The browser gamepad
  80100. */
  80101. browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  80102. if (leftStickX === void 0) { leftStickX = 0; }
  80103. if (leftStickY === void 0) { leftStickY = 1; }
  80104. if (rightStickX === void 0) { rightStickX = 2; }
  80105. if (rightStickY === void 0) { rightStickY = 3; }
  80106. this.id = id;
  80107. this.index = index;
  80108. this.browserGamepad = browserGamepad;
  80109. this._leftStick = { x: 0, y: 0 };
  80110. this._rightStick = { x: 0, y: 0 };
  80111. /** @hidden */
  80112. this._isConnected = true;
  80113. /**
  80114. * Specifies whether the left control stick should be Y-inverted
  80115. */
  80116. this._invertLeftStickY = false;
  80117. this.type = Gamepad.GAMEPAD;
  80118. this._leftStickAxisX = leftStickX;
  80119. this._leftStickAxisY = leftStickY;
  80120. this._rightStickAxisX = rightStickX;
  80121. this._rightStickAxisY = rightStickY;
  80122. if (this.browserGamepad.axes.length >= 2) {
  80123. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  80124. }
  80125. if (this.browserGamepad.axes.length >= 4) {
  80126. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  80127. }
  80128. }
  80129. Object.defineProperty(Gamepad.prototype, "isConnected", {
  80130. /**
  80131. * Specifies if the gamepad has been connected
  80132. */
  80133. get: function () {
  80134. return this._isConnected;
  80135. },
  80136. enumerable: true,
  80137. configurable: true
  80138. });
  80139. /**
  80140. * Callback triggered when the left joystick has changed
  80141. * @param callback
  80142. */
  80143. Gamepad.prototype.onleftstickchanged = function (callback) {
  80144. this._onleftstickchanged = callback;
  80145. };
  80146. /**
  80147. * Callback triggered when the right joystick has changed
  80148. * @param callback
  80149. */
  80150. Gamepad.prototype.onrightstickchanged = function (callback) {
  80151. this._onrightstickchanged = callback;
  80152. };
  80153. Object.defineProperty(Gamepad.prototype, "leftStick", {
  80154. /**
  80155. * Gets the left joystick
  80156. */
  80157. get: function () {
  80158. return this._leftStick;
  80159. },
  80160. /**
  80161. * Sets the left joystick values
  80162. */
  80163. set: function (newValues) {
  80164. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  80165. this._onleftstickchanged(newValues);
  80166. }
  80167. this._leftStick = newValues;
  80168. },
  80169. enumerable: true,
  80170. configurable: true
  80171. });
  80172. Object.defineProperty(Gamepad.prototype, "rightStick", {
  80173. /**
  80174. * Gets the right joystick
  80175. */
  80176. get: function () {
  80177. return this._rightStick;
  80178. },
  80179. /**
  80180. * Sets the right joystick value
  80181. */
  80182. set: function (newValues) {
  80183. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  80184. this._onrightstickchanged(newValues);
  80185. }
  80186. this._rightStick = newValues;
  80187. },
  80188. enumerable: true,
  80189. configurable: true
  80190. });
  80191. /**
  80192. * Updates the gamepad joystick positions
  80193. */
  80194. Gamepad.prototype.update = function () {
  80195. if (this._leftStick) {
  80196. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  80197. if (this._invertLeftStickY) {
  80198. this.leftStick.y *= -1;
  80199. }
  80200. }
  80201. if (this._rightStick) {
  80202. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  80203. }
  80204. };
  80205. /**
  80206. * Disposes the gamepad
  80207. */
  80208. Gamepad.prototype.dispose = function () {
  80209. };
  80210. /**
  80211. * Represents a gamepad controller
  80212. */
  80213. Gamepad.GAMEPAD = 0;
  80214. /**
  80215. * Represents a generic controller
  80216. */
  80217. Gamepad.GENERIC = 1;
  80218. /**
  80219. * Represents an XBox controller
  80220. */
  80221. Gamepad.XBOX = 2;
  80222. /**
  80223. * Represents a pose-enabled controller
  80224. */
  80225. Gamepad.POSE_ENABLED = 3;
  80226. return Gamepad;
  80227. }());
  80228. BABYLON.Gamepad = Gamepad;
  80229. /**
  80230. * Represents a generic gamepad
  80231. */
  80232. var GenericPad = /** @class */ (function (_super) {
  80233. __extends(GenericPad, _super);
  80234. /**
  80235. * Initializes the generic gamepad
  80236. * @param id The id of the generic gamepad
  80237. * @param index The index of the generic gamepad
  80238. * @param browserGamepad The browser gamepad
  80239. */
  80240. function GenericPad(id, index, browserGamepad) {
  80241. var _this = _super.call(this, id, index, browserGamepad) || this;
  80242. /**
  80243. * Observable triggered when a button has been pressed
  80244. */
  80245. _this.onButtonDownObservable = new BABYLON.Observable();
  80246. /**
  80247. * Observable triggered when a button has been released
  80248. */
  80249. _this.onButtonUpObservable = new BABYLON.Observable();
  80250. _this.type = Gamepad.GENERIC;
  80251. _this._buttons = new Array(browserGamepad.buttons.length);
  80252. return _this;
  80253. }
  80254. /**
  80255. * Callback triggered when a button has been pressed
  80256. * @param callback Called when a button has been pressed
  80257. */
  80258. GenericPad.prototype.onbuttondown = function (callback) {
  80259. this._onbuttondown = callback;
  80260. };
  80261. /**
  80262. * Callback triggered when a button has been released
  80263. * @param callback Called when a button has been released
  80264. */
  80265. GenericPad.prototype.onbuttonup = function (callback) {
  80266. this._onbuttonup = callback;
  80267. };
  80268. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  80269. if (newValue !== currentValue) {
  80270. if (newValue === 1) {
  80271. if (this._onbuttondown) {
  80272. this._onbuttondown(buttonIndex);
  80273. }
  80274. this.onButtonDownObservable.notifyObservers(buttonIndex);
  80275. }
  80276. if (newValue === 0) {
  80277. if (this._onbuttonup) {
  80278. this._onbuttonup(buttonIndex);
  80279. }
  80280. this.onButtonUpObservable.notifyObservers(buttonIndex);
  80281. }
  80282. }
  80283. return newValue;
  80284. };
  80285. /**
  80286. * Updates the generic gamepad
  80287. */
  80288. GenericPad.prototype.update = function () {
  80289. _super.prototype.update.call(this);
  80290. for (var index = 0; index < this._buttons.length; index++) {
  80291. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  80292. }
  80293. };
  80294. /**
  80295. * Disposes the generic gamepad
  80296. */
  80297. GenericPad.prototype.dispose = function () {
  80298. _super.prototype.dispose.call(this);
  80299. this.onButtonDownObservable.clear();
  80300. this.onButtonUpObservable.clear();
  80301. };
  80302. return GenericPad;
  80303. }(Gamepad));
  80304. BABYLON.GenericPad = GenericPad;
  80305. })(BABYLON || (BABYLON = {}));
  80306. //# sourceMappingURL=babylon.gamepad.js.map
  80307. var BABYLON;
  80308. (function (BABYLON) {
  80309. /**
  80310. * Defines supported buttons for XBox360 compatible gamepads
  80311. */
  80312. var Xbox360Button;
  80313. (function (Xbox360Button) {
  80314. /** A */
  80315. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  80316. /** B */
  80317. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  80318. /** X */
  80319. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  80320. /** Y */
  80321. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  80322. /** Start */
  80323. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  80324. /** Back */
  80325. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  80326. /** Left button */
  80327. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  80328. /** Right button */
  80329. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  80330. /** Left stick */
  80331. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  80332. /** Right stick */
  80333. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  80334. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  80335. /** Defines values for XBox360 DPad */
  80336. var Xbox360Dpad;
  80337. (function (Xbox360Dpad) {
  80338. /** Up */
  80339. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  80340. /** Down */
  80341. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  80342. /** Left */
  80343. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  80344. /** Right */
  80345. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  80346. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  80347. /**
  80348. * Defines a XBox360 gamepad
  80349. */
  80350. var Xbox360Pad = /** @class */ (function (_super) {
  80351. __extends(Xbox360Pad, _super);
  80352. /**
  80353. * Creates a new XBox360 gamepad object
  80354. * @param id defines the id of this gamepad
  80355. * @param index defines its index
  80356. * @param gamepad defines the internal HTML gamepad object
  80357. * @param xboxOne defines if it is a XBox One gamepad
  80358. */
  80359. function Xbox360Pad(id, index, gamepad, xboxOne) {
  80360. if (xboxOne === void 0) { xboxOne = false; }
  80361. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  80362. _this._leftTrigger = 0;
  80363. _this._rightTrigger = 0;
  80364. /** Observable raised when a button is pressed */
  80365. _this.onButtonDownObservable = new BABYLON.Observable();
  80366. /** Observable raised when a button is released */
  80367. _this.onButtonUpObservable = new BABYLON.Observable();
  80368. /** Observable raised when a pad is pressed */
  80369. _this.onPadDownObservable = new BABYLON.Observable();
  80370. /** Observable raised when a pad is released */
  80371. _this.onPadUpObservable = new BABYLON.Observable();
  80372. _this._buttonA = 0;
  80373. _this._buttonB = 0;
  80374. _this._buttonX = 0;
  80375. _this._buttonY = 0;
  80376. _this._buttonBack = 0;
  80377. _this._buttonStart = 0;
  80378. _this._buttonLB = 0;
  80379. _this._buttonRB = 0;
  80380. _this._buttonLeftStick = 0;
  80381. _this._buttonRightStick = 0;
  80382. _this._dPadUp = 0;
  80383. _this._dPadDown = 0;
  80384. _this._dPadLeft = 0;
  80385. _this._dPadRight = 0;
  80386. _this._isXboxOnePad = false;
  80387. _this.type = BABYLON.Gamepad.XBOX;
  80388. _this._isXboxOnePad = xboxOne;
  80389. return _this;
  80390. }
  80391. /**
  80392. * Defines the callback to call when left trigger is pressed
  80393. * @param callback defines the callback to use
  80394. */
  80395. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  80396. this._onlefttriggerchanged = callback;
  80397. };
  80398. /**
  80399. * Defines the callback to call when right trigger is pressed
  80400. * @param callback defines the callback to use
  80401. */
  80402. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  80403. this._onrighttriggerchanged = callback;
  80404. };
  80405. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  80406. /**
  80407. * Gets the left trigger value
  80408. */
  80409. get: function () {
  80410. return this._leftTrigger;
  80411. },
  80412. /**
  80413. * Sets the left trigger value
  80414. */
  80415. set: function (newValue) {
  80416. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  80417. this._onlefttriggerchanged(newValue);
  80418. }
  80419. this._leftTrigger = newValue;
  80420. },
  80421. enumerable: true,
  80422. configurable: true
  80423. });
  80424. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  80425. /**
  80426. * Gets the right trigger value
  80427. */
  80428. get: function () {
  80429. return this._rightTrigger;
  80430. },
  80431. /**
  80432. * Sets the right trigger value
  80433. */
  80434. set: function (newValue) {
  80435. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  80436. this._onrighttriggerchanged(newValue);
  80437. }
  80438. this._rightTrigger = newValue;
  80439. },
  80440. enumerable: true,
  80441. configurable: true
  80442. });
  80443. /**
  80444. * Defines the callback to call when a button is pressed
  80445. * @param callback defines the callback to use
  80446. */
  80447. Xbox360Pad.prototype.onbuttondown = function (callback) {
  80448. this._onbuttondown = callback;
  80449. };
  80450. /**
  80451. * Defines the callback to call when a button is released
  80452. * @param callback defines the callback to use
  80453. */
  80454. Xbox360Pad.prototype.onbuttonup = function (callback) {
  80455. this._onbuttonup = callback;
  80456. };
  80457. /**
  80458. * Defines the callback to call when a pad is pressed
  80459. * @param callback defines the callback to use
  80460. */
  80461. Xbox360Pad.prototype.ondpaddown = function (callback) {
  80462. this._ondpaddown = callback;
  80463. };
  80464. /**
  80465. * Defines the callback to call when a pad is released
  80466. * @param callback defines the callback to use
  80467. */
  80468. Xbox360Pad.prototype.ondpadup = function (callback) {
  80469. this._ondpadup = callback;
  80470. };
  80471. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  80472. if (newValue !== currentValue) {
  80473. if (newValue === 1) {
  80474. if (this._onbuttondown) {
  80475. this._onbuttondown(buttonType);
  80476. }
  80477. this.onButtonDownObservable.notifyObservers(buttonType);
  80478. }
  80479. if (newValue === 0) {
  80480. if (this._onbuttonup) {
  80481. this._onbuttonup(buttonType);
  80482. }
  80483. this.onButtonUpObservable.notifyObservers(buttonType);
  80484. }
  80485. }
  80486. return newValue;
  80487. };
  80488. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  80489. if (newValue !== currentValue) {
  80490. if (newValue === 1) {
  80491. if (this._ondpaddown) {
  80492. this._ondpaddown(buttonType);
  80493. }
  80494. this.onPadDownObservable.notifyObservers(buttonType);
  80495. }
  80496. if (newValue === 0) {
  80497. if (this._ondpadup) {
  80498. this._ondpadup(buttonType);
  80499. }
  80500. this.onPadUpObservable.notifyObservers(buttonType);
  80501. }
  80502. }
  80503. return newValue;
  80504. };
  80505. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  80506. /**
  80507. * Gets the value of the `A` button
  80508. */
  80509. get: function () {
  80510. return this._buttonA;
  80511. },
  80512. /**
  80513. * Sets the value of the `A` button
  80514. */
  80515. set: function (value) {
  80516. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  80517. },
  80518. enumerable: true,
  80519. configurable: true
  80520. });
  80521. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  80522. /**
  80523. * Gets the value of the `B` button
  80524. */
  80525. get: function () {
  80526. return this._buttonB;
  80527. },
  80528. /**
  80529. * Sets the value of the `B` button
  80530. */
  80531. set: function (value) {
  80532. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  80533. },
  80534. enumerable: true,
  80535. configurable: true
  80536. });
  80537. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  80538. /**
  80539. * Gets the value of the `X` button
  80540. */
  80541. get: function () {
  80542. return this._buttonX;
  80543. },
  80544. /**
  80545. * Sets the value of the `X` button
  80546. */
  80547. set: function (value) {
  80548. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  80549. },
  80550. enumerable: true,
  80551. configurable: true
  80552. });
  80553. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  80554. /**
  80555. * Gets the value of the `Y` button
  80556. */
  80557. get: function () {
  80558. return this._buttonY;
  80559. },
  80560. /**
  80561. * Sets the value of the `Y` button
  80562. */
  80563. set: function (value) {
  80564. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  80565. },
  80566. enumerable: true,
  80567. configurable: true
  80568. });
  80569. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  80570. /**
  80571. * Gets the value of the `Start` button
  80572. */
  80573. get: function () {
  80574. return this._buttonStart;
  80575. },
  80576. /**
  80577. * Sets the value of the `Start` button
  80578. */
  80579. set: function (value) {
  80580. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  80581. },
  80582. enumerable: true,
  80583. configurable: true
  80584. });
  80585. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  80586. /**
  80587. * Gets the value of the `Back` button
  80588. */
  80589. get: function () {
  80590. return this._buttonBack;
  80591. },
  80592. /**
  80593. * Sets the value of the `Back` button
  80594. */
  80595. set: function (value) {
  80596. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  80597. },
  80598. enumerable: true,
  80599. configurable: true
  80600. });
  80601. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  80602. /**
  80603. * Gets the value of the `Left` button
  80604. */
  80605. get: function () {
  80606. return this._buttonLB;
  80607. },
  80608. /**
  80609. * Sets the value of the `Left` button
  80610. */
  80611. set: function (value) {
  80612. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  80613. },
  80614. enumerable: true,
  80615. configurable: true
  80616. });
  80617. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  80618. /**
  80619. * Gets the value of the `Right` button
  80620. */
  80621. get: function () {
  80622. return this._buttonRB;
  80623. },
  80624. /**
  80625. * Sets the value of the `Right` button
  80626. */
  80627. set: function (value) {
  80628. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  80629. },
  80630. enumerable: true,
  80631. configurable: true
  80632. });
  80633. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  80634. /**
  80635. * Gets the value of the Left joystick
  80636. */
  80637. get: function () {
  80638. return this._buttonLeftStick;
  80639. },
  80640. /**
  80641. * Sets the value of the Left joystick
  80642. */
  80643. set: function (value) {
  80644. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  80645. },
  80646. enumerable: true,
  80647. configurable: true
  80648. });
  80649. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  80650. /**
  80651. * Gets the value of the Right joystick
  80652. */
  80653. get: function () {
  80654. return this._buttonRightStick;
  80655. },
  80656. /**
  80657. * Sets the value of the Right joystick
  80658. */
  80659. set: function (value) {
  80660. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  80661. },
  80662. enumerable: true,
  80663. configurable: true
  80664. });
  80665. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  80666. /**
  80667. * Gets the value of D-pad up
  80668. */
  80669. get: function () {
  80670. return this._dPadUp;
  80671. },
  80672. /**
  80673. * Sets the value of D-pad up
  80674. */
  80675. set: function (value) {
  80676. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  80677. },
  80678. enumerable: true,
  80679. configurable: true
  80680. });
  80681. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  80682. /**
  80683. * Gets the value of D-pad down
  80684. */
  80685. get: function () {
  80686. return this._dPadDown;
  80687. },
  80688. /**
  80689. * Sets the value of D-pad down
  80690. */
  80691. set: function (value) {
  80692. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  80693. },
  80694. enumerable: true,
  80695. configurable: true
  80696. });
  80697. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  80698. /**
  80699. * Gets the value of D-pad left
  80700. */
  80701. get: function () {
  80702. return this._dPadLeft;
  80703. },
  80704. /**
  80705. * Sets the value of D-pad left
  80706. */
  80707. set: function (value) {
  80708. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  80709. },
  80710. enumerable: true,
  80711. configurable: true
  80712. });
  80713. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  80714. /**
  80715. * Gets the value of D-pad right
  80716. */
  80717. get: function () {
  80718. return this._dPadRight;
  80719. },
  80720. /**
  80721. * Sets the value of D-pad right
  80722. */
  80723. set: function (value) {
  80724. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  80725. },
  80726. enumerable: true,
  80727. configurable: true
  80728. });
  80729. /**
  80730. * Force the gamepad to synchronize with device values
  80731. */
  80732. Xbox360Pad.prototype.update = function () {
  80733. _super.prototype.update.call(this);
  80734. if (this._isXboxOnePad) {
  80735. this.buttonA = this.browserGamepad.buttons[0].value;
  80736. this.buttonB = this.browserGamepad.buttons[1].value;
  80737. this.buttonX = this.browserGamepad.buttons[2].value;
  80738. this.buttonY = this.browserGamepad.buttons[3].value;
  80739. this.buttonLB = this.browserGamepad.buttons[4].value;
  80740. this.buttonRB = this.browserGamepad.buttons[5].value;
  80741. this.leftTrigger = this.browserGamepad.axes[2];
  80742. this.rightTrigger = this.browserGamepad.axes[5];
  80743. this.buttonBack = this.browserGamepad.buttons[9].value;
  80744. this.buttonStart = this.browserGamepad.buttons[8].value;
  80745. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  80746. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  80747. this.dPadUp = this.browserGamepad.buttons[11].value;
  80748. this.dPadDown = this.browserGamepad.buttons[12].value;
  80749. this.dPadLeft = this.browserGamepad.buttons[13].value;
  80750. this.dPadRight = this.browserGamepad.buttons[14].value;
  80751. }
  80752. else {
  80753. this.buttonA = this.browserGamepad.buttons[0].value;
  80754. this.buttonB = this.browserGamepad.buttons[1].value;
  80755. this.buttonX = this.browserGamepad.buttons[2].value;
  80756. this.buttonY = this.browserGamepad.buttons[3].value;
  80757. this.buttonLB = this.browserGamepad.buttons[4].value;
  80758. this.buttonRB = this.browserGamepad.buttons[5].value;
  80759. this.leftTrigger = this.browserGamepad.buttons[6].value;
  80760. this.rightTrigger = this.browserGamepad.buttons[7].value;
  80761. this.buttonBack = this.browserGamepad.buttons[8].value;
  80762. this.buttonStart = this.browserGamepad.buttons[9].value;
  80763. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  80764. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  80765. this.dPadUp = this.browserGamepad.buttons[12].value;
  80766. this.dPadDown = this.browserGamepad.buttons[13].value;
  80767. this.dPadLeft = this.browserGamepad.buttons[14].value;
  80768. this.dPadRight = this.browserGamepad.buttons[15].value;
  80769. }
  80770. };
  80771. /**
  80772. * Disposes the gamepad
  80773. */
  80774. Xbox360Pad.prototype.dispose = function () {
  80775. _super.prototype.dispose.call(this);
  80776. this.onButtonDownObservable.clear();
  80777. this.onButtonUpObservable.clear();
  80778. this.onPadDownObservable.clear();
  80779. this.onPadUpObservable.clear();
  80780. };
  80781. return Xbox360Pad;
  80782. }(BABYLON.Gamepad));
  80783. BABYLON.Xbox360Pad = Xbox360Pad;
  80784. })(BABYLON || (BABYLON = {}));
  80785. //# sourceMappingURL=babylon.xboxGamepad.js.map
  80786. var BABYLON;
  80787. (function (BABYLON) {
  80788. /**
  80789. * Defines the types of pose enabled controllers that are supported
  80790. */
  80791. var PoseEnabledControllerType;
  80792. (function (PoseEnabledControllerType) {
  80793. /**
  80794. * HTC Vive
  80795. */
  80796. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  80797. /**
  80798. * Oculus Rift
  80799. */
  80800. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  80801. /**
  80802. * Windows mixed reality
  80803. */
  80804. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  80805. /**
  80806. * Samsung gear VR
  80807. */
  80808. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  80809. /**
  80810. * Google Daydream
  80811. */
  80812. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  80813. /**
  80814. * Generic
  80815. */
  80816. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  80817. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  80818. /**
  80819. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  80820. */
  80821. var PoseEnabledControllerHelper = /** @class */ (function () {
  80822. function PoseEnabledControllerHelper() {
  80823. }
  80824. /**
  80825. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  80826. * @param vrGamepad the gamepad to initialized
  80827. * @returns a vr controller of the type the gamepad identified as
  80828. */
  80829. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  80830. // Oculus Touch
  80831. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  80832. return new BABYLON.OculusTouchController(vrGamepad);
  80833. }
  80834. // Windows Mixed Reality controllers
  80835. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  80836. return new BABYLON.WindowsMotionController(vrGamepad);
  80837. }
  80838. // HTC Vive
  80839. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  80840. return new BABYLON.ViveController(vrGamepad);
  80841. }
  80842. // Samsung/Oculus Gear VR or Oculus Go
  80843. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  80844. return new BABYLON.GearVRController(vrGamepad);
  80845. }
  80846. // Google Daydream
  80847. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  80848. return new BABYLON.DaydreamController(vrGamepad);
  80849. }
  80850. // Generic
  80851. else {
  80852. return new BABYLON.GenericController(vrGamepad);
  80853. }
  80854. };
  80855. return PoseEnabledControllerHelper;
  80856. }());
  80857. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  80858. /**
  80859. * Defines the PoseEnabledController object that contains state of a vr capable controller
  80860. */
  80861. var PoseEnabledController = /** @class */ (function (_super) {
  80862. __extends(PoseEnabledController, _super);
  80863. /**
  80864. * Creates a new PoseEnabledController from a gamepad
  80865. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  80866. */
  80867. function PoseEnabledController(browserGamepad) {
  80868. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  80869. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  80870. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  80871. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  80872. /**
  80873. * The device position in babylon space
  80874. */
  80875. _this.devicePosition = BABYLON.Vector3.Zero();
  80876. /**
  80877. * The device rotation in babylon space
  80878. */
  80879. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  80880. /**
  80881. * The scale factor of the device in babylon space
  80882. */
  80883. _this.deviceScaleFactor = 1;
  80884. // Used to convert 6dof controllers to 3dof
  80885. _this._trackPosition = true;
  80886. _this._maxRotationDistFromHeadset = Math.PI / 5;
  80887. _this._draggedRoomRotation = 0;
  80888. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  80889. /**
  80890. * Internal, matrix used to convert room space to babylon space
  80891. * @hidden
  80892. */
  80893. _this._deviceToWorld = BABYLON.Matrix.Identity();
  80894. /**
  80895. * Node to be used when casting a ray from the controller
  80896. * @hidden
  80897. */
  80898. _this._pointingPoseNode = null;
  80899. _this._workingMatrix = BABYLON.Matrix.Identity();
  80900. /**
  80901. * @hidden
  80902. */
  80903. _this._meshAttachedObservable = new BABYLON.Observable();
  80904. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  80905. _this.controllerType = PoseEnabledControllerType.GENERIC;
  80906. _this.position = BABYLON.Vector3.Zero();
  80907. _this.rotationQuaternion = new BABYLON.Quaternion();
  80908. _this._calculatedPosition = BABYLON.Vector3.Zero();
  80909. _this._calculatedRotation = new BABYLON.Quaternion();
  80910. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  80911. return _this;
  80912. }
  80913. /**
  80914. * @hidden
  80915. */
  80916. PoseEnabledController.prototype._disableTrackPosition = function (fixedPosition) {
  80917. if (this._trackPosition) {
  80918. this._calculatedPosition.copyFrom(fixedPosition);
  80919. this._trackPosition = false;
  80920. }
  80921. };
  80922. /**
  80923. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  80924. */
  80925. PoseEnabledController.prototype.update = function () {
  80926. _super.prototype.update.call(this);
  80927. this._updatePoseAndMesh();
  80928. };
  80929. /**
  80930. * Updates only the pose device and mesh without doing any button event checking
  80931. */
  80932. PoseEnabledController.prototype._updatePoseAndMesh = function () {
  80933. var pose = this.browserGamepad.pose;
  80934. this.updateFromDevice(pose);
  80935. if (!this._trackPosition && BABYLON.Engine.LastCreatedScene && BABYLON.Engine.LastCreatedScene.activeCamera && BABYLON.Engine.LastCreatedScene.activeCamera.devicePosition) {
  80936. var camera = BABYLON.Engine.LastCreatedScene.activeCamera;
  80937. camera._computeDevicePosition();
  80938. this._deviceToWorld.setTranslation(camera.devicePosition);
  80939. if (camera.deviceRotationQuaternion) {
  80940. var camera = camera;
  80941. camera._deviceRoomRotationQuaternion.toEulerAnglesToRef(BABYLON.Tmp.Vector3[0]);
  80942. // Find the radian distance away that the headset is from the controllers rotation
  80943. var distanceAway = Math.atan2(Math.sin(BABYLON.Tmp.Vector3[0].y - this._draggedRoomRotation), Math.cos(BABYLON.Tmp.Vector3[0].y - this._draggedRoomRotation));
  80944. if (Math.abs(distanceAway) > this._maxRotationDistFromHeadset) {
  80945. // Only rotate enouph to be within the _maxRotationDistFromHeadset
  80946. var rotationAmount = distanceAway - (distanceAway < 0 ? -this._maxRotationDistFromHeadset : this._maxRotationDistFromHeadset);
  80947. this._draggedRoomRotation += rotationAmount;
  80948. // Rotate controller around headset
  80949. var sin = Math.sin(-rotationAmount);
  80950. var cos = Math.cos(-rotationAmount);
  80951. this._calculatedPosition.x = this._calculatedPosition.x * cos - this._calculatedPosition.z * sin;
  80952. this._calculatedPosition.z = this._calculatedPosition.x * sin + this._calculatedPosition.z * cos;
  80953. }
  80954. }
  80955. }
  80956. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  80957. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  80958. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  80959. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  80960. if (this._mesh) {
  80961. this._mesh.position.copyFrom(this.devicePosition);
  80962. if (this._mesh.rotationQuaternion) {
  80963. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  80964. }
  80965. }
  80966. };
  80967. /**
  80968. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  80969. * @param poseData raw pose fromthe device
  80970. */
  80971. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  80972. if (poseData) {
  80973. this.rawPose = poseData;
  80974. if (poseData.position) {
  80975. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  80976. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  80977. this._deviceRoomPosition.z *= -1;
  80978. }
  80979. if (this._trackPosition) {
  80980. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  80981. }
  80982. this._calculatedPosition.addInPlace(this.position);
  80983. }
  80984. var pose = this.rawPose;
  80985. if (poseData.orientation && pose.orientation) {
  80986. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  80987. if (this._mesh) {
  80988. if (this._mesh.getScene().useRightHandedSystem) {
  80989. this._deviceRoomRotationQuaternion.z *= -1;
  80990. this._deviceRoomRotationQuaternion.w *= -1;
  80991. }
  80992. else {
  80993. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  80994. }
  80995. }
  80996. // if the camera is set, rotate to the camera's rotation
  80997. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  80998. }
  80999. }
  81000. };
  81001. /**
  81002. * Attaches a mesh to the controller
  81003. * @param mesh the mesh to be attached
  81004. */
  81005. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  81006. if (this._mesh) {
  81007. this._mesh.parent = null;
  81008. }
  81009. this._mesh = mesh;
  81010. if (this._poseControlledCamera) {
  81011. this._mesh.parent = this._poseControlledCamera;
  81012. }
  81013. if (!this._mesh.rotationQuaternion) {
  81014. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  81015. }
  81016. // Sync controller mesh and pointing pose node's state with controller, this is done to avoid a frame where position is 0,0,0 when attaching mesh
  81017. this._updatePoseAndMesh();
  81018. if (this._pointingPoseNode) {
  81019. var parents = [];
  81020. var obj = this._pointingPoseNode;
  81021. while (obj.parent) {
  81022. parents.push(obj.parent);
  81023. obj = obj.parent;
  81024. }
  81025. parents.reverse().forEach(function (p) { p.computeWorldMatrix(true); });
  81026. }
  81027. this._meshAttachedObservable.notifyObservers(mesh);
  81028. };
  81029. /**
  81030. * Attaches the controllers mesh to a camera
  81031. * @param camera the camera the mesh should be attached to
  81032. */
  81033. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  81034. this._poseControlledCamera = camera;
  81035. if (this._mesh) {
  81036. this._mesh.parent = this._poseControlledCamera;
  81037. }
  81038. };
  81039. /**
  81040. * Disposes of the controller
  81041. */
  81042. PoseEnabledController.prototype.dispose = function () {
  81043. if (this._mesh) {
  81044. this._mesh.dispose();
  81045. }
  81046. this._mesh = null;
  81047. _super.prototype.dispose.call(this);
  81048. };
  81049. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  81050. /**
  81051. * The mesh that is attached to the controller
  81052. */
  81053. get: function () {
  81054. return this._mesh;
  81055. },
  81056. enumerable: true,
  81057. configurable: true
  81058. });
  81059. /**
  81060. * Gets the ray of the controller in the direction the controller is pointing
  81061. * @param length the length the resulting ray should be
  81062. * @returns a ray in the direction the controller is pointing
  81063. */
  81064. PoseEnabledController.prototype.getForwardRay = function (length) {
  81065. if (length === void 0) { length = 100; }
  81066. if (!this.mesh) {
  81067. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  81068. }
  81069. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  81070. var origin = m.getTranslation();
  81071. var forward = new BABYLON.Vector3(0, 0, -1);
  81072. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  81073. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  81074. return new BABYLON.Ray(origin, direction, length);
  81075. };
  81076. /**
  81077. * Name of the child mesh that can be used to cast a ray from the controller
  81078. */
  81079. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  81080. return PoseEnabledController;
  81081. }(BABYLON.Gamepad));
  81082. BABYLON.PoseEnabledController = PoseEnabledController;
  81083. })(BABYLON || (BABYLON = {}));
  81084. //# sourceMappingURL=babylon.poseEnabledController.js.map
  81085. var BABYLON;
  81086. (function (BABYLON) {
  81087. /**
  81088. * Defines the WebVRController object that represents controllers tracked in 3D space
  81089. */
  81090. var WebVRController = /** @class */ (function (_super) {
  81091. __extends(WebVRController, _super);
  81092. /**
  81093. * Creates a new WebVRController from a gamepad
  81094. * @param vrGamepad the gamepad that the WebVRController should be created from
  81095. */
  81096. function WebVRController(vrGamepad) {
  81097. var _this = _super.call(this, vrGamepad) || this;
  81098. // Observables
  81099. /**
  81100. * Fired when the trigger state has changed
  81101. */
  81102. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  81103. /**
  81104. * Fired when the main button state has changed
  81105. */
  81106. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  81107. /**
  81108. * Fired when the secondary button state has changed
  81109. */
  81110. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  81111. /**
  81112. * Fired when the pad state has changed
  81113. */
  81114. _this.onPadStateChangedObservable = new BABYLON.Observable();
  81115. /**
  81116. * Fired when controllers stick values have changed
  81117. */
  81118. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  81119. /**
  81120. * X and Y axis corrisponding to the controllers joystick
  81121. */
  81122. _this.pad = { x: 0, y: 0 };
  81123. // avoid GC, store state in a tmp object
  81124. _this._changes = {
  81125. pressChanged: false,
  81126. touchChanged: false,
  81127. valueChanged: false,
  81128. changed: false
  81129. };
  81130. _this._buttons = new Array(vrGamepad.buttons.length);
  81131. _this.hand = vrGamepad.hand;
  81132. return _this;
  81133. }
  81134. /**
  81135. * Fired when a controller button's state has changed
  81136. * @param callback the callback containing the button that was modified
  81137. */
  81138. WebVRController.prototype.onButtonStateChange = function (callback) {
  81139. this._onButtonStateChange = callback;
  81140. };
  81141. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  81142. /**
  81143. * The default controller model for the controller
  81144. */
  81145. get: function () {
  81146. return this._defaultModel;
  81147. },
  81148. enumerable: true,
  81149. configurable: true
  81150. });
  81151. /**
  81152. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  81153. */
  81154. WebVRController.prototype.update = function () {
  81155. _super.prototype.update.call(this);
  81156. for (var index = 0; index < this._buttons.length; index++) {
  81157. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  81158. }
  81159. ;
  81160. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  81161. this.pad.x = this.leftStick.x;
  81162. this.pad.y = this.leftStick.y;
  81163. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  81164. }
  81165. };
  81166. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  81167. if (!newState) {
  81168. newState = {
  81169. pressed: false,
  81170. touched: false,
  81171. value: 0
  81172. };
  81173. }
  81174. if (!currentState) {
  81175. this._buttons[buttonIndex] = {
  81176. pressed: newState.pressed,
  81177. touched: newState.touched,
  81178. value: newState.value
  81179. };
  81180. return;
  81181. }
  81182. this._checkChanges(newState, currentState);
  81183. if (this._changes.changed) {
  81184. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  81185. this._handleButtonChange(buttonIndex, newState, this._changes);
  81186. }
  81187. this._buttons[buttonIndex].pressed = newState.pressed;
  81188. this._buttons[buttonIndex].touched = newState.touched;
  81189. // oculus triggers are never 0, thou not touched.
  81190. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  81191. };
  81192. WebVRController.prototype._checkChanges = function (newState, currentState) {
  81193. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  81194. this._changes.touchChanged = newState.touched !== currentState.touched;
  81195. this._changes.valueChanged = newState.value !== currentState.value;
  81196. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  81197. return this._changes;
  81198. };
  81199. /**
  81200. * Disposes of th webVRCOntroller
  81201. */
  81202. WebVRController.prototype.dispose = function () {
  81203. _super.prototype.dispose.call(this);
  81204. this.onTriggerStateChangedObservable.clear();
  81205. this.onMainButtonStateChangedObservable.clear();
  81206. this.onSecondaryButtonStateChangedObservable.clear();
  81207. this.onPadStateChangedObservable.clear();
  81208. this.onPadValuesChangedObservable.clear();
  81209. };
  81210. return WebVRController;
  81211. }(BABYLON.PoseEnabledController));
  81212. BABYLON.WebVRController = WebVRController;
  81213. })(BABYLON || (BABYLON = {}));
  81214. //# sourceMappingURL=babylon.webVRController.js.map
  81215. var BABYLON;
  81216. (function (BABYLON) {
  81217. /**
  81218. * Oculus Touch Controller
  81219. */
  81220. var OculusTouchController = /** @class */ (function (_super) {
  81221. __extends(OculusTouchController, _super);
  81222. /**
  81223. * Creates a new OculusTouchController from a gamepad
  81224. * @param vrGamepad the gamepad that the controller should be created from
  81225. */
  81226. function OculusTouchController(vrGamepad) {
  81227. var _this = _super.call(this, vrGamepad) || this;
  81228. /**
  81229. * Fired when the secondary trigger on this controller is modified
  81230. */
  81231. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  81232. /**
  81233. * Fired when the thumb rest on this controller is modified
  81234. */
  81235. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  81236. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  81237. return _this;
  81238. }
  81239. /**
  81240. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  81241. * @param scene scene in which to add meshes
  81242. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  81243. */
  81244. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  81245. var _this = this;
  81246. var meshName;
  81247. // Hand
  81248. if (this.hand === 'left') {
  81249. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  81250. }
  81251. else { // Right is the default if no hand is specified
  81252. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  81253. }
  81254. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  81255. /*
  81256. Parent Mesh name: oculus_touch_left
  81257. - body
  81258. - trigger
  81259. - thumbstick
  81260. - grip
  81261. - button_y
  81262. - button_x
  81263. - button_enter
  81264. */
  81265. _this._defaultModel = newMeshes[1];
  81266. _this.attachToMesh(_this._defaultModel);
  81267. if (meshLoaded) {
  81268. meshLoaded(_this._defaultModel);
  81269. }
  81270. });
  81271. };
  81272. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  81273. /**
  81274. * Fired when the A button on this controller is modified
  81275. */
  81276. get: function () {
  81277. if (this.hand === 'right') {
  81278. return this.onMainButtonStateChangedObservable;
  81279. }
  81280. else {
  81281. throw new Error('No A button on left hand');
  81282. }
  81283. },
  81284. enumerable: true,
  81285. configurable: true
  81286. });
  81287. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  81288. /**
  81289. * Fired when the B button on this controller is modified
  81290. */
  81291. get: function () {
  81292. if (this.hand === 'right') {
  81293. return this.onSecondaryButtonStateChangedObservable;
  81294. }
  81295. else {
  81296. throw new Error('No B button on left hand');
  81297. }
  81298. },
  81299. enumerable: true,
  81300. configurable: true
  81301. });
  81302. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  81303. /**
  81304. * Fired when the X button on this controller is modified
  81305. */
  81306. get: function () {
  81307. if (this.hand === 'left') {
  81308. return this.onMainButtonStateChangedObservable;
  81309. }
  81310. else {
  81311. throw new Error('No X button on right hand');
  81312. }
  81313. },
  81314. enumerable: true,
  81315. configurable: true
  81316. });
  81317. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  81318. /**
  81319. * Fired when the Y button on this controller is modified
  81320. */
  81321. get: function () {
  81322. if (this.hand === 'left') {
  81323. return this.onSecondaryButtonStateChangedObservable;
  81324. }
  81325. else {
  81326. throw new Error('No Y button on right hand');
  81327. }
  81328. },
  81329. enumerable: true,
  81330. configurable: true
  81331. });
  81332. /**
  81333. * Called once for each button that changed state since the last frame
  81334. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  81335. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  81336. * 2) secondary trigger (same)
  81337. * 3) A (right) X (left), touch, pressed = value
  81338. * 4) B / Y
  81339. * 5) thumb rest
  81340. * @param buttonIdx Which button index changed
  81341. * @param state New state of the button
  81342. * @param changes Which properties on the state changed since last frame
  81343. */
  81344. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  81345. var notifyObject = state; //{ state: state, changes: changes };
  81346. var triggerDirection = this.hand === 'right' ? -1 : 1;
  81347. switch (buttonIdx) {
  81348. case 0:
  81349. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  81350. return;
  81351. case 1: // index trigger
  81352. if (this._defaultModel) {
  81353. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  81354. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  81355. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  81356. }
  81357. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  81358. return;
  81359. case 2: // secondary trigger
  81360. if (this._defaultModel) {
  81361. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  81362. }
  81363. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  81364. return;
  81365. case 3:
  81366. if (this._defaultModel) {
  81367. if (notifyObject.pressed) {
  81368. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  81369. }
  81370. else {
  81371. (this._defaultModel.getChildren()[1]).position.y = 0;
  81372. }
  81373. }
  81374. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  81375. return;
  81376. case 4:
  81377. if (this._defaultModel) {
  81378. if (notifyObject.pressed) {
  81379. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  81380. }
  81381. else {
  81382. (this._defaultModel.getChildren()[2]).position.y = 0;
  81383. }
  81384. }
  81385. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  81386. return;
  81387. case 5:
  81388. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  81389. return;
  81390. }
  81391. };
  81392. /**
  81393. * Base Url for the controller model.
  81394. */
  81395. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  81396. /**
  81397. * File name for the left controller model.
  81398. */
  81399. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  81400. /**
  81401. * File name for the right controller model.
  81402. */
  81403. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  81404. return OculusTouchController;
  81405. }(BABYLON.WebVRController));
  81406. BABYLON.OculusTouchController = OculusTouchController;
  81407. })(BABYLON || (BABYLON = {}));
  81408. //# sourceMappingURL=babylon.oculusTouchController.js.map
  81409. var BABYLON;
  81410. (function (BABYLON) {
  81411. /**
  81412. * Vive Controller
  81413. */
  81414. var ViveController = /** @class */ (function (_super) {
  81415. __extends(ViveController, _super);
  81416. /**
  81417. * Creates a new ViveController from a gamepad
  81418. * @param vrGamepad the gamepad that the controller should be created from
  81419. */
  81420. function ViveController(vrGamepad) {
  81421. var _this = _super.call(this, vrGamepad) || this;
  81422. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  81423. _this._invertLeftStickY = true;
  81424. return _this;
  81425. }
  81426. /**
  81427. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  81428. * @param scene scene in which to add meshes
  81429. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  81430. */
  81431. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  81432. var _this = this;
  81433. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  81434. /*
  81435. Parent Mesh name: ViveWand
  81436. - body
  81437. - r_gripper
  81438. - l_gripper
  81439. - menu_button
  81440. - system_button
  81441. - trackpad
  81442. - trigger
  81443. - LED
  81444. */
  81445. _this._defaultModel = newMeshes[1];
  81446. _this.attachToMesh(_this._defaultModel);
  81447. if (meshLoaded) {
  81448. meshLoaded(_this._defaultModel);
  81449. }
  81450. });
  81451. };
  81452. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  81453. /**
  81454. * Fired when the left button on this controller is modified
  81455. */
  81456. get: function () {
  81457. return this.onMainButtonStateChangedObservable;
  81458. },
  81459. enumerable: true,
  81460. configurable: true
  81461. });
  81462. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  81463. /**
  81464. * Fired when the right button on this controller is modified
  81465. */
  81466. get: function () {
  81467. return this.onMainButtonStateChangedObservable;
  81468. },
  81469. enumerable: true,
  81470. configurable: true
  81471. });
  81472. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  81473. /**
  81474. * Fired when the menu button on this controller is modified
  81475. */
  81476. get: function () {
  81477. return this.onSecondaryButtonStateChangedObservable;
  81478. },
  81479. enumerable: true,
  81480. configurable: true
  81481. });
  81482. /**
  81483. * Called once for each button that changed state since the last frame
  81484. * Vive mapping:
  81485. * 0: touchpad
  81486. * 1: trigger
  81487. * 2: left AND right buttons
  81488. * 3: menu button
  81489. * @param buttonIdx Which button index changed
  81490. * @param state New state of the button
  81491. * @param changes Which properties on the state changed since last frame
  81492. */
  81493. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  81494. var notifyObject = state; //{ state: state, changes: changes };
  81495. switch (buttonIdx) {
  81496. case 0:
  81497. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  81498. return;
  81499. case 1: // index trigger
  81500. if (this._defaultModel) {
  81501. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  81502. }
  81503. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  81504. return;
  81505. case 2: // left AND right button
  81506. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  81507. return;
  81508. case 3:
  81509. if (this._defaultModel) {
  81510. if (notifyObject.pressed) {
  81511. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  81512. }
  81513. else {
  81514. (this._defaultModel.getChildren()[2]).position.y = 0;
  81515. }
  81516. }
  81517. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  81518. return;
  81519. }
  81520. };
  81521. /**
  81522. * Base Url for the controller model.
  81523. */
  81524. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  81525. /**
  81526. * File name for the controller model.
  81527. */
  81528. ViveController.MODEL_FILENAME = 'wand.babylon';
  81529. return ViveController;
  81530. }(BABYLON.WebVRController));
  81531. BABYLON.ViveController = ViveController;
  81532. })(BABYLON || (BABYLON = {}));
  81533. //# sourceMappingURL=babylon.viveController.js.map
  81534. var BABYLON;
  81535. (function (BABYLON) {
  81536. /**
  81537. * Generic Controller
  81538. */
  81539. var GenericController = /** @class */ (function (_super) {
  81540. __extends(GenericController, _super);
  81541. /**
  81542. * Creates a new GenericController from a gamepad
  81543. * @param vrGamepad the gamepad that the controller should be created from
  81544. */
  81545. function GenericController(vrGamepad) {
  81546. return _super.call(this, vrGamepad) || this;
  81547. }
  81548. /**
  81549. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  81550. * @param scene scene in which to add meshes
  81551. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  81552. */
  81553. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  81554. var _this = this;
  81555. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  81556. _this._defaultModel = newMeshes[1];
  81557. _this.attachToMesh(_this._defaultModel);
  81558. if (meshLoaded) {
  81559. meshLoaded(_this._defaultModel);
  81560. }
  81561. });
  81562. };
  81563. /**
  81564. * Called once for each button that changed state since the last frame
  81565. * @param buttonIdx Which button index changed
  81566. * @param state New state of the button
  81567. * @param changes Which properties on the state changed since last frame
  81568. */
  81569. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  81570. console.log("Button id: " + buttonIdx + "state: ");
  81571. console.dir(state);
  81572. };
  81573. /**
  81574. * Base Url for the controller model.
  81575. */
  81576. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  81577. /**
  81578. * File name for the controller model.
  81579. */
  81580. GenericController.MODEL_FILENAME = 'generic.babylon';
  81581. return GenericController;
  81582. }(BABYLON.WebVRController));
  81583. BABYLON.GenericController = GenericController;
  81584. })(BABYLON || (BABYLON = {}));
  81585. //# sourceMappingURL=babylon.genericController.js.map
  81586. var BABYLON;
  81587. (function (BABYLON) {
  81588. /**
  81589. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  81590. */
  81591. var LoadedMeshInfo = /** @class */ (function () {
  81592. function LoadedMeshInfo() {
  81593. /**
  81594. * Map of the button meshes contained in the controller
  81595. */
  81596. this.buttonMeshes = {};
  81597. /**
  81598. * Map of the axis meshes contained in the controller
  81599. */
  81600. this.axisMeshes = {};
  81601. }
  81602. return LoadedMeshInfo;
  81603. }());
  81604. /**
  81605. * Defines the WindowsMotionController object that the state of the windows motion controller
  81606. */
  81607. var WindowsMotionController = /** @class */ (function (_super) {
  81608. __extends(WindowsMotionController, _super);
  81609. /**
  81610. * Creates a new WindowsMotionController from a gamepad
  81611. * @param vrGamepad the gamepad that the controller should be created from
  81612. */
  81613. function WindowsMotionController(vrGamepad) {
  81614. var _this = _super.call(this, vrGamepad) || this;
  81615. _this._mapping = {
  81616. // Semantic button names
  81617. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  81618. // A mapping of the button name to glTF model node name
  81619. // that should be transformed by button value.
  81620. buttonMeshNames: {
  81621. 'trigger': 'SELECT',
  81622. 'menu': 'MENU',
  81623. 'grip': 'GRASP',
  81624. 'thumbstick': 'THUMBSTICK_PRESS',
  81625. 'trackpad': 'TOUCHPAD_PRESS'
  81626. },
  81627. // This mapping is used to translate from the Motion Controller to Babylon semantics
  81628. buttonObservableNames: {
  81629. 'trigger': 'onTriggerStateChangedObservable',
  81630. 'menu': 'onSecondaryButtonStateChangedObservable',
  81631. 'grip': 'onMainButtonStateChangedObservable',
  81632. 'thumbstick': 'onPadStateChangedObservable',
  81633. 'trackpad': 'onTrackpadChangedObservable'
  81634. },
  81635. // A mapping of the axis name to glTF model node name
  81636. // that should be transformed by axis value.
  81637. // This array mirrors the browserGamepad.axes array, such that
  81638. // the mesh corresponding to axis 0 is in this array index 0.
  81639. axisMeshNames: [
  81640. 'THUMBSTICK_X',
  81641. 'THUMBSTICK_Y',
  81642. 'TOUCHPAD_TOUCH_X',
  81643. 'TOUCHPAD_TOUCH_Y'
  81644. ],
  81645. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  81646. };
  81647. /**
  81648. * Fired when the trackpad on this controller is clicked
  81649. */
  81650. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  81651. /**
  81652. * Fired when the trackpad on this controller is modified
  81653. */
  81654. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  81655. /**
  81656. * The current x and y values of this controller's trackpad
  81657. */
  81658. _this.trackpad = { x: 0, y: 0 };
  81659. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  81660. _this._loadedMeshInfo = null;
  81661. return _this;
  81662. }
  81663. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  81664. /**
  81665. * Fired when the trigger on this controller is modified
  81666. */
  81667. get: function () {
  81668. return this.onTriggerStateChangedObservable;
  81669. },
  81670. enumerable: true,
  81671. configurable: true
  81672. });
  81673. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  81674. /**
  81675. * Fired when the menu button on this controller is modified
  81676. */
  81677. get: function () {
  81678. return this.onSecondaryButtonStateChangedObservable;
  81679. },
  81680. enumerable: true,
  81681. configurable: true
  81682. });
  81683. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  81684. /**
  81685. * Fired when the grip button on this controller is modified
  81686. */
  81687. get: function () {
  81688. return this.onMainButtonStateChangedObservable;
  81689. },
  81690. enumerable: true,
  81691. configurable: true
  81692. });
  81693. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  81694. /**
  81695. * Fired when the thumbstick button on this controller is modified
  81696. */
  81697. get: function () {
  81698. return this.onPadStateChangedObservable;
  81699. },
  81700. enumerable: true,
  81701. configurable: true
  81702. });
  81703. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  81704. /**
  81705. * Fired when the touchpad button on this controller is modified
  81706. */
  81707. get: function () {
  81708. return this.onTrackpadChangedObservable;
  81709. },
  81710. enumerable: true,
  81711. configurable: true
  81712. });
  81713. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  81714. /**
  81715. * Fired when the touchpad values on this controller are modified
  81716. */
  81717. get: function () {
  81718. return this.onTrackpadValuesChangedObservable;
  81719. },
  81720. enumerable: true,
  81721. configurable: true
  81722. });
  81723. WindowsMotionController.prototype._updateTrackpad = function () {
  81724. if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
  81725. this.trackpad.x = this.browserGamepad["axes"][2];
  81726. this.trackpad.y = this.browserGamepad["axes"][3];
  81727. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  81728. }
  81729. };
  81730. /**
  81731. * Called once per frame by the engine.
  81732. */
  81733. WindowsMotionController.prototype.update = function () {
  81734. _super.prototype.update.call(this);
  81735. if (this.browserGamepad.axes) {
  81736. this._updateTrackpad();
  81737. // Only need to animate axes if there is a loaded mesh
  81738. if (this._loadedMeshInfo) {
  81739. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  81740. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  81741. }
  81742. }
  81743. }
  81744. };
  81745. /**
  81746. * Called once for each button that changed state since the last frame
  81747. * @param buttonIdx Which button index changed
  81748. * @param state New state of the button
  81749. * @param changes Which properties on the state changed since last frame
  81750. */
  81751. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  81752. var buttonName = this._mapping.buttons[buttonIdx];
  81753. if (!buttonName) {
  81754. return;
  81755. }
  81756. // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
  81757. this._updateTrackpad();
  81758. // Only emit events for buttons that we know how to map from index to name
  81759. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  81760. if (observable) {
  81761. observable.notifyObservers(state);
  81762. }
  81763. this._lerpButtonTransform(buttonName, state.value);
  81764. };
  81765. /**
  81766. * Moves the buttons on the controller mesh based on their current state
  81767. * @param buttonName the name of the button to move
  81768. * @param buttonValue the value of the button which determines the buttons new position
  81769. */
  81770. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  81771. // If there is no loaded mesh, there is nothing to transform.
  81772. if (!this._loadedMeshInfo) {
  81773. return;
  81774. }
  81775. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  81776. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  81777. return;
  81778. }
  81779. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  81780. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  81781. };
  81782. /**
  81783. * Moves the axis on the controller mesh based on its current state
  81784. * @param axis the index of the axis
  81785. * @param axisValue the value of the axis which determines the meshes new position
  81786. * @hidden
  81787. */
  81788. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  81789. if (!this._loadedMeshInfo) {
  81790. return;
  81791. }
  81792. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  81793. if (!meshInfo) {
  81794. return;
  81795. }
  81796. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  81797. return;
  81798. }
  81799. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  81800. var lerpValue = axisValue * 0.5 + 0.5;
  81801. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  81802. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  81803. };
  81804. /**
  81805. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  81806. * @param scene scene in which to add meshes
  81807. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  81808. */
  81809. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  81810. var _this = this;
  81811. if (forceDefault === void 0) { forceDefault = false; }
  81812. var path;
  81813. var filename;
  81814. // Checking if GLB loader is present
  81815. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  81816. // Determine the device specific folder based on the ID suffix
  81817. var device = 'default';
  81818. if (this.id && !forceDefault) {
  81819. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  81820. device = ((match && match[0]) || device);
  81821. }
  81822. // Hand
  81823. if (this.hand === 'left') {
  81824. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  81825. }
  81826. else { // Right is the default if no hand is specified
  81827. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  81828. }
  81829. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  81830. }
  81831. else {
  81832. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  81833. path = BABYLON.GenericController.MODEL_BASE_URL;
  81834. filename = BABYLON.GenericController.MODEL_FILENAME;
  81835. }
  81836. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  81837. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  81838. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  81839. if (!_this._loadedMeshInfo) {
  81840. return;
  81841. }
  81842. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  81843. _this.attachToMesh(_this._defaultModel);
  81844. if (meshLoaded) {
  81845. meshLoaded(_this._defaultModel);
  81846. }
  81847. }, null, function (scene, message) {
  81848. BABYLON.Tools.Log(message);
  81849. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  81850. if (!forceDefault) {
  81851. _this.initControllerMesh(scene, meshLoaded, true);
  81852. }
  81853. });
  81854. };
  81855. /**
  81856. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  81857. * can be transformed by button presses and axes values, based on this._mapping.
  81858. *
  81859. * @param scene scene in which the meshes exist
  81860. * @param meshes list of meshes that make up the controller model to process
  81861. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  81862. */
  81863. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  81864. var loadedMeshInfo = null;
  81865. // Create a new mesh to contain the glTF hierarchy
  81866. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  81867. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  81868. var childMesh = null;
  81869. for (var i = 0; i < meshes.length; i++) {
  81870. var mesh = meshes[i];
  81871. if (!mesh.parent) {
  81872. // Exclude controller meshes from picking results
  81873. mesh.isPickable = false;
  81874. // Handle root node, attach to the new parentMesh
  81875. childMesh = mesh;
  81876. break;
  81877. }
  81878. }
  81879. if (childMesh) {
  81880. childMesh.setParent(parentMesh);
  81881. // Create our mesh info. Note that this method will always return non-null.
  81882. loadedMeshInfo = this.createMeshInfo(parentMesh);
  81883. }
  81884. else {
  81885. BABYLON.Tools.Warn('Could not find root node in model file.');
  81886. }
  81887. return loadedMeshInfo;
  81888. };
  81889. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  81890. var loadedMeshInfo = new LoadedMeshInfo();
  81891. var i;
  81892. loadedMeshInfo.rootNode = rootNode;
  81893. // Reset the caches
  81894. loadedMeshInfo.buttonMeshes = {};
  81895. loadedMeshInfo.axisMeshes = {};
  81896. // Button Meshes
  81897. for (i = 0; i < this._mapping.buttons.length; i++) {
  81898. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  81899. if (!buttonMeshName) {
  81900. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  81901. continue;
  81902. }
  81903. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  81904. if (!buttonMesh) {
  81905. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  81906. continue;
  81907. }
  81908. var buttonMeshInfo = {
  81909. index: i,
  81910. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  81911. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  81912. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  81913. };
  81914. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  81915. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  81916. }
  81917. else {
  81918. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  81919. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  81920. '(VALUE: ' + !!buttonMeshInfo.value +
  81921. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  81922. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  81923. ')');
  81924. }
  81925. }
  81926. // Axis Meshes
  81927. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  81928. var axisMeshName = this._mapping.axisMeshNames[i];
  81929. if (!axisMeshName) {
  81930. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  81931. continue;
  81932. }
  81933. var axisMesh = getChildByName(rootNode, axisMeshName);
  81934. if (!axisMesh) {
  81935. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  81936. continue;
  81937. }
  81938. var axisMeshInfo = {
  81939. index: i,
  81940. value: getImmediateChildByName(axisMesh, 'VALUE'),
  81941. min: getImmediateChildByName(axisMesh, 'MIN'),
  81942. max: getImmediateChildByName(axisMesh, 'MAX')
  81943. };
  81944. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  81945. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  81946. }
  81947. else {
  81948. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  81949. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  81950. '(VALUE: ' + !!axisMeshInfo.value +
  81951. ', MIN: ' + !!axisMeshInfo.min +
  81952. ', MAX:' + !!axisMeshInfo.max +
  81953. ')');
  81954. }
  81955. }
  81956. // Pointing Ray
  81957. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  81958. if (!loadedMeshInfo.pointingPoseNode) {
  81959. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  81960. }
  81961. else {
  81962. this._pointingPoseNode = loadedMeshInfo.pointingPoseNode;
  81963. }
  81964. return loadedMeshInfo;
  81965. // Look through all children recursively. This will return null if no mesh exists with the given name.
  81966. function getChildByName(node, name) {
  81967. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  81968. }
  81969. // Look through only immediate children. This will return null if no mesh exists with the given name.
  81970. function getImmediateChildByName(node, name) {
  81971. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  81972. }
  81973. };
  81974. /**
  81975. * Gets the ray of the controller in the direction the controller is pointing
  81976. * @param length the length the resulting ray should be
  81977. * @returns a ray in the direction the controller is pointing
  81978. */
  81979. WindowsMotionController.prototype.getForwardRay = function (length) {
  81980. if (length === void 0) { length = 100; }
  81981. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  81982. return _super.prototype.getForwardRay.call(this, length);
  81983. }
  81984. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  81985. var origin = m.getTranslation();
  81986. var forward = new BABYLON.Vector3(0, 0, -1);
  81987. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  81988. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  81989. return new BABYLON.Ray(origin, direction, length);
  81990. };
  81991. /**
  81992. * Disposes of the controller
  81993. */
  81994. WindowsMotionController.prototype.dispose = function () {
  81995. _super.prototype.dispose.call(this);
  81996. this.onTrackpadChangedObservable.clear();
  81997. };
  81998. /**
  81999. * The base url used to load the left and right controller models
  82000. */
  82001. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  82002. /**
  82003. * The name of the left controller model file
  82004. */
  82005. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  82006. /**
  82007. * The name of the right controller model file
  82008. */
  82009. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  82010. /**
  82011. * The controller name prefix for this controller type
  82012. */
  82013. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  82014. /**
  82015. * The controller id pattern for this controller type
  82016. */
  82017. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  82018. return WindowsMotionController;
  82019. }(BABYLON.WebVRController));
  82020. BABYLON.WindowsMotionController = WindowsMotionController;
  82021. })(BABYLON || (BABYLON = {}));
  82022. //# sourceMappingURL=babylon.windowsMotionController.js.map
  82023. var BABYLON;
  82024. (function (BABYLON) {
  82025. /**
  82026. * Gear VR Controller
  82027. */
  82028. var GearVRController = /** @class */ (function (_super) {
  82029. __extends(GearVRController, _super);
  82030. /**
  82031. * Creates a new GearVRController from a gamepad
  82032. * @param vrGamepad the gamepad that the controller should be created from
  82033. */
  82034. function GearVRController(vrGamepad) {
  82035. var _this = _super.call(this, vrGamepad) || this;
  82036. _this._buttonIndexToObservableNameMap = [
  82037. 'onTrackpadChangedObservable',
  82038. 'onTriggerStateChangedObservable' // Trigger
  82039. ];
  82040. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  82041. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  82042. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.25);
  82043. _this._disableTrackPosition(_this._calculatedPosition);
  82044. return _this;
  82045. }
  82046. /**
  82047. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  82048. * @param scene scene in which to add meshes
  82049. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  82050. */
  82051. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  82052. var _this = this;
  82053. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  82054. // Offset the controller so it will rotate around the users wrist
  82055. var mesh = new BABYLON.Mesh("", scene);
  82056. newMeshes[1].parent = mesh;
  82057. newMeshes[1].position.z = -0.15;
  82058. _this._defaultModel = mesh;
  82059. _this.attachToMesh(_this._defaultModel);
  82060. if (meshLoaded) {
  82061. meshLoaded(_this._defaultModel);
  82062. }
  82063. });
  82064. };
  82065. /**
  82066. * Called once for each button that changed state since the last frame
  82067. * @param buttonIdx Which button index changed
  82068. * @param state New state of the button
  82069. * @param changes Which properties on the state changed since last frame
  82070. */
  82071. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  82072. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  82073. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  82074. // Only emit events for buttons that we know how to map from index to observable
  82075. var observable = this[observableName];
  82076. if (observable) {
  82077. observable.notifyObservers(state);
  82078. }
  82079. }
  82080. };
  82081. /**
  82082. * Base Url for the controller model.
  82083. */
  82084. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  82085. /**
  82086. * File name for the controller model.
  82087. */
  82088. GearVRController.MODEL_FILENAME = 'generic.babylon';
  82089. /**
  82090. * Gamepad Id prefix used to identify this controller.
  82091. */
  82092. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  82093. return GearVRController;
  82094. }(BABYLON.WebVRController));
  82095. BABYLON.GearVRController = GearVRController;
  82096. })(BABYLON || (BABYLON = {}));
  82097. //# sourceMappingURL=babylon.gearVRController.js.map
  82098. var BABYLON;
  82099. (function (BABYLON) {
  82100. /**
  82101. * Google Daydream controller
  82102. */
  82103. var DaydreamController = /** @class */ (function (_super) {
  82104. __extends(DaydreamController, _super);
  82105. /**
  82106. * Creates a new DaydreamController from a gamepad
  82107. * @param vrGamepad the gamepad that the controller should be created from
  82108. */
  82109. function DaydreamController(vrGamepad) {
  82110. var _this = _super.call(this, vrGamepad) || this;
  82111. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  82112. return _this;
  82113. }
  82114. /**
  82115. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  82116. * @param scene scene in which to add meshes
  82117. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  82118. */
  82119. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  82120. var _this = this;
  82121. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  82122. _this._defaultModel = newMeshes[1];
  82123. _this.attachToMesh(_this._defaultModel);
  82124. if (meshLoaded) {
  82125. meshLoaded(_this._defaultModel);
  82126. }
  82127. });
  82128. };
  82129. /**
  82130. * Called once for each button that changed state since the last frame
  82131. * @param buttonIdx Which button index changed
  82132. * @param state New state of the button
  82133. * @param changes Which properties on the state changed since last frame
  82134. */
  82135. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  82136. // Daydream controller only has 1 GamepadButton (on the trackpad).
  82137. if (buttonIdx === 0) {
  82138. var observable = this.onTriggerStateChangedObservable;
  82139. if (observable) {
  82140. observable.notifyObservers(state);
  82141. }
  82142. }
  82143. else {
  82144. // If the app or home buttons are ever made available
  82145. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  82146. }
  82147. };
  82148. /**
  82149. * Base Url for the controller model.
  82150. */
  82151. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  82152. /**
  82153. * File name for the controller model.
  82154. */
  82155. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  82156. /**
  82157. * Gamepad Id prefix used to identify Daydream Controller.
  82158. */
  82159. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  82160. return DaydreamController;
  82161. }(BABYLON.WebVRController));
  82162. BABYLON.DaydreamController = DaydreamController;
  82163. })(BABYLON || (BABYLON = {}));
  82164. //# sourceMappingURL=babylon.daydreamController.js.map
  82165. var BABYLON;
  82166. (function (BABYLON) {
  82167. Object.defineProperty(BABYLON.Scene.prototype, "gamepadManager", {
  82168. get: function () {
  82169. if (!this._gamepadManager) {
  82170. this._gamepadManager = new BABYLON.GamepadManager(this);
  82171. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_GAMEPAD);
  82172. if (!component) {
  82173. component = new GamepadSystemSceneComponent(this);
  82174. this._addComponent(component);
  82175. }
  82176. }
  82177. return this._gamepadManager;
  82178. },
  82179. enumerable: true,
  82180. configurable: true
  82181. });
  82182. /**
  82183. * Adds a gamepad to the free camera inputs manager
  82184. */
  82185. BABYLON.FreeCameraInputsManager.prototype.addGamepad = function () {
  82186. this.add(new BABYLON.FreeCameraGamepadInput());
  82187. return this;
  82188. };
  82189. /**
  82190. * Adds a gamepad to the arc rotate camera inputs manager
  82191. */
  82192. BABYLON.ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  82193. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  82194. return this;
  82195. };
  82196. /**
  82197. * Defines the gamepad scene component responsible to manage gamepads in a given scene
  82198. */
  82199. var GamepadSystemSceneComponent = /** @class */ (function () {
  82200. /**
  82201. * Creates a new instance of the component for the given scene
  82202. * @param scene Defines the scene to register the component in
  82203. */
  82204. function GamepadSystemSceneComponent(scene) {
  82205. /**
  82206. * The component name helpfull to identify the component in the list of scene components.
  82207. */
  82208. this.name = BABYLON.SceneComponentConstants.NAME_GAMEPAD;
  82209. this.scene = scene;
  82210. }
  82211. /**
  82212. * Registers the component in a given scene
  82213. */
  82214. GamepadSystemSceneComponent.prototype.register = function () {
  82215. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD, this, this._beforeCameraUpdate);
  82216. };
  82217. /**
  82218. * Rebuilds the elements related to this component in case of
  82219. * context lost for instance.
  82220. */
  82221. GamepadSystemSceneComponent.prototype.rebuild = function () {
  82222. // Nothing to do for gamepads
  82223. };
  82224. /**
  82225. * Disposes the component and the associated ressources
  82226. */
  82227. GamepadSystemSceneComponent.prototype.dispose = function () {
  82228. var gamepadManager = this.scene._gamepadManager;
  82229. if (gamepadManager) {
  82230. gamepadManager.dispose();
  82231. this.scene._gamepadManager = null;
  82232. }
  82233. };
  82234. GamepadSystemSceneComponent.prototype._beforeCameraUpdate = function () {
  82235. var gamepadManager = this.scene._gamepadManager;
  82236. if (gamepadManager && gamepadManager._isMonitoring) {
  82237. gamepadManager._checkGamepadsStatus();
  82238. }
  82239. };
  82240. return GamepadSystemSceneComponent;
  82241. }());
  82242. BABYLON.GamepadSystemSceneComponent = GamepadSystemSceneComponent;
  82243. })(BABYLON || (BABYLON = {}));
  82244. //# sourceMappingURL=babylon.gamepadSceneComponent.js.map
  82245. var BABYLON;
  82246. (function (BABYLON) {
  82247. BABYLON.Node.AddNodeConstructor("FollowCamera", function (name, scene) {
  82248. return function () { return new FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  82249. });
  82250. BABYLON.Node.AddNodeConstructor("ArcFollowCamera", function (name, scene) {
  82251. return function () { return new ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  82252. });
  82253. /**
  82254. * A follow camera takes a mesh as a target and follows it as it moves. Both a free camera version followCamera and
  82255. * an arc rotate version arcFollowCamera are available.
  82256. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  82257. */
  82258. var FollowCamera = /** @class */ (function (_super) {
  82259. __extends(FollowCamera, _super);
  82260. /**
  82261. * Instantiates the follow camera.
  82262. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  82263. * @param name Define the name of the camera in the scene
  82264. * @param position Define the position of the camera
  82265. * @param scene Define the scene the camera belong to
  82266. * @param lockedTarget Define the target of the camera
  82267. */
  82268. function FollowCamera(name, position, scene, lockedTarget) {
  82269. if (lockedTarget === void 0) { lockedTarget = null; }
  82270. var _this = _super.call(this, name, position, scene) || this;
  82271. /**
  82272. * Distance the follow camera should follow an object at
  82273. */
  82274. _this.radius = 12;
  82275. /**
  82276. * Define a rotation offset between the camera and the object it follows
  82277. */
  82278. _this.rotationOffset = 0;
  82279. /**
  82280. * Define a height offset between the camera and the object it follows.
  82281. * It can help following an object from the top (like a car chaing a plane)
  82282. */
  82283. _this.heightOffset = 4;
  82284. /**
  82285. * Define how fast the camera can accelerate to follow it s target.
  82286. */
  82287. _this.cameraAcceleration = 0.05;
  82288. /**
  82289. * Define the speed limit of the camera following an object.
  82290. */
  82291. _this.maxCameraSpeed = 20;
  82292. _this.lockedTarget = lockedTarget;
  82293. return _this;
  82294. }
  82295. FollowCamera.prototype._follow = function (cameraTarget) {
  82296. if (!cameraTarget)
  82297. return;
  82298. var yRotation;
  82299. if (cameraTarget.rotationQuaternion) {
  82300. var rotMatrix = new BABYLON.Matrix();
  82301. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  82302. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  82303. }
  82304. else {
  82305. yRotation = cameraTarget.rotation.y;
  82306. }
  82307. var radians = BABYLON.Tools.ToRadians(this.rotationOffset) + yRotation;
  82308. var targetPosition = cameraTarget.getAbsolutePosition();
  82309. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  82310. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  82311. var dx = targetX - this.position.x;
  82312. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  82313. var dz = (targetZ) - this.position.z;
  82314. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  82315. var vy = dy * this.cameraAcceleration;
  82316. var vz = dz * this.cameraAcceleration * 2;
  82317. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  82318. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  82319. }
  82320. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  82321. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  82322. }
  82323. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  82324. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  82325. }
  82326. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  82327. this.setTarget(targetPosition);
  82328. };
  82329. /** @hidden */
  82330. FollowCamera.prototype._checkInputs = function () {
  82331. _super.prototype._checkInputs.call(this);
  82332. if (this.lockedTarget) {
  82333. this._follow(this.lockedTarget);
  82334. }
  82335. };
  82336. /**
  82337. * Gets the camera class name.
  82338. * @returns the class name
  82339. */
  82340. FollowCamera.prototype.getClassName = function () {
  82341. return "FollowCamera";
  82342. };
  82343. __decorate([
  82344. BABYLON.serialize()
  82345. ], FollowCamera.prototype, "radius", void 0);
  82346. __decorate([
  82347. BABYLON.serialize()
  82348. ], FollowCamera.prototype, "rotationOffset", void 0);
  82349. __decorate([
  82350. BABYLON.serialize()
  82351. ], FollowCamera.prototype, "heightOffset", void 0);
  82352. __decorate([
  82353. BABYLON.serialize()
  82354. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  82355. __decorate([
  82356. BABYLON.serialize()
  82357. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  82358. __decorate([
  82359. BABYLON.serializeAsMeshReference("lockedTargetId")
  82360. ], FollowCamera.prototype, "lockedTarget", void 0);
  82361. return FollowCamera;
  82362. }(BABYLON.TargetCamera));
  82363. BABYLON.FollowCamera = FollowCamera;
  82364. /**
  82365. * Arc Rotate version of the follow camera.
  82366. * It still follows a Defined mesh but in an Arc Rotate Camera fashion.
  82367. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  82368. */
  82369. var ArcFollowCamera = /** @class */ (function (_super) {
  82370. __extends(ArcFollowCamera, _super);
  82371. /**
  82372. * Instantiates a new ArcFollowCamera
  82373. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  82374. * @param name Define the name of the camera
  82375. * @param alpha Define the rotation angle of the camera around the logitudinal axis
  82376. * @param beta Define the rotation angle of the camera around the elevation axis
  82377. * @param radius Define the radius of the camera from its target point
  82378. * @param target Define the target of the camera
  82379. * @param scene Define the scene the camera belongs to
  82380. */
  82381. function ArcFollowCamera(name,
  82382. /** The longitudinal angle of the camera */
  82383. alpha,
  82384. /** The latitudinal angle of the camera */
  82385. beta,
  82386. /** The radius of the camera from its target */
  82387. radius,
  82388. /** Define the camera target (the messh it should follow) */
  82389. target, scene) {
  82390. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  82391. _this.alpha = alpha;
  82392. _this.beta = beta;
  82393. _this.radius = radius;
  82394. _this.target = target;
  82395. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  82396. _this._follow();
  82397. return _this;
  82398. }
  82399. ArcFollowCamera.prototype._follow = function () {
  82400. if (!this.target) {
  82401. return;
  82402. }
  82403. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  82404. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  82405. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  82406. var targetPosition = this.target.getAbsolutePosition();
  82407. this.position = targetPosition.add(this._cartesianCoordinates);
  82408. this.setTarget(targetPosition);
  82409. };
  82410. /** @hidden */
  82411. ArcFollowCamera.prototype._checkInputs = function () {
  82412. _super.prototype._checkInputs.call(this);
  82413. this._follow();
  82414. };
  82415. /**
  82416. * Returns the class name of the object.
  82417. * It is mostly used internally for serialization purposes.
  82418. */
  82419. ArcFollowCamera.prototype.getClassName = function () {
  82420. return "ArcFollowCamera";
  82421. };
  82422. return ArcFollowCamera;
  82423. }(BABYLON.TargetCamera));
  82424. BABYLON.ArcFollowCamera = ArcFollowCamera;
  82425. })(BABYLON || (BABYLON = {}));
  82426. //# sourceMappingURL=babylon.followCamera.js.map
  82427. var BABYLON;
  82428. (function (BABYLON) {
  82429. /**
  82430. * The Universal Camera is the one to choose for first person shooter type games, and works with all the keyboard, mouse, touch and gamepads. This replaces the earlier Free Camera,
  82431. * which still works and will still be found in many Playgrounds.
  82432. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  82433. */
  82434. var UniversalCamera = /** @class */ (function (_super) {
  82435. __extends(UniversalCamera, _super);
  82436. /**
  82437. * The Universal Camera is the one to choose for first person shooter type games, and works with all the keyboard, mouse, touch and gamepads. This replaces the earlier Free Camera,
  82438. * which still works and will still be found in many Playgrounds.
  82439. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  82440. * @param name Define the name of the camera in the scene
  82441. * @param position Define the start position of the camera in the scene
  82442. * @param scene Define the scene the camera belongs to
  82443. */
  82444. function UniversalCamera(name, position, scene) {
  82445. var _this = _super.call(this, name, position, scene) || this;
  82446. _this.inputs.addGamepad();
  82447. return _this;
  82448. }
  82449. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  82450. /**
  82451. * Defines the gamepad rotation sensiblity.
  82452. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  82453. */
  82454. get: function () {
  82455. var gamepad = this.inputs.attached["gamepad"];
  82456. if (gamepad)
  82457. return gamepad.gamepadAngularSensibility;
  82458. return 0;
  82459. },
  82460. set: function (value) {
  82461. var gamepad = this.inputs.attached["gamepad"];
  82462. if (gamepad)
  82463. gamepad.gamepadAngularSensibility = value;
  82464. },
  82465. enumerable: true,
  82466. configurable: true
  82467. });
  82468. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  82469. /**
  82470. * Defines the gamepad move sensiblity.
  82471. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  82472. */
  82473. get: function () {
  82474. var gamepad = this.inputs.attached["gamepad"];
  82475. if (gamepad)
  82476. return gamepad.gamepadMoveSensibility;
  82477. return 0;
  82478. },
  82479. set: function (value) {
  82480. var gamepad = this.inputs.attached["gamepad"];
  82481. if (gamepad)
  82482. gamepad.gamepadMoveSensibility = value;
  82483. },
  82484. enumerable: true,
  82485. configurable: true
  82486. });
  82487. /**
  82488. * Gets the current object class name.
  82489. * @return the class name
  82490. */
  82491. UniversalCamera.prototype.getClassName = function () {
  82492. return "UniversalCamera";
  82493. };
  82494. return UniversalCamera;
  82495. }(BABYLON.TouchCamera));
  82496. BABYLON.UniversalCamera = UniversalCamera;
  82497. })(BABYLON || (BABYLON = {}));
  82498. //# sourceMappingURL=babylon.universalCamera.js.map
  82499. var BABYLON;
  82500. (function (BABYLON) {
  82501. BABYLON.Node.AddNodeConstructor("GamepadCamera", function (name, scene) {
  82502. return function () { return new GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  82503. });
  82504. /**
  82505. * This represents a FPS type of camera. This is only here for back compat purpose.
  82506. * Please use the UniversalCamera instead as both are identical.
  82507. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  82508. */
  82509. var GamepadCamera = /** @class */ (function (_super) {
  82510. __extends(GamepadCamera, _super);
  82511. /**
  82512. * Instantiates a new Gamepad Camera
  82513. * This represents a FPS type of camera. This is only here for back compat purpose.
  82514. * Please use the UniversalCamera instead as both are identical.
  82515. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  82516. * @param name Define the name of the camera in the scene
  82517. * @param position Define the start position of the camera in the scene
  82518. * @param scene Define the scene the camera belongs to
  82519. */
  82520. function GamepadCamera(name, position, scene) {
  82521. return _super.call(this, name, position, scene) || this;
  82522. }
  82523. /**
  82524. * Gets the current object class name.
  82525. * @return the class name
  82526. */
  82527. GamepadCamera.prototype.getClassName = function () {
  82528. return "GamepadCamera";
  82529. };
  82530. return GamepadCamera;
  82531. }(BABYLON.UniversalCamera));
  82532. BABYLON.GamepadCamera = GamepadCamera;
  82533. })(BABYLON || (BABYLON = {}));
  82534. //# sourceMappingURL=babylon.gamepadCamera.js.map
  82535. var BABYLON;
  82536. (function (BABYLON) {
  82537. /**
  82538. * PostProcessRenderPipelineManager class
  82539. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  82540. */
  82541. var PostProcessRenderPipelineManager = /** @class */ (function () {
  82542. /**
  82543. * Initializes a PostProcessRenderPipelineManager
  82544. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  82545. */
  82546. function PostProcessRenderPipelineManager() {
  82547. this._renderPipelines = {};
  82548. }
  82549. /**
  82550. * Adds a pipeline to the manager
  82551. * @param renderPipeline The pipeline to add
  82552. */
  82553. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  82554. this._renderPipelines[renderPipeline._name] = renderPipeline;
  82555. };
  82556. /**
  82557. * Attaches a camera to the pipeline
  82558. * @param renderPipelineName The name of the pipeline to attach to
  82559. * @param cameras the camera to attach
  82560. * @param unique if the camera can be attached multiple times to the pipeline
  82561. */
  82562. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  82563. if (unique === void 0) { unique = false; }
  82564. var renderPipeline = this._renderPipelines[renderPipelineName];
  82565. if (!renderPipeline) {
  82566. return;
  82567. }
  82568. renderPipeline._attachCameras(cameras, unique);
  82569. };
  82570. /**
  82571. * Detaches a camera from the pipeline
  82572. * @param renderPipelineName The name of the pipeline to detach from
  82573. * @param cameras the camera to detach
  82574. */
  82575. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  82576. var renderPipeline = this._renderPipelines[renderPipelineName];
  82577. if (!renderPipeline) {
  82578. return;
  82579. }
  82580. renderPipeline._detachCameras(cameras);
  82581. };
  82582. /**
  82583. * Enables an effect by name on a pipeline
  82584. * @param renderPipelineName the name of the pipeline to enable the effect in
  82585. * @param renderEffectName the name of the effect to enable
  82586. * @param cameras the cameras that the effect should be enabled on
  82587. */
  82588. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  82589. var renderPipeline = this._renderPipelines[renderPipelineName];
  82590. if (!renderPipeline) {
  82591. return;
  82592. }
  82593. renderPipeline._enableEffect(renderEffectName, cameras);
  82594. };
  82595. /**
  82596. * Disables an effect by name on a pipeline
  82597. * @param renderPipelineName the name of the pipeline to disable the effect in
  82598. * @param renderEffectName the name of the effect to disable
  82599. * @param cameras the cameras that the effect should be disabled on
  82600. */
  82601. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  82602. var renderPipeline = this._renderPipelines[renderPipelineName];
  82603. if (!renderPipeline) {
  82604. return;
  82605. }
  82606. renderPipeline._disableEffect(renderEffectName, cameras);
  82607. };
  82608. /**
  82609. * Updates the state of all contained render pipelines and disposes of any non supported pipelines
  82610. */
  82611. PostProcessRenderPipelineManager.prototype.update = function () {
  82612. for (var renderPipelineName in this._renderPipelines) {
  82613. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  82614. var pipeline = this._renderPipelines[renderPipelineName];
  82615. if (!pipeline.isSupported) {
  82616. pipeline.dispose();
  82617. delete this._renderPipelines[renderPipelineName];
  82618. }
  82619. else {
  82620. pipeline._update();
  82621. }
  82622. }
  82623. }
  82624. };
  82625. /** @hidden */
  82626. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  82627. for (var renderPipelineName in this._renderPipelines) {
  82628. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  82629. var pipeline = this._renderPipelines[renderPipelineName];
  82630. pipeline._rebuild();
  82631. }
  82632. }
  82633. };
  82634. /**
  82635. * Disposes of the manager and pipelines
  82636. */
  82637. PostProcessRenderPipelineManager.prototype.dispose = function () {
  82638. for (var renderPipelineName in this._renderPipelines) {
  82639. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  82640. var pipeline = this._renderPipelines[renderPipelineName];
  82641. pipeline.dispose();
  82642. }
  82643. }
  82644. };
  82645. return PostProcessRenderPipelineManager;
  82646. }());
  82647. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  82648. })(BABYLON || (BABYLON = {}));
  82649. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  82650. var BABYLON;
  82651. (function (BABYLON) {
  82652. Object.defineProperty(BABYLON.Scene.prototype, "postProcessRenderPipelineManager", {
  82653. get: function () {
  82654. if (!this._postProcessRenderPipelineManager) {
  82655. // Register the G Buffer component to the scene.
  82656. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER);
  82657. if (!component) {
  82658. component = new PostProcessRenderPipelineManagerSceneComponent(this);
  82659. this._addComponent(component);
  82660. }
  82661. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  82662. }
  82663. return this._postProcessRenderPipelineManager;
  82664. },
  82665. enumerable: true,
  82666. configurable: true
  82667. });
  82668. /**
  82669. * Defines the Render Pipeline scene component responsible to rendering pipelines
  82670. */
  82671. var PostProcessRenderPipelineManagerSceneComponent = /** @class */ (function () {
  82672. /**
  82673. * Creates a new instance of the component for the given scene
  82674. * @param scene Defines the scene to register the component in
  82675. */
  82676. function PostProcessRenderPipelineManagerSceneComponent(scene) {
  82677. /**
  82678. * The component name helpfull to identify the component in the list of scene components.
  82679. */
  82680. this.name = BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER;
  82681. this.scene = scene;
  82682. }
  82683. /**
  82684. * Registers the component in a given scene
  82685. */
  82686. PostProcessRenderPipelineManagerSceneComponent.prototype.register = function () {
  82687. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER, this, this._gatherRenderTargets);
  82688. };
  82689. /**
  82690. * Rebuilds the elements related to this component in case of
  82691. * context lost for instance.
  82692. */
  82693. PostProcessRenderPipelineManagerSceneComponent.prototype.rebuild = function () {
  82694. if (this.scene._postProcessRenderPipelineManager) {
  82695. this.scene._postProcessRenderPipelineManager._rebuild();
  82696. }
  82697. };
  82698. /**
  82699. * Disposes the component and the associated ressources
  82700. */
  82701. PostProcessRenderPipelineManagerSceneComponent.prototype.dispose = function () {
  82702. if (this.scene._postProcessRenderPipelineManager) {
  82703. this.scene._postProcessRenderPipelineManager.dispose();
  82704. }
  82705. };
  82706. PostProcessRenderPipelineManagerSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  82707. if (this.scene._postProcessRenderPipelineManager) {
  82708. this.scene._postProcessRenderPipelineManager.update();
  82709. }
  82710. };
  82711. return PostProcessRenderPipelineManagerSceneComponent;
  82712. }());
  82713. BABYLON.PostProcessRenderPipelineManagerSceneComponent = PostProcessRenderPipelineManagerSceneComponent;
  82714. })(BABYLON || (BABYLON = {}));
  82715. //# sourceMappingURL=babylon.postProcessRenderPipelineManagerSceneComponent.js.map
  82716. var BABYLON;
  82717. (function (BABYLON) {
  82718. /**
  82719. * This represents a set of one or more post processes in Babylon.
  82720. * A post process can be used to apply a shader to a texture after it is rendered.
  82721. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  82722. */
  82723. var PostProcessRenderEffect = /** @class */ (function () {
  82724. /**
  82725. * Instantiates a post process render effect.
  82726. * A post process can be used to apply a shader to a texture after it is rendered.
  82727. * @param engine The engine the effect is tied to
  82728. * @param name The name of the effect
  82729. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  82730. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  82731. */
  82732. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  82733. this._name = name;
  82734. this._singleInstance = singleInstance || true;
  82735. this._getPostProcesses = getPostProcesses;
  82736. this._cameras = {};
  82737. this._indicesForCamera = {};
  82738. this._postProcesses = {};
  82739. }
  82740. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  82741. /**
  82742. * Checks if all the post processes in the effect are supported.
  82743. */
  82744. get: function () {
  82745. for (var index in this._postProcesses) {
  82746. if (this._postProcesses.hasOwnProperty(index)) {
  82747. var pps = this._postProcesses[index];
  82748. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  82749. if (!pps[ppIndex].isSupported) {
  82750. return false;
  82751. }
  82752. }
  82753. }
  82754. }
  82755. return true;
  82756. },
  82757. enumerable: true,
  82758. configurable: true
  82759. });
  82760. /**
  82761. * Updates the current state of the effect
  82762. * @hidden
  82763. */
  82764. PostProcessRenderEffect.prototype._update = function () {
  82765. };
  82766. /**
  82767. * Attaches the effect on cameras
  82768. * @param cameras The camera to attach to.
  82769. * @hidden
  82770. */
  82771. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  82772. var _this = this;
  82773. var cameraKey;
  82774. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  82775. if (!cams) {
  82776. return;
  82777. }
  82778. for (var i = 0; i < cams.length; i++) {
  82779. var camera = cams[i];
  82780. var cameraName = camera.name;
  82781. if (this._singleInstance) {
  82782. cameraKey = 0;
  82783. }
  82784. else {
  82785. cameraKey = cameraName;
  82786. }
  82787. if (!this._postProcesses[cameraKey]) {
  82788. var postProcess = this._getPostProcesses();
  82789. if (postProcess) {
  82790. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  82791. }
  82792. }
  82793. if (!this._indicesForCamera[cameraName]) {
  82794. this._indicesForCamera[cameraName] = [];
  82795. }
  82796. this._postProcesses[cameraKey].forEach(function (postProcess) {
  82797. var index = camera.attachPostProcess(postProcess);
  82798. _this._indicesForCamera[cameraName].push(index);
  82799. });
  82800. if (!this._cameras[cameraName]) {
  82801. this._cameras[cameraName] = camera;
  82802. }
  82803. }
  82804. };
  82805. /**
  82806. * Detatches the effect on cameras
  82807. * @param cameras The camera to detatch from.
  82808. * @hidden
  82809. */
  82810. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  82811. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  82812. if (!cams) {
  82813. return;
  82814. }
  82815. for (var i = 0; i < cams.length; i++) {
  82816. var camera = cams[i];
  82817. var cameraName = camera.name;
  82818. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  82819. camera.detachPostProcess(postProcess);
  82820. });
  82821. if (this._cameras[cameraName]) {
  82822. //this._indicesForCamera.splice(index, 1);
  82823. this._cameras[cameraName] = null;
  82824. }
  82825. }
  82826. };
  82827. /**
  82828. * Enables the effect on given cameras
  82829. * @param cameras The camera to enable.
  82830. * @hidden
  82831. */
  82832. PostProcessRenderEffect.prototype._enable = function (cameras) {
  82833. var _this = this;
  82834. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  82835. if (!cams) {
  82836. return;
  82837. }
  82838. for (var i = 0; i < cams.length; i++) {
  82839. var camera = cams[i];
  82840. var cameraName = camera.name;
  82841. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  82842. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  82843. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  82844. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  82845. });
  82846. }
  82847. }
  82848. }
  82849. };
  82850. /**
  82851. * Disables the effect on the given cameras
  82852. * @param cameras The camera to disable.
  82853. * @hidden
  82854. */
  82855. PostProcessRenderEffect.prototype._disable = function (cameras) {
  82856. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  82857. if (!cams) {
  82858. return;
  82859. }
  82860. for (var i = 0; i < cams.length; i++) {
  82861. var camera = cams[i];
  82862. var cameraName = camera.name;
  82863. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  82864. camera.detachPostProcess(postProcess);
  82865. });
  82866. }
  82867. };
  82868. /**
  82869. * Gets a list of the post processes contained in the effect.
  82870. * @param camera The camera to get the post processes on.
  82871. * @returns The list of the post processes in the effect.
  82872. */
  82873. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  82874. if (this._singleInstance) {
  82875. return this._postProcesses[0];
  82876. }
  82877. else {
  82878. if (!camera) {
  82879. return null;
  82880. }
  82881. return this._postProcesses[camera.name];
  82882. }
  82883. };
  82884. return PostProcessRenderEffect;
  82885. }());
  82886. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  82887. })(BABYLON || (BABYLON = {}));
  82888. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  82889. var BABYLON;
  82890. (function (BABYLON) {
  82891. /**
  82892. * PostProcessRenderPipeline
  82893. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  82894. */
  82895. var PostProcessRenderPipeline = /** @class */ (function () {
  82896. /**
  82897. * Initializes a PostProcessRenderPipeline
  82898. * @param engine engine to add the pipeline to
  82899. * @param name name of the pipeline
  82900. */
  82901. function PostProcessRenderPipeline(engine, name) {
  82902. this.engine = engine;
  82903. this._name = name;
  82904. this._renderEffects = {};
  82905. this._renderEffectsForIsolatedPass = new Array();
  82906. this._cameras = [];
  82907. }
  82908. /**
  82909. * "PostProcessRenderPipeline"
  82910. * @returns "PostProcessRenderPipeline"
  82911. */
  82912. PostProcessRenderPipeline.prototype.getClassName = function () {
  82913. return "PostProcessRenderPipeline";
  82914. };
  82915. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  82916. /**
  82917. * If all the render effects in the pipeline are support
  82918. */
  82919. get: function () {
  82920. for (var renderEffectName in this._renderEffects) {
  82921. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  82922. if (!this._renderEffects[renderEffectName].isSupported) {
  82923. return false;
  82924. }
  82925. }
  82926. }
  82927. return true;
  82928. },
  82929. enumerable: true,
  82930. configurable: true
  82931. });
  82932. /**
  82933. * Adds an effect to the pipeline
  82934. * @param renderEffect the effect to add
  82935. */
  82936. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  82937. this._renderEffects[renderEffect._name] = renderEffect;
  82938. };
  82939. // private
  82940. /** @hidden */
  82941. PostProcessRenderPipeline.prototype._rebuild = function () {
  82942. };
  82943. /** @hidden */
  82944. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  82945. var renderEffects = this._renderEffects[renderEffectName];
  82946. if (!renderEffects) {
  82947. return;
  82948. }
  82949. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  82950. };
  82951. /** @hidden */
  82952. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  82953. var renderEffects = this._renderEffects[renderEffectName];
  82954. if (!renderEffects) {
  82955. return;
  82956. }
  82957. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  82958. };
  82959. /** @hidden */
  82960. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  82961. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  82962. if (!cams) {
  82963. return;
  82964. }
  82965. var indicesToDelete = [];
  82966. var i;
  82967. for (i = 0; i < cams.length; i++) {
  82968. var camera = cams[i];
  82969. var cameraName = camera.name;
  82970. if (this._cameras.indexOf(camera) === -1) {
  82971. this._cameras[cameraName] = camera;
  82972. }
  82973. else if (unique) {
  82974. indicesToDelete.push(i);
  82975. }
  82976. }
  82977. for (i = 0; i < indicesToDelete.length; i++) {
  82978. cameras.splice(indicesToDelete[i], 1);
  82979. }
  82980. for (var renderEffectName in this._renderEffects) {
  82981. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  82982. this._renderEffects[renderEffectName]._attachCameras(cams);
  82983. }
  82984. }
  82985. };
  82986. /** @hidden */
  82987. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  82988. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  82989. if (!cams) {
  82990. return;
  82991. }
  82992. for (var renderEffectName in this._renderEffects) {
  82993. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  82994. this._renderEffects[renderEffectName]._detachCameras(cams);
  82995. }
  82996. }
  82997. for (var i = 0; i < cams.length; i++) {
  82998. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  82999. }
  83000. };
  83001. /** @hidden */
  83002. PostProcessRenderPipeline.prototype._update = function () {
  83003. for (var renderEffectName in this._renderEffects) {
  83004. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  83005. this._renderEffects[renderEffectName]._update();
  83006. }
  83007. }
  83008. for (var i = 0; i < this._cameras.length; i++) {
  83009. var cameraName = this._cameras[i].name;
  83010. if (this._renderEffectsForIsolatedPass[cameraName]) {
  83011. this._renderEffectsForIsolatedPass[cameraName]._update();
  83012. }
  83013. }
  83014. };
  83015. /** @hidden */
  83016. PostProcessRenderPipeline.prototype._reset = function () {
  83017. this._renderEffects = {};
  83018. this._renderEffectsForIsolatedPass = new Array();
  83019. };
  83020. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  83021. // 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)
  83022. var effectKeys = Object.keys(this._renderEffects);
  83023. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  83024. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  83025. if (postProcesses) {
  83026. postProcesses[0].samples = sampleCount;
  83027. return true;
  83028. }
  83029. }
  83030. return false;
  83031. };
  83032. /**
  83033. * Disposes of the pipeline
  83034. */
  83035. PostProcessRenderPipeline.prototype.dispose = function () {
  83036. // Must be implemented by children
  83037. };
  83038. __decorate([
  83039. BABYLON.serialize()
  83040. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  83041. return PostProcessRenderPipeline;
  83042. }());
  83043. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  83044. })(BABYLON || (BABYLON = {}));
  83045. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  83046. var BABYLON;
  83047. (function (BABYLON) {
  83048. /**
  83049. * This represents a depth renderer in Babylon.
  83050. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  83051. */
  83052. var DepthRenderer = /** @class */ (function () {
  83053. /**
  83054. * Instantiates a depth renderer
  83055. * @param scene The scene the renderer belongs to
  83056. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  83057. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  83058. */
  83059. function DepthRenderer(scene, type, camera) {
  83060. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  83061. if (camera === void 0) { camera = null; }
  83062. var _this = this;
  83063. /**
  83064. * Specifiess that the depth renderer will only be used within
  83065. * the camera it is created for.
  83066. * This can help forcing its rendering during the camera processing.
  83067. */
  83068. this.useOnlyInActiveCamera = false;
  83069. this._scene = scene;
  83070. // Register the G Buffer component to the scene.
  83071. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER);
  83072. if (!component) {
  83073. component = new BABYLON.DepthRendererSceneComponent(scene);
  83074. scene._addComponent(component);
  83075. }
  83076. this._camera = camera;
  83077. var engine = scene.getEngine();
  83078. // Render target
  83079. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  83080. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83081. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83082. this._depthMap.refreshRate = 1;
  83083. this._depthMap.renderParticles = false;
  83084. this._depthMap.renderList = null;
  83085. // Camera to get depth map from to support multiple concurrent cameras
  83086. this._depthMap.activeCamera = this._camera;
  83087. this._depthMap.ignoreCameraViewport = true;
  83088. this._depthMap.useCameraPostProcesses = false;
  83089. // set default depth value to 1.0 (far away)
  83090. this._depthMap.onClearObservable.add(function (engine) {
  83091. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  83092. });
  83093. // Custom render function
  83094. var renderSubMesh = function (subMesh) {
  83095. var mesh = subMesh.getRenderingMesh();
  83096. var scene = _this._scene;
  83097. var engine = scene.getEngine();
  83098. var material = subMesh.getMaterial();
  83099. if (!material) {
  83100. return;
  83101. }
  83102. // Culling and reverse (right handed system)
  83103. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  83104. // Managing instances
  83105. var batch = mesh._getInstancesRenderList(subMesh._id);
  83106. if (batch.mustReturn) {
  83107. return;
  83108. }
  83109. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  83110. var camera = _this._camera || scene.activeCamera;
  83111. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  83112. engine.enableEffect(_this._effect);
  83113. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  83114. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  83115. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  83116. // Alpha test
  83117. if (material && material.needAlphaTesting()) {
  83118. var alphaTexture = material.getAlphaTestTexture();
  83119. if (alphaTexture) {
  83120. _this._effect.setTexture("diffuseSampler", alphaTexture);
  83121. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  83122. }
  83123. }
  83124. // Bones
  83125. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  83126. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  83127. }
  83128. // Draw
  83129. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  83130. }
  83131. };
  83132. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  83133. var index;
  83134. if (depthOnlySubMeshes.length) {
  83135. engine.setColorWrite(false);
  83136. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  83137. renderSubMesh(depthOnlySubMeshes.data[index]);
  83138. }
  83139. engine.setColorWrite(true);
  83140. }
  83141. for (index = 0; index < opaqueSubMeshes.length; index++) {
  83142. renderSubMesh(opaqueSubMeshes.data[index]);
  83143. }
  83144. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  83145. renderSubMesh(alphaTestSubMeshes.data[index]);
  83146. }
  83147. };
  83148. }
  83149. /**
  83150. * Creates the depth rendering effect and checks if the effect is ready.
  83151. * @param subMesh The submesh to be used to render the depth map of
  83152. * @param useInstances If multiple world instances should be used
  83153. * @returns if the depth renderer is ready to render the depth map
  83154. */
  83155. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  83156. var material = subMesh.getMaterial();
  83157. if (material.disableDepthWrite) {
  83158. return false;
  83159. }
  83160. var defines = [];
  83161. var attribs = [BABYLON.VertexBuffer.PositionKind];
  83162. var mesh = subMesh.getMesh();
  83163. // Alpha test
  83164. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  83165. defines.push("#define ALPHATEST");
  83166. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  83167. attribs.push(BABYLON.VertexBuffer.UVKind);
  83168. defines.push("#define UV1");
  83169. }
  83170. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  83171. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  83172. defines.push("#define UV2");
  83173. }
  83174. }
  83175. // Bones
  83176. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  83177. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  83178. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  83179. if (mesh.numBoneInfluencers > 4) {
  83180. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  83181. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  83182. }
  83183. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  83184. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  83185. }
  83186. else {
  83187. defines.push("#define NUM_BONE_INFLUENCERS 0");
  83188. }
  83189. // Instances
  83190. if (useInstances) {
  83191. defines.push("#define INSTANCES");
  83192. attribs.push("world0");
  83193. attribs.push("world1");
  83194. attribs.push("world2");
  83195. attribs.push("world3");
  83196. }
  83197. // Get correct effect
  83198. var join = defines.join("\n");
  83199. if (this._cachedDefines !== join) {
  83200. this._cachedDefines = join;
  83201. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  83202. }
  83203. return this._effect.isReady();
  83204. };
  83205. /**
  83206. * Gets the texture which the depth map will be written to.
  83207. * @returns The depth map texture
  83208. */
  83209. DepthRenderer.prototype.getDepthMap = function () {
  83210. return this._depthMap;
  83211. };
  83212. /**
  83213. * Disposes of the depth renderer.
  83214. */
  83215. DepthRenderer.prototype.dispose = function () {
  83216. this._depthMap.dispose();
  83217. };
  83218. return DepthRenderer;
  83219. }());
  83220. BABYLON.DepthRenderer = DepthRenderer;
  83221. })(BABYLON || (BABYLON = {}));
  83222. //# sourceMappingURL=babylon.depthRenderer.js.map
  83223. var BABYLON;
  83224. (function (BABYLON) {
  83225. BABYLON.Scene.prototype.enableDepthRenderer = function (camera) {
  83226. camera = camera || this.activeCamera;
  83227. if (!camera) {
  83228. throw "No camera available to enable depth renderer";
  83229. }
  83230. if (!this._depthRenderer) {
  83231. this._depthRenderer = {};
  83232. }
  83233. if (!this._depthRenderer[camera.id]) {
  83234. var textureType = 0;
  83235. if (this.getEngine().getCaps().textureHalfFloatRender) {
  83236. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  83237. }
  83238. else if (this.getEngine().getCaps().textureFloatRender) {
  83239. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  83240. }
  83241. else {
  83242. throw "Depth renderer does not support int texture type";
  83243. }
  83244. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  83245. }
  83246. return this._depthRenderer[camera.id];
  83247. };
  83248. BABYLON.Scene.prototype.disableDepthRenderer = function (camera) {
  83249. camera = camera || this.activeCamera;
  83250. if (!camera || !this._depthRenderer || !this._depthRenderer[camera.id]) {
  83251. return;
  83252. }
  83253. this._depthRenderer[camera.id].dispose();
  83254. delete this._depthRenderer[camera.id];
  83255. };
  83256. /**
  83257. * Defines the Depth Renderer scene component responsible to manage a depth buffer usefull
  83258. * in several rendering techniques.
  83259. */
  83260. var DepthRendererSceneComponent = /** @class */ (function () {
  83261. /**
  83262. * Creates a new instance of the component for the given scene
  83263. * @param scene Defines the scene to register the component in
  83264. */
  83265. function DepthRendererSceneComponent(scene) {
  83266. /**
  83267. * The component name helpfull to identify the component in the list of scene components.
  83268. */
  83269. this.name = BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER;
  83270. this.scene = scene;
  83271. }
  83272. /**
  83273. * Registers the component in a given scene
  83274. */
  83275. DepthRendererSceneComponent.prototype.register = function () {
  83276. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER, this, this._gatherRenderTargets);
  83277. this.scene._gatherActiveCameraRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER, this, this._gatherActiveCameraRenderTargets);
  83278. };
  83279. /**
  83280. * Rebuilds the elements related to this component in case of
  83281. * context lost for instance.
  83282. */
  83283. DepthRendererSceneComponent.prototype.rebuild = function () {
  83284. // Nothing to do for this component
  83285. };
  83286. /**
  83287. * Disposes the component and the associated ressources
  83288. */
  83289. DepthRendererSceneComponent.prototype.dispose = function () {
  83290. for (var key in this.scene._depthRenderer) {
  83291. this.scene._depthRenderer[key].dispose();
  83292. }
  83293. };
  83294. DepthRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  83295. if (this.scene._depthRenderer) {
  83296. for (var key in this.scene._depthRenderer) {
  83297. var depthRenderer = this.scene._depthRenderer[key];
  83298. if (!depthRenderer.useOnlyInActiveCamera) {
  83299. renderTargets.push(depthRenderer.getDepthMap());
  83300. }
  83301. }
  83302. }
  83303. };
  83304. DepthRendererSceneComponent.prototype._gatherActiveCameraRenderTargets = function (renderTargets) {
  83305. if (this.scene._depthRenderer) {
  83306. for (var key in this.scene._depthRenderer) {
  83307. var depthRenderer = this.scene._depthRenderer[key];
  83308. if (depthRenderer.useOnlyInActiveCamera && this.scene.activeCamera.id === key) {
  83309. renderTargets.push(depthRenderer.getDepthMap());
  83310. }
  83311. }
  83312. }
  83313. };
  83314. return DepthRendererSceneComponent;
  83315. }());
  83316. BABYLON.DepthRendererSceneComponent = DepthRendererSceneComponent;
  83317. })(BABYLON || (BABYLON = {}));
  83318. //# sourceMappingURL=babylon.depthRendererSceneComponent.js.map
  83319. var BABYLON;
  83320. (function (BABYLON) {
  83321. /**
  83322. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  83323. */
  83324. var GeometryBufferRenderer = /** @class */ (function () {
  83325. /**
  83326. * Creates a new G Buffer for the scene
  83327. * @param scene The scene the buffer belongs to
  83328. * @param ratio How big is the buffer related to the main canvas.
  83329. */
  83330. function GeometryBufferRenderer(scene, ratio) {
  83331. if (ratio === void 0) { ratio = 1; }
  83332. this._enablePosition = false;
  83333. this._scene = scene;
  83334. this._ratio = ratio;
  83335. // Register the G Buffer component to the scene.
  83336. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER);
  83337. if (!component) {
  83338. component = new BABYLON.GeometryBufferRendererSceneComponent(scene);
  83339. scene._addComponent(component);
  83340. }
  83341. // Render target
  83342. this._createRenderTargets();
  83343. }
  83344. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  83345. /**
  83346. * Set the render list (meshes to be rendered) used in the G buffer.
  83347. */
  83348. set: function (meshes) {
  83349. this._multiRenderTarget.renderList = meshes;
  83350. },
  83351. enumerable: true,
  83352. configurable: true
  83353. });
  83354. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  83355. /**
  83356. * Gets wether or not G buffer are supported by the running hardware.
  83357. * This requires draw buffer supports
  83358. */
  83359. get: function () {
  83360. return this._multiRenderTarget.isSupported;
  83361. },
  83362. enumerable: true,
  83363. configurable: true
  83364. });
  83365. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  83366. /**
  83367. * Gets wether or not position are enabled for the G buffer.
  83368. */
  83369. get: function () {
  83370. return this._enablePosition;
  83371. },
  83372. /**
  83373. * Sets wether or not position are enabled for the G buffer.
  83374. */
  83375. set: function (enable) {
  83376. this._enablePosition = enable;
  83377. this.dispose();
  83378. this._createRenderTargets();
  83379. },
  83380. enumerable: true,
  83381. configurable: true
  83382. });
  83383. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  83384. /**
  83385. * Gets the scene associated with the buffer.
  83386. */
  83387. get: function () {
  83388. return this._scene;
  83389. },
  83390. enumerable: true,
  83391. configurable: true
  83392. });
  83393. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  83394. /**
  83395. * Gets the ratio used by the buffer during its creation.
  83396. * How big is the buffer related to the main canvas.
  83397. */
  83398. get: function () {
  83399. return this._ratio;
  83400. },
  83401. enumerable: true,
  83402. configurable: true
  83403. });
  83404. /**
  83405. * Checks wether everything is ready to render a submesh to the G buffer.
  83406. * @param subMesh the submesh to check readiness for
  83407. * @param useInstances is the mesh drawn using instance or not
  83408. * @returns true if ready otherwise false
  83409. */
  83410. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  83411. var material = subMesh.getMaterial();
  83412. if (material && material.disableDepthWrite) {
  83413. return false;
  83414. }
  83415. var defines = [];
  83416. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  83417. var mesh = subMesh.getMesh();
  83418. // Alpha test
  83419. if (material && material.needAlphaTesting()) {
  83420. defines.push("#define ALPHATEST");
  83421. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  83422. attribs.push(BABYLON.VertexBuffer.UVKind);
  83423. defines.push("#define UV1");
  83424. }
  83425. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  83426. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  83427. defines.push("#define UV2");
  83428. }
  83429. }
  83430. // Buffers
  83431. if (this._enablePosition) {
  83432. defines.push("#define POSITION");
  83433. }
  83434. // Bones
  83435. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  83436. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  83437. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  83438. if (mesh.numBoneInfluencers > 4) {
  83439. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  83440. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  83441. }
  83442. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  83443. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  83444. }
  83445. else {
  83446. defines.push("#define NUM_BONE_INFLUENCERS 0");
  83447. }
  83448. // Instances
  83449. if (useInstances) {
  83450. defines.push("#define INSTANCES");
  83451. attribs.push("world0");
  83452. attribs.push("world1");
  83453. attribs.push("world2");
  83454. attribs.push("world3");
  83455. }
  83456. // Get correct effect
  83457. var join = defines.join("\n");
  83458. if (this._cachedDefines !== join) {
  83459. this._cachedDefines = join;
  83460. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  83461. }
  83462. return this._effect.isReady();
  83463. };
  83464. /**
  83465. * Gets the current underlying G Buffer.
  83466. * @returns the buffer
  83467. */
  83468. GeometryBufferRenderer.prototype.getGBuffer = function () {
  83469. return this._multiRenderTarget;
  83470. };
  83471. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  83472. /**
  83473. * Gets the number of samples used to render the buffer (anti aliasing).
  83474. */
  83475. get: function () {
  83476. return this._multiRenderTarget.samples;
  83477. },
  83478. /**
  83479. * Sets the number of samples used to render the buffer (anti aliasing).
  83480. */
  83481. set: function (value) {
  83482. this._multiRenderTarget.samples = value;
  83483. },
  83484. enumerable: true,
  83485. configurable: true
  83486. });
  83487. /**
  83488. * Disposes the renderer and frees up associated resources.
  83489. */
  83490. GeometryBufferRenderer.prototype.dispose = function () {
  83491. this.getGBuffer().dispose();
  83492. };
  83493. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  83494. var _this = this;
  83495. var engine = this._scene.getEngine();
  83496. var count = this._enablePosition ? 3 : 2;
  83497. 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 });
  83498. if (!this.isSupported) {
  83499. return;
  83500. }
  83501. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83502. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83503. this._multiRenderTarget.refreshRate = 1;
  83504. this._multiRenderTarget.renderParticles = false;
  83505. this._multiRenderTarget.renderList = null;
  83506. // set default depth value to 1.0 (far away)
  83507. this._multiRenderTarget.onClearObservable.add(function (engine) {
  83508. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  83509. });
  83510. // Custom render function
  83511. var renderSubMesh = function (subMesh) {
  83512. var mesh = subMesh.getRenderingMesh();
  83513. var scene = _this._scene;
  83514. var engine = scene.getEngine();
  83515. var material = subMesh.getMaterial();
  83516. if (!material) {
  83517. return;
  83518. }
  83519. // Culling
  83520. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  83521. // Managing instances
  83522. var batch = mesh._getInstancesRenderList(subMesh._id);
  83523. if (batch.mustReturn) {
  83524. return;
  83525. }
  83526. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  83527. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  83528. engine.enableEffect(_this._effect);
  83529. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  83530. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  83531. _this._effect.setMatrix("view", scene.getViewMatrix());
  83532. // Alpha test
  83533. if (material && material.needAlphaTesting()) {
  83534. var alphaTexture = material.getAlphaTestTexture();
  83535. if (alphaTexture) {
  83536. _this._effect.setTexture("diffuseSampler", alphaTexture);
  83537. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  83538. }
  83539. }
  83540. // Bones
  83541. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  83542. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  83543. }
  83544. // Draw
  83545. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  83546. }
  83547. };
  83548. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  83549. var index;
  83550. if (depthOnlySubMeshes.length) {
  83551. engine.setColorWrite(false);
  83552. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  83553. renderSubMesh(depthOnlySubMeshes.data[index]);
  83554. }
  83555. engine.setColorWrite(true);
  83556. }
  83557. for (index = 0; index < opaqueSubMeshes.length; index++) {
  83558. renderSubMesh(opaqueSubMeshes.data[index]);
  83559. }
  83560. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  83561. renderSubMesh(alphaTestSubMeshes.data[index]);
  83562. }
  83563. };
  83564. };
  83565. return GeometryBufferRenderer;
  83566. }());
  83567. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  83568. })(BABYLON || (BABYLON = {}));
  83569. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  83570. var BABYLON;
  83571. (function (BABYLON) {
  83572. Object.defineProperty(BABYLON.Scene.prototype, "geometryBufferRenderer", {
  83573. get: function () {
  83574. this._geometryBufferRenderer;
  83575. },
  83576. set: function (value) {
  83577. if (value && value.isSupported) {
  83578. this._geometryBufferRenderer = value;
  83579. }
  83580. ;
  83581. },
  83582. enumerable: true,
  83583. configurable: true
  83584. });
  83585. BABYLON.Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  83586. if (ratio === void 0) { ratio = 1; }
  83587. if (this._geometryBufferRenderer) {
  83588. return this._geometryBufferRenderer;
  83589. }
  83590. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  83591. if (!this._geometryBufferRenderer.isSupported) {
  83592. this._geometryBufferRenderer = null;
  83593. }
  83594. return this._geometryBufferRenderer;
  83595. };
  83596. BABYLON.Scene.prototype.disableGeometryBufferRenderer = function () {
  83597. if (!this._geometryBufferRenderer) {
  83598. return;
  83599. }
  83600. this._geometryBufferRenderer.dispose();
  83601. this._geometryBufferRenderer = null;
  83602. };
  83603. /**
  83604. * Defines the Geometry Buffer scene component responsible to manage a G-Buffer useful
  83605. * in several rendering techniques.
  83606. */
  83607. var GeometryBufferRendererSceneComponent = /** @class */ (function () {
  83608. /**
  83609. * Creates a new instance of the component for the given scene
  83610. * @param scene Defines the scene to register the component in
  83611. */
  83612. function GeometryBufferRendererSceneComponent(scene) {
  83613. /**
  83614. * The component name helpful to identify the component in the list of scene components.
  83615. */
  83616. this.name = BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER;
  83617. this.scene = scene;
  83618. }
  83619. /**
  83620. * Registers the component in a given scene
  83621. */
  83622. GeometryBufferRendererSceneComponent.prototype.register = function () {
  83623. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER, this, this._gatherRenderTargets);
  83624. };
  83625. /**
  83626. * Rebuilds the elements related to this component in case of
  83627. * context lost for instance.
  83628. */
  83629. GeometryBufferRendererSceneComponent.prototype.rebuild = function () {
  83630. // Nothing to do for this component
  83631. };
  83632. /**
  83633. * Disposes the component and the associated ressources
  83634. */
  83635. GeometryBufferRendererSceneComponent.prototype.dispose = function () {
  83636. // Nothing to do for this component
  83637. };
  83638. GeometryBufferRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  83639. if (this.scene._geometryBufferRenderer) {
  83640. renderTargets.push(this.scene._geometryBufferRenderer.getGBuffer());
  83641. }
  83642. };
  83643. return GeometryBufferRendererSceneComponent;
  83644. }());
  83645. BABYLON.GeometryBufferRendererSceneComponent = GeometryBufferRendererSceneComponent;
  83646. })(BABYLON || (BABYLON = {}));
  83647. //# sourceMappingURL=babylon.geometryBufferRendererSceneComponent.js.map
  83648. var BABYLON;
  83649. (function (BABYLON) {
  83650. /**
  83651. * Render pipeline to produce ssao effect
  83652. */
  83653. var SSAORenderingPipeline = /** @class */ (function (_super) {
  83654. __extends(SSAORenderingPipeline, _super);
  83655. /**
  83656. * @constructor
  83657. * @param {string} name - The rendering pipeline name
  83658. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  83659. * @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 }
  83660. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  83661. */
  83662. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  83663. var _this = _super.call(this, scene.getEngine(), name) || this;
  83664. // Members
  83665. /**
  83666. * @ignore
  83667. * The PassPostProcess id in the pipeline that contains the original scene color
  83668. */
  83669. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  83670. /**
  83671. * @ignore
  83672. * The SSAO PostProcess id in the pipeline
  83673. */
  83674. _this.SSAORenderEffect = "SSAORenderEffect";
  83675. /**
  83676. * @ignore
  83677. * The horizontal blur PostProcess id in the pipeline
  83678. */
  83679. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  83680. /**
  83681. * @ignore
  83682. * The vertical blur PostProcess id in the pipeline
  83683. */
  83684. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  83685. /**
  83686. * @ignore
  83687. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  83688. */
  83689. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  83690. /**
  83691. * The output strength of the SSAO post-process. Default value is 1.0.
  83692. */
  83693. _this.totalStrength = 1.0;
  83694. /**
  83695. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  83696. */
  83697. _this.radius = 0.0001;
  83698. /**
  83699. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  83700. * Must not be equal to fallOff and superior to fallOff.
  83701. * Default value is 0.975
  83702. */
  83703. _this.area = 0.0075;
  83704. /**
  83705. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  83706. * Must not be equal to area and inferior to area.
  83707. * Default value is 0.0
  83708. */
  83709. _this.fallOff = 0.000001;
  83710. /**
  83711. * The base color of the SSAO post-process
  83712. * The final result is "base + ssao" between [0, 1]
  83713. */
  83714. _this.base = 0.5;
  83715. _this._firstUpdate = true;
  83716. _this._scene = scene;
  83717. // Set up assets
  83718. _this._createRandomTexture();
  83719. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  83720. var ssaoRatio = ratio.ssaoRatio || ratio;
  83721. var combineRatio = ratio.combineRatio || ratio;
  83722. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  83723. _this._createSSAOPostProcess(ssaoRatio);
  83724. _this._createBlurPostProcess(ssaoRatio);
  83725. _this._createSSAOCombinePostProcess(combineRatio);
  83726. // Set up pipeline
  83727. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  83728. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  83729. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  83730. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  83731. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  83732. // Finish
  83733. scene.postProcessRenderPipelineManager.addPipeline(_this);
  83734. if (cameras)
  83735. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  83736. return _this;
  83737. }
  83738. // Public Methods
  83739. /**
  83740. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  83741. */
  83742. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  83743. if (disableDepthRender === void 0) { disableDepthRender = false; }
  83744. for (var i = 0; i < this._scene.cameras.length; i++) {
  83745. var camera = this._scene.cameras[i];
  83746. this._originalColorPostProcess.dispose(camera);
  83747. this._ssaoPostProcess.dispose(camera);
  83748. this._blurHPostProcess.dispose(camera);
  83749. this._blurVPostProcess.dispose(camera);
  83750. this._ssaoCombinePostProcess.dispose(camera);
  83751. }
  83752. this._randomTexture.dispose();
  83753. if (disableDepthRender)
  83754. this._scene.disableDepthRenderer();
  83755. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  83756. _super.prototype.dispose.call(this);
  83757. };
  83758. // Private Methods
  83759. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  83760. var _this = this;
  83761. var size = 16;
  83762. 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);
  83763. 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);
  83764. this._blurHPostProcess.onActivateObservable.add(function () {
  83765. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  83766. _this._blurHPostProcess.kernel = size * dw;
  83767. });
  83768. this._blurVPostProcess.onActivateObservable.add(function () {
  83769. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  83770. _this._blurVPostProcess.kernel = size * dw;
  83771. });
  83772. };
  83773. /** @hidden */
  83774. SSAORenderingPipeline.prototype._rebuild = function () {
  83775. this._firstUpdate = true;
  83776. _super.prototype._rebuild.call(this);
  83777. };
  83778. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  83779. var _this = this;
  83780. var numSamples = 16;
  83781. var sampleSphere = [
  83782. 0.5381, 0.1856, -0.4319,
  83783. 0.1379, 0.2486, 0.4430,
  83784. 0.3371, 0.5679, -0.0057,
  83785. -0.6999, -0.0451, -0.0019,
  83786. 0.0689, -0.1598, -0.8547,
  83787. 0.0560, 0.0069, -0.1843,
  83788. -0.0146, 0.1402, 0.0762,
  83789. 0.0100, -0.1924, -0.0344,
  83790. -0.3577, -0.5301, -0.4358,
  83791. -0.3169, 0.1063, 0.0158,
  83792. 0.0103, -0.5869, 0.0046,
  83793. -0.0897, -0.4940, 0.3287,
  83794. 0.7119, -0.0154, -0.0918,
  83795. -0.0533, 0.0596, -0.5411,
  83796. 0.0352, -0.0631, 0.5460,
  83797. -0.4776, 0.2847, -0.0271
  83798. ];
  83799. var samplesFactor = 1.0 / numSamples;
  83800. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  83801. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  83802. "area", "fallOff", "base", "range", "viewport"
  83803. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  83804. this._ssaoPostProcess.onApply = function (effect) {
  83805. if (_this._firstUpdate) {
  83806. effect.setArray3("sampleSphere", sampleSphere);
  83807. effect.setFloat("samplesFactor", samplesFactor);
  83808. effect.setFloat("randTextureTiles", 4.0);
  83809. }
  83810. effect.setFloat("totalStrength", _this.totalStrength);
  83811. effect.setFloat("radius", _this.radius);
  83812. effect.setFloat("area", _this.area);
  83813. effect.setFloat("fallOff", _this.fallOff);
  83814. effect.setFloat("base", _this.base);
  83815. effect.setTexture("textureSampler", _this._depthTexture);
  83816. effect.setTexture("randomSampler", _this._randomTexture);
  83817. };
  83818. };
  83819. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  83820. var _this = this;
  83821. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  83822. this._ssaoCombinePostProcess.onApply = function (effect) {
  83823. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  83824. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  83825. };
  83826. };
  83827. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  83828. var size = 512;
  83829. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  83830. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  83831. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  83832. var context = this._randomTexture.getContext();
  83833. var rand = function (min, max) {
  83834. return Math.random() * (max - min) + min;
  83835. };
  83836. var randVector = BABYLON.Vector3.Zero();
  83837. for (var x = 0; x < size; x++) {
  83838. for (var y = 0; y < size; y++) {
  83839. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  83840. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  83841. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  83842. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  83843. context.fillRect(x, y, 1, 1);
  83844. }
  83845. }
  83846. this._randomTexture.update(false);
  83847. };
  83848. __decorate([
  83849. BABYLON.serialize()
  83850. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  83851. __decorate([
  83852. BABYLON.serialize()
  83853. ], SSAORenderingPipeline.prototype, "radius", void 0);
  83854. __decorate([
  83855. BABYLON.serialize()
  83856. ], SSAORenderingPipeline.prototype, "area", void 0);
  83857. __decorate([
  83858. BABYLON.serialize()
  83859. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  83860. __decorate([
  83861. BABYLON.serialize()
  83862. ], SSAORenderingPipeline.prototype, "base", void 0);
  83863. return SSAORenderingPipeline;
  83864. }(BABYLON.PostProcessRenderPipeline));
  83865. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  83866. })(BABYLON || (BABYLON = {}));
  83867. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  83868. var BABYLON;
  83869. (function (BABYLON) {
  83870. /**
  83871. * Render pipeline to produce ssao effect
  83872. */
  83873. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  83874. __extends(SSAO2RenderingPipeline, _super);
  83875. /**
  83876. * @constructor
  83877. * @param {string} name - The rendering pipeline name
  83878. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  83879. * @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 }
  83880. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  83881. */
  83882. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  83883. var _this = _super.call(this, scene.getEngine(), name) || this;
  83884. // Members
  83885. /**
  83886. * @ignore
  83887. * The PassPostProcess id in the pipeline that contains the original scene color
  83888. */
  83889. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  83890. /**
  83891. * @ignore
  83892. * The SSAO PostProcess id in the pipeline
  83893. */
  83894. _this.SSAORenderEffect = "SSAORenderEffect";
  83895. /**
  83896. * @ignore
  83897. * The horizontal blur PostProcess id in the pipeline
  83898. */
  83899. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  83900. /**
  83901. * @ignore
  83902. * The vertical blur PostProcess id in the pipeline
  83903. */
  83904. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  83905. /**
  83906. * @ignore
  83907. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  83908. */
  83909. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  83910. /**
  83911. * The output strength of the SSAO post-process. Default value is 1.0.
  83912. */
  83913. _this.totalStrength = 1.0;
  83914. /**
  83915. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  83916. */
  83917. _this.maxZ = 100.0;
  83918. /**
  83919. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  83920. */
  83921. _this.minZAspect = 0.2;
  83922. _this._samples = 8;
  83923. _this._textureSamples = 1;
  83924. _this._expensiveBlur = true;
  83925. /**
  83926. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  83927. */
  83928. _this.radius = 2.0;
  83929. /**
  83930. * The base color of the SSAO post-process
  83931. * The final result is "base + ssao" between [0, 1]
  83932. */
  83933. _this.base = 0;
  83934. _this._firstUpdate = true;
  83935. _this._bits = new Uint32Array(1);
  83936. _this._scene = scene;
  83937. _this._ratio = ratio;
  83938. if (!_this.isSupported) {
  83939. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  83940. return _this;
  83941. }
  83942. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  83943. var blurRatio = _this._ratio.blurRatio || ratio;
  83944. // Set up assets
  83945. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  83946. _this._createRandomTexture();
  83947. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  83948. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  83949. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  83950. _this._originalColorPostProcess.samples = _this.textureSamples;
  83951. _this._createSSAOPostProcess(1.0);
  83952. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  83953. _this._createSSAOCombinePostProcess(blurRatio);
  83954. // Set up pipeline
  83955. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  83956. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  83957. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  83958. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  83959. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  83960. // Finish
  83961. scene.postProcessRenderPipelineManager.addPipeline(_this);
  83962. if (cameras)
  83963. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  83964. return _this;
  83965. }
  83966. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  83967. get: function () {
  83968. return this._samples;
  83969. },
  83970. /**
  83971. * Number of samples used for the SSAO calculations. Default value is 8
  83972. */
  83973. set: function (n) {
  83974. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  83975. this._samples = n;
  83976. this._sampleSphere = this._generateHemisphere();
  83977. this._firstUpdate = true;
  83978. },
  83979. enumerable: true,
  83980. configurable: true
  83981. });
  83982. Object.defineProperty(SSAO2RenderingPipeline.prototype, "textureSamples", {
  83983. get: function () {
  83984. return this._textureSamples;
  83985. },
  83986. /**
  83987. * Number of samples to use for antialiasing
  83988. */
  83989. set: function (n) {
  83990. this._textureSamples = n;
  83991. this._originalColorPostProcess.samples = n;
  83992. this._blurHPostProcess.samples = n;
  83993. this._blurVPostProcess.samples = n;
  83994. this._ssaoPostProcess.samples = n;
  83995. this._ssaoCombinePostProcess.samples = n;
  83996. },
  83997. enumerable: true,
  83998. configurable: true
  83999. });
  84000. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  84001. get: function () {
  84002. return this._expensiveBlur;
  84003. },
  84004. /**
  84005. * If bilateral blur should be used
  84006. */
  84007. set: function (b) {
  84008. 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"]);
  84009. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  84010. this._expensiveBlur = b;
  84011. this._firstUpdate = true;
  84012. },
  84013. enumerable: true,
  84014. configurable: true
  84015. });
  84016. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  84017. /**
  84018. * Support test.
  84019. */
  84020. get: function () {
  84021. var engine = BABYLON.Engine.LastCreatedEngine;
  84022. if (!engine) {
  84023. return false;
  84024. }
  84025. return engine.getCaps().drawBuffersExtension;
  84026. },
  84027. enumerable: true,
  84028. configurable: true
  84029. });
  84030. // Public Methods
  84031. /**
  84032. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  84033. */
  84034. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  84035. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  84036. for (var i = 0; i < this._scene.cameras.length; i++) {
  84037. var camera = this._scene.cameras[i];
  84038. this._originalColorPostProcess.dispose(camera);
  84039. this._ssaoPostProcess.dispose(camera);
  84040. this._blurHPostProcess.dispose(camera);
  84041. this._blurVPostProcess.dispose(camera);
  84042. this._ssaoCombinePostProcess.dispose(camera);
  84043. }
  84044. this._randomTexture.dispose();
  84045. if (disableGeometryBufferRenderer)
  84046. this._scene.disableGeometryBufferRenderer();
  84047. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  84048. _super.prototype.dispose.call(this);
  84049. };
  84050. // Private Methods
  84051. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  84052. var _this = this;
  84053. this._samplerOffsets = [];
  84054. var expensive = this.expensiveBlur;
  84055. for (var i = -8; i < 8; i++) {
  84056. this._samplerOffsets.push(i * 2 + 0.5);
  84057. }
  84058. 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");
  84059. this._blurHPostProcess.onApply = function (effect) {
  84060. if (!_this._scene.activeCamera) {
  84061. return;
  84062. }
  84063. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  84064. effect.setFloat("near", _this._scene.activeCamera.minZ);
  84065. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  84066. effect.setFloat("radius", _this.radius);
  84067. effect.setTexture("depthSampler", _this._depthTexture);
  84068. if (_this._firstUpdate) {
  84069. effect.setArray("samplerOffsets", _this._samplerOffsets);
  84070. }
  84071. };
  84072. 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");
  84073. this._blurVPostProcess.onApply = function (effect) {
  84074. if (!_this._scene.activeCamera) {
  84075. return;
  84076. }
  84077. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  84078. effect.setFloat("near", _this._scene.activeCamera.minZ);
  84079. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  84080. effect.setFloat("radius", _this.radius);
  84081. effect.setTexture("depthSampler", _this._depthTexture);
  84082. if (_this._firstUpdate) {
  84083. effect.setArray("samplerOffsets", _this._samplerOffsets);
  84084. _this._firstUpdate = false;
  84085. }
  84086. };
  84087. this._blurHPostProcess.samples = this.textureSamples;
  84088. this._blurVPostProcess.samples = this.textureSamples;
  84089. };
  84090. /** @hidden */
  84091. SSAO2RenderingPipeline.prototype._rebuild = function () {
  84092. this._firstUpdate = true;
  84093. _super.prototype._rebuild.call(this);
  84094. };
  84095. //Van der Corput radical inverse
  84096. SSAO2RenderingPipeline.prototype._radicalInverse_VdC = function (i) {
  84097. this._bits[0] = i;
  84098. this._bits[0] = ((this._bits[0] << 16) | (this._bits[0] >> 16)) >>> 0;
  84099. this._bits[0] = ((this._bits[0] & 0x55555555) << 1) | ((this._bits[0] & 0xAAAAAAAA) >>> 1) >>> 0;
  84100. this._bits[0] = ((this._bits[0] & 0x33333333) << 2) | ((this._bits[0] & 0xCCCCCCCC) >>> 2) >>> 0;
  84101. this._bits[0] = ((this._bits[0] & 0x0F0F0F0F) << 4) | ((this._bits[0] & 0xF0F0F0F0) >>> 4) >>> 0;
  84102. this._bits[0] = ((this._bits[0] & 0x00FF00FF) << 8) | ((this._bits[0] & 0xFF00FF00) >>> 8) >>> 0;
  84103. return this._bits[0] * 2.3283064365386963e-10; // / 0x100000000 or / 4294967296
  84104. };
  84105. SSAO2RenderingPipeline.prototype._hammersley = function (i, n) {
  84106. return [i / n, this._radicalInverse_VdC(i)];
  84107. };
  84108. SSAO2RenderingPipeline.prototype._hemisphereSample_uniform = function (u, v) {
  84109. var phi = v * 2.0 * Math.PI;
  84110. // rejecting samples that are close to tangent plane to avoid z-fighting artifacts
  84111. var cosTheta = 1.0 - (u * 0.85 + 0.15);
  84112. var sinTheta = Math.sqrt(1.0 - cosTheta * cosTheta);
  84113. return new BABYLON.Vector3(Math.cos(phi) * sinTheta, Math.sin(phi) * sinTheta, cosTheta);
  84114. };
  84115. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  84116. var numSamples = this.samples;
  84117. var result = [];
  84118. var vector;
  84119. var i = 0;
  84120. while (i < numSamples) {
  84121. if (numSamples < 16) {
  84122. vector = this._hemisphereSample_uniform(Math.random(), Math.random());
  84123. }
  84124. else {
  84125. var rand = this._hammersley(i, numSamples);
  84126. vector = this._hemisphereSample_uniform(rand[0], rand[1]);
  84127. }
  84128. result.push(vector.x, vector.y, vector.z);
  84129. i++;
  84130. }
  84131. return result;
  84132. };
  84133. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  84134. var _this = this;
  84135. var numSamples = this.samples;
  84136. this._sampleSphere = this._generateHemisphere();
  84137. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  84138. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  84139. "base", "range", "projection", "near", "far", "texelSize",
  84140. "xViewport", "yViewport", "maxZ", "minZAspect"
  84141. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  84142. this._ssaoPostProcess.onApply = function (effect) {
  84143. if (_this._firstUpdate) {
  84144. effect.setArray3("sampleSphere", _this._sampleSphere);
  84145. effect.setFloat("randTextureTiles", 32.0);
  84146. }
  84147. if (!_this._scene.activeCamera) {
  84148. return;
  84149. }
  84150. effect.setFloat("samplesFactor", 1 / _this.samples);
  84151. effect.setFloat("totalStrength", _this.totalStrength);
  84152. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  84153. effect.setFloat("radius", _this.radius);
  84154. effect.setFloat("maxZ", _this.maxZ);
  84155. effect.setFloat("minZAspect", _this.minZAspect);
  84156. effect.setFloat("base", _this.base);
  84157. effect.setFloat("near", _this._scene.activeCamera.minZ);
  84158. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  84159. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  84160. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  84161. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  84162. effect.setTexture("textureSampler", _this._depthTexture);
  84163. effect.setTexture("normalSampler", _this._normalTexture);
  84164. effect.setTexture("randomSampler", _this._randomTexture);
  84165. };
  84166. this._ssaoPostProcess.samples = this.textureSamples;
  84167. };
  84168. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  84169. var _this = this;
  84170. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  84171. this._ssaoCombinePostProcess.onApply = function (effect) {
  84172. var viewport = _this._scene.activeCamera.viewport;
  84173. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  84174. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  84175. };
  84176. this._ssaoCombinePostProcess.samples = this.textureSamples;
  84177. };
  84178. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  84179. var size = 128;
  84180. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  84181. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  84182. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  84183. var context = this._randomTexture.getContext();
  84184. var rand = function (min, max) {
  84185. return Math.random() * (max - min) + min;
  84186. };
  84187. var randVector = BABYLON.Vector3.Zero();
  84188. for (var x = 0; x < size; x++) {
  84189. for (var y = 0; y < size; y++) {
  84190. randVector.x = rand(0.0, 1.0);
  84191. randVector.y = rand(0.0, 1.0);
  84192. randVector.z = 0.0;
  84193. randVector.normalize();
  84194. randVector.scaleInPlace(255);
  84195. randVector.x = Math.floor(randVector.x);
  84196. randVector.y = Math.floor(randVector.y);
  84197. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  84198. context.fillRect(x, y, 1, 1);
  84199. }
  84200. }
  84201. this._randomTexture.update(false);
  84202. };
  84203. /**
  84204. * Serialize the rendering pipeline (Used when exporting)
  84205. * @returns the serialized object
  84206. */
  84207. SSAO2RenderingPipeline.prototype.serialize = function () {
  84208. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  84209. serializationObject.customType = "SSAO2RenderingPipeline";
  84210. return serializationObject;
  84211. };
  84212. /**
  84213. * Parse the serialized pipeline
  84214. * @param source Source pipeline.
  84215. * @param scene The scene to load the pipeline to.
  84216. * @param rootUrl The URL of the serialized pipeline.
  84217. * @returns An instantiated pipeline from the serialized object.
  84218. */
  84219. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  84220. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  84221. };
  84222. __decorate([
  84223. BABYLON.serialize()
  84224. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  84225. __decorate([
  84226. BABYLON.serialize()
  84227. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  84228. __decorate([
  84229. BABYLON.serialize()
  84230. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  84231. __decorate([
  84232. BABYLON.serialize("samples")
  84233. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  84234. __decorate([
  84235. BABYLON.serialize("textureSamples")
  84236. ], SSAO2RenderingPipeline.prototype, "_textureSamples", void 0);
  84237. __decorate([
  84238. BABYLON.serialize()
  84239. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  84240. __decorate([
  84241. BABYLON.serialize("expensiveBlur")
  84242. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  84243. __decorate([
  84244. BABYLON.serialize()
  84245. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  84246. __decorate([
  84247. BABYLON.serialize()
  84248. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  84249. return SSAO2RenderingPipeline;
  84250. }(BABYLON.PostProcessRenderPipeline));
  84251. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  84252. })(BABYLON || (BABYLON = {}));
  84253. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  84254. var BABYLON;
  84255. (function (BABYLON) {
  84256. /**
  84257. * BABYLON.JS Chromatic Aberration GLSL Shader
  84258. * Author: Olivier Guyot
  84259. * Separates very slightly R, G and B colors on the edges of the screen
  84260. * Inspired by Francois Tarlier & Martins Upitis
  84261. */
  84262. var LensRenderingPipeline = /** @class */ (function (_super) {
  84263. __extends(LensRenderingPipeline, _super);
  84264. /**
  84265. * @constructor
  84266. *
  84267. * Effect parameters are as follow:
  84268. * {
  84269. * chromatic_aberration: number; // from 0 to x (1 for realism)
  84270. * edge_blur: number; // from 0 to x (1 for realism)
  84271. * distortion: number; // from 0 to x (1 for realism)
  84272. * grain_amount: number; // from 0 to 1
  84273. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  84274. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  84275. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  84276. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  84277. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  84278. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  84279. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  84280. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  84281. * }
  84282. * Note: if an effect parameter is unset, effect is disabled
  84283. *
  84284. * @param {string} name - The rendering pipeline name
  84285. * @param {object} parameters - An object containing all parameters (see above)
  84286. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  84287. * @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)
  84288. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  84289. */
  84290. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  84291. if (ratio === void 0) { ratio = 1.0; }
  84292. var _this = _super.call(this, scene.getEngine(), name) || this;
  84293. // Lens effects can be of the following:
  84294. // - chromatic aberration (slight shift of RGB colors)
  84295. // - blur on the edge of the lens
  84296. // - lens distortion
  84297. // - depth-of-field blur & highlights enhancing
  84298. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  84299. // - grain effect (noise or custom texture)
  84300. // Two additional texture samplers are needed:
  84301. // - depth map (for depth-of-field)
  84302. // - grain texture
  84303. /**
  84304. * @ignore
  84305. * The chromatic aberration PostProcess id in the pipeline
  84306. */
  84307. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  84308. /**
  84309. * @ignore
  84310. * The highlights enhancing PostProcess id in the pipeline
  84311. */
  84312. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  84313. /**
  84314. * @ignore
  84315. * The depth-of-field PostProcess id in the pipeline
  84316. */
  84317. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  84318. _this._scene = scene;
  84319. // Fetch texture samplers
  84320. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  84321. if (parameters.grain_texture) {
  84322. _this._grainTexture = parameters.grain_texture;
  84323. }
  84324. else {
  84325. _this._createGrainTexture();
  84326. }
  84327. // save parameters
  84328. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  84329. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  84330. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  84331. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  84332. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  84333. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  84334. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  84335. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  84336. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  84337. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  84338. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  84339. // Create effects
  84340. _this._createChromaticAberrationPostProcess(ratio);
  84341. _this._createHighlightsPostProcess(ratio);
  84342. _this._createDepthOfFieldPostProcess(ratio / 4);
  84343. // Set up pipeline
  84344. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  84345. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  84346. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  84347. if (_this._highlightsGain === -1) {
  84348. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  84349. }
  84350. // Finish
  84351. scene.postProcessRenderPipelineManager.addPipeline(_this);
  84352. if (cameras) {
  84353. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  84354. }
  84355. return _this;
  84356. }
  84357. // public methods (self explanatory)
  84358. /**
  84359. * Sets the amount of blur at the edges
  84360. * @param amount blur amount
  84361. */
  84362. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  84363. /**
  84364. * Sets edge blur to 0
  84365. */
  84366. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  84367. /**
  84368. * Sets the amout of grain
  84369. * @param amount Amount of grain
  84370. */
  84371. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  84372. /**
  84373. * Set grain amount to 0
  84374. */
  84375. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  84376. /**
  84377. * Sets the chromatic aberration amount
  84378. * @param amount amount of chromatic aberration
  84379. */
  84380. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  84381. /**
  84382. * Sets chromatic aberration amount to 0
  84383. */
  84384. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  84385. /**
  84386. * Sets the EdgeDistortion amount
  84387. * @param amount amount of EdgeDistortion
  84388. */
  84389. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  84390. /**
  84391. * Sets edge distortion to 0
  84392. */
  84393. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  84394. /**
  84395. * Sets the FocusDistance amount
  84396. * @param amount amount of FocusDistance
  84397. */
  84398. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  84399. /**
  84400. * Disables depth of field
  84401. */
  84402. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  84403. /**
  84404. * Sets the Aperture amount
  84405. * @param amount amount of Aperture
  84406. */
  84407. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  84408. /**
  84409. * Sets the DarkenOutOfFocus amount
  84410. * @param amount amount of DarkenOutOfFocus
  84411. */
  84412. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  84413. /**
  84414. * Creates a pentagon bokeh effect
  84415. */
  84416. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  84417. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  84418. };
  84419. /**
  84420. * Disables the pentagon bokeh effect
  84421. */
  84422. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  84423. this._highlightsPostProcess.updateEffect();
  84424. };
  84425. /**
  84426. * Enables noise blur
  84427. */
  84428. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  84429. /**
  84430. * Disables noise blur
  84431. */
  84432. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  84433. /**
  84434. * Sets the HighlightsGain amount
  84435. * @param amount amount of HighlightsGain
  84436. */
  84437. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  84438. this._highlightsGain = amount;
  84439. };
  84440. /**
  84441. * Sets the HighlightsThreshold amount
  84442. * @param amount amount of HighlightsThreshold
  84443. */
  84444. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  84445. if (this._highlightsGain === -1) {
  84446. this._highlightsGain = 1.0;
  84447. }
  84448. this._highlightsThreshold = amount;
  84449. };
  84450. /**
  84451. * Disables highlights
  84452. */
  84453. LensRenderingPipeline.prototype.disableHighlights = function () {
  84454. this._highlightsGain = -1;
  84455. };
  84456. /**
  84457. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  84458. * @param disableDepthRender If the scens depth rendering should be disabled (default: false)
  84459. */
  84460. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  84461. if (disableDepthRender === void 0) { disableDepthRender = false; }
  84462. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  84463. this._chromaticAberrationPostProcess = null;
  84464. this._highlightsPostProcess = null;
  84465. this._depthOfFieldPostProcess = null;
  84466. this._grainTexture.dispose();
  84467. if (disableDepthRender)
  84468. this._scene.disableDepthRenderer();
  84469. };
  84470. // colors shifting and distortion
  84471. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  84472. var _this = this;
  84473. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  84474. [], // samplers
  84475. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  84476. this._chromaticAberrationPostProcess.onApply = function (effect) {
  84477. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  84478. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  84479. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  84480. effect.setFloat('radialIntensity', 1);
  84481. effect.setFloat2('direction', 17, 17);
  84482. effect.setFloat2('centerPosition', 0.5, 0.5);
  84483. };
  84484. };
  84485. // highlights enhancing
  84486. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  84487. var _this = this;
  84488. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  84489. [], // samplers
  84490. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  84491. this._highlightsPostProcess.onApply = function (effect) {
  84492. effect.setFloat('gain', _this._highlightsGain);
  84493. effect.setFloat('threshold', _this._highlightsThreshold);
  84494. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  84495. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  84496. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  84497. };
  84498. };
  84499. // colors shifting and distortion
  84500. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  84501. var _this = this;
  84502. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  84503. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  84504. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  84505. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  84506. this._depthOfFieldPostProcess.onApply = function (effect) {
  84507. effect.setTexture("depthSampler", _this._depthTexture);
  84508. effect.setTexture("grainSampler", _this._grainTexture);
  84509. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  84510. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  84511. effect.setFloat('grain_amount', _this._grainAmount);
  84512. effect.setBool('blur_noise', _this._blurNoise);
  84513. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  84514. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  84515. effect.setFloat('distortion', _this._distortion);
  84516. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  84517. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  84518. effect.setFloat('aperture', _this._dofAperture);
  84519. effect.setFloat('darken', _this._dofDarken);
  84520. effect.setFloat('edge_blur', _this._edgeBlur);
  84521. effect.setBool('highlights', (_this._highlightsGain !== -1));
  84522. if (_this._scene.activeCamera) {
  84523. effect.setFloat('near', _this._scene.activeCamera.minZ);
  84524. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  84525. }
  84526. };
  84527. };
  84528. // creates a black and white random noise texture, 512x512
  84529. LensRenderingPipeline.prototype._createGrainTexture = function () {
  84530. var size = 512;
  84531. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  84532. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  84533. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  84534. var context = this._grainTexture.getContext();
  84535. var rand = function (min, max) {
  84536. return Math.random() * (max - min) + min;
  84537. };
  84538. var value;
  84539. for (var x = 0; x < size; x++) {
  84540. for (var y = 0; y < size; y++) {
  84541. value = Math.floor(rand(0.42, 0.58) * 255);
  84542. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  84543. context.fillRect(x, y, 1, 1);
  84544. }
  84545. }
  84546. this._grainTexture.update(false);
  84547. };
  84548. return LensRenderingPipeline;
  84549. }(BABYLON.PostProcessRenderPipeline));
  84550. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  84551. })(BABYLON || (BABYLON = {}));
  84552. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  84553. var BABYLON;
  84554. (function (BABYLON) {
  84555. /**
  84556. * Standard rendering pipeline
  84557. * Default pipeline should be used going forward but the standard pipeline will be kept for backwards compatibility.
  84558. * @see https://doc.babylonjs.com/how_to/using_standard_rendering_pipeline
  84559. */
  84560. var StandardRenderingPipeline = /** @class */ (function (_super) {
  84561. __extends(StandardRenderingPipeline, _super);
  84562. /**
  84563. * Default pipeline should be used going forward but the standard pipeline will be kept for backwards compatibility.
  84564. * @constructor
  84565. * @param {string} name - The rendering pipeline name
  84566. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  84567. * @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)
  84568. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  84569. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  84570. */
  84571. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  84572. if (originalPostProcess === void 0) { originalPostProcess = null; }
  84573. var _this = _super.call(this, scene.getEngine(), name) || this;
  84574. /**
  84575. * Post-process used to down scale an image x4
  84576. */
  84577. _this.downSampleX4PostProcess = null;
  84578. /**
  84579. * Post-process used to calculate the illuminated surfaces controlled by a threshold
  84580. */
  84581. _this.brightPassPostProcess = null;
  84582. /**
  84583. * Post-process array storing all the horizontal blur post-processes used by the pipeline
  84584. */
  84585. _this.blurHPostProcesses = [];
  84586. /**
  84587. * Post-process array storing all the vertical blur post-processes used by the pipeline
  84588. */
  84589. _this.blurVPostProcesses = [];
  84590. /**
  84591. * Post-process used to add colors of 2 textures (typically brightness + real scene color)
  84592. */
  84593. _this.textureAdderPostProcess = null;
  84594. /**
  84595. * Post-process used to create volumetric lighting effect
  84596. */
  84597. _this.volumetricLightPostProcess = null;
  84598. /**
  84599. * Post-process used to smooth the previous volumetric light post-process on the X axis
  84600. */
  84601. _this.volumetricLightSmoothXPostProcess = null;
  84602. /**
  84603. * Post-process used to smooth the previous volumetric light post-process on the Y axis
  84604. */
  84605. _this.volumetricLightSmoothYPostProcess = null;
  84606. /**
  84607. * Post-process used to merge the volumetric light effect and the real scene color
  84608. */
  84609. _this.volumetricLightMergePostProces = null;
  84610. /**
  84611. * Post-process used to store the final volumetric light post-process (attach/detach for debug purpose)
  84612. */
  84613. _this.volumetricLightFinalPostProcess = null;
  84614. /**
  84615. * Base post-process used to calculate the average luminance of the final image for HDR
  84616. */
  84617. _this.luminancePostProcess = null;
  84618. /**
  84619. * Post-processes used to create down sample post-processes in order to get
  84620. * the average luminance of the final image for HDR
  84621. * Array of length "StandardRenderingPipeline.LuminanceSteps"
  84622. */
  84623. _this.luminanceDownSamplePostProcesses = [];
  84624. /**
  84625. * Post-process used to create a HDR effect (light adaptation)
  84626. */
  84627. _this.hdrPostProcess = null;
  84628. /**
  84629. * Post-process used to store the final texture adder post-process (attach/detach for debug purpose)
  84630. */
  84631. _this.textureAdderFinalPostProcess = null;
  84632. /**
  84633. * Post-process used to store the final lens flare post-process (attach/detach for debug purpose)
  84634. */
  84635. _this.lensFlareFinalPostProcess = null;
  84636. /**
  84637. * Post-process used to merge the final HDR post-process and the real scene color
  84638. */
  84639. _this.hdrFinalPostProcess = null;
  84640. /**
  84641. * Post-process used to create a lens flare effect
  84642. */
  84643. _this.lensFlarePostProcess = null;
  84644. /**
  84645. * Post-process that merges the result of the lens flare post-process and the real scene color
  84646. */
  84647. _this.lensFlareComposePostProcess = null;
  84648. /**
  84649. * Post-process used to create a motion blur effect
  84650. */
  84651. _this.motionBlurPostProcess = null;
  84652. /**
  84653. * Post-process used to create a depth of field effect
  84654. */
  84655. _this.depthOfFieldPostProcess = null;
  84656. /**
  84657. * The Fast Approximate Anti-Aliasing post process which attemps to remove aliasing from an image.
  84658. */
  84659. _this.fxaaPostProcess = null;
  84660. // Values
  84661. /**
  84662. * Represents the brightness threshold in order to configure the illuminated surfaces
  84663. */
  84664. _this.brightThreshold = 1.0;
  84665. /**
  84666. * Configures the blur intensity used for surexposed surfaces are highlighted surfaces (light halo)
  84667. */
  84668. _this.blurWidth = 512.0;
  84669. /**
  84670. * Sets if the blur for highlighted surfaces must be only horizontal
  84671. */
  84672. _this.horizontalBlur = false;
  84673. /**
  84674. * Sets the overall exposure used by the pipeline
  84675. */
  84676. _this.exposure = 1.0;
  84677. /**
  84678. * Texture used typically to simulate "dirty" on camera lens
  84679. */
  84680. _this.lensTexture = null;
  84681. /**
  84682. * Represents the offset coefficient based on Rayleigh principle. Typically in interval [-0.2, 0.2]
  84683. */
  84684. _this.volumetricLightCoefficient = 0.2;
  84685. /**
  84686. * The overall power of volumetric lights, typically in interval [0, 10] maximum
  84687. */
  84688. _this.volumetricLightPower = 4.0;
  84689. /**
  84690. * Used the set the blur intensity to smooth the volumetric lights
  84691. */
  84692. _this.volumetricLightBlurScale = 64.0;
  84693. /**
  84694. * Light (spot or directional) used to generate the volumetric lights rays
  84695. * The source light must have a shadow generate so the pipeline can get its
  84696. * depth map
  84697. */
  84698. _this.sourceLight = null;
  84699. /**
  84700. * For eye adaptation, represents the minimum luminance the eye can see
  84701. */
  84702. _this.hdrMinimumLuminance = 1.0;
  84703. /**
  84704. * For eye adaptation, represents the decrease luminance speed
  84705. */
  84706. _this.hdrDecreaseRate = 0.5;
  84707. /**
  84708. * For eye adaptation, represents the increase luminance speed
  84709. */
  84710. _this.hdrIncreaseRate = 0.5;
  84711. /**
  84712. * Lens color texture used by the lens flare effect. Mandatory if lens flare effect enabled
  84713. */
  84714. _this.lensColorTexture = null;
  84715. /**
  84716. * The overall strengh for the lens flare effect
  84717. */
  84718. _this.lensFlareStrength = 20.0;
  84719. /**
  84720. * Dispersion coefficient for lens flare ghosts
  84721. */
  84722. _this.lensFlareGhostDispersal = 1.4;
  84723. /**
  84724. * Main lens flare halo width
  84725. */
  84726. _this.lensFlareHaloWidth = 0.7;
  84727. /**
  84728. * Based on the lens distortion effect, defines how much the lens flare result
  84729. * is distorted
  84730. */
  84731. _this.lensFlareDistortionStrength = 16.0;
  84732. /**
  84733. * Lens star texture must be used to simulate rays on the flares and is available
  84734. * in the documentation
  84735. */
  84736. _this.lensStarTexture = null;
  84737. /**
  84738. * As the "lensTexture" (can be the same texture or different), it is used to apply the lens
  84739. * flare effect by taking account of the dirt texture
  84740. */
  84741. _this.lensFlareDirtTexture = null;
  84742. /**
  84743. * Represents the focal length for the depth of field effect
  84744. */
  84745. _this.depthOfFieldDistance = 10.0;
  84746. /**
  84747. * Represents the blur intensity for the blurred part of the depth of field effect
  84748. */
  84749. _this.depthOfFieldBlurWidth = 64.0;
  84750. /**
  84751. * For motion blur, defines how much the image is blurred by the movement
  84752. */
  84753. _this.motionStrength = 1.0;
  84754. /**
  84755. * List of animations for the pipeline (IAnimatable implementation)
  84756. */
  84757. _this.animations = [];
  84758. _this._currentDepthOfFieldSource = null;
  84759. _this._hdrCurrentLuminance = 1.0;
  84760. // Getters and setters
  84761. _this._bloomEnabled = false;
  84762. _this._depthOfFieldEnabled = false;
  84763. _this._vlsEnabled = false;
  84764. _this._lensFlareEnabled = false;
  84765. _this._hdrEnabled = false;
  84766. _this._motionBlurEnabled = false;
  84767. _this._fxaaEnabled = false;
  84768. _this._motionBlurSamples = 64.0;
  84769. _this._volumetricLightStepsCount = 50.0;
  84770. _this._samples = 1;
  84771. _this._cameras = cameras || [];
  84772. // Initialize
  84773. _this._scene = scene;
  84774. _this._basePostProcess = originalPostProcess;
  84775. _this._ratio = ratio;
  84776. // Misc
  84777. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  84778. // Finish
  84779. scene.postProcessRenderPipelineManager.addPipeline(_this);
  84780. _this._buildPipeline();
  84781. return _this;
  84782. }
  84783. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  84784. /**
  84785. * @ignore
  84786. * Specifies if the bloom pipeline is enabled
  84787. */
  84788. get: function () {
  84789. return this._bloomEnabled;
  84790. },
  84791. set: function (enabled) {
  84792. if (this._bloomEnabled === enabled) {
  84793. return;
  84794. }
  84795. this._bloomEnabled = enabled;
  84796. this._buildPipeline();
  84797. },
  84798. enumerable: true,
  84799. configurable: true
  84800. });
  84801. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  84802. /**
  84803. * @ignore
  84804. * Specifies if the depth of field pipeline is enabed
  84805. */
  84806. get: function () {
  84807. return this._depthOfFieldEnabled;
  84808. },
  84809. set: function (enabled) {
  84810. if (this._depthOfFieldEnabled === enabled) {
  84811. return;
  84812. }
  84813. this._depthOfFieldEnabled = enabled;
  84814. this._buildPipeline();
  84815. },
  84816. enumerable: true,
  84817. configurable: true
  84818. });
  84819. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  84820. /**
  84821. * @ignore
  84822. * Specifies if the lens flare pipeline is enabed
  84823. */
  84824. get: function () {
  84825. return this._lensFlareEnabled;
  84826. },
  84827. set: function (enabled) {
  84828. if (this._lensFlareEnabled === enabled) {
  84829. return;
  84830. }
  84831. this._lensFlareEnabled = enabled;
  84832. this._buildPipeline();
  84833. },
  84834. enumerable: true,
  84835. configurable: true
  84836. });
  84837. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  84838. /**
  84839. * @ignore
  84840. * Specifies if the HDR pipeline is enabled
  84841. */
  84842. get: function () {
  84843. return this._hdrEnabled;
  84844. },
  84845. set: function (enabled) {
  84846. if (this._hdrEnabled === enabled) {
  84847. return;
  84848. }
  84849. this._hdrEnabled = enabled;
  84850. this._buildPipeline();
  84851. },
  84852. enumerable: true,
  84853. configurable: true
  84854. });
  84855. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  84856. /**
  84857. * @ignore
  84858. * Specifies if the volumetric lights scattering effect is enabled
  84859. */
  84860. get: function () {
  84861. return this._vlsEnabled;
  84862. },
  84863. set: function (enabled) {
  84864. if (this._vlsEnabled === enabled) {
  84865. return;
  84866. }
  84867. if (enabled) {
  84868. var geometry = this._scene.enableGeometryBufferRenderer();
  84869. if (!geometry) {
  84870. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  84871. return;
  84872. }
  84873. }
  84874. this._vlsEnabled = enabled;
  84875. this._buildPipeline();
  84876. },
  84877. enumerable: true,
  84878. configurable: true
  84879. });
  84880. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  84881. /**
  84882. * @ignore
  84883. * Specifies if the motion blur effect is enabled
  84884. */
  84885. get: function () {
  84886. return this._motionBlurEnabled;
  84887. },
  84888. set: function (enabled) {
  84889. if (this._motionBlurEnabled === enabled) {
  84890. return;
  84891. }
  84892. this._motionBlurEnabled = enabled;
  84893. this._buildPipeline();
  84894. },
  84895. enumerable: true,
  84896. configurable: true
  84897. });
  84898. Object.defineProperty(StandardRenderingPipeline.prototype, "fxaaEnabled", {
  84899. /**
  84900. * Specifies if anti-aliasing is enabled
  84901. */
  84902. get: function () {
  84903. return this._fxaaEnabled;
  84904. },
  84905. set: function (enabled) {
  84906. if (this._fxaaEnabled === enabled) {
  84907. return;
  84908. }
  84909. this._fxaaEnabled = enabled;
  84910. this._buildPipeline();
  84911. },
  84912. enumerable: true,
  84913. configurable: true
  84914. });
  84915. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  84916. /**
  84917. * Specifies the number of steps used to calculate the volumetric lights
  84918. * Typically in interval [50, 200]
  84919. */
  84920. get: function () {
  84921. return this._volumetricLightStepsCount;
  84922. },
  84923. set: function (count) {
  84924. if (this.volumetricLightPostProcess) {
  84925. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  84926. }
  84927. this._volumetricLightStepsCount = count;
  84928. },
  84929. enumerable: true,
  84930. configurable: true
  84931. });
  84932. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  84933. /**
  84934. * Specifies the number of samples used for the motion blur effect
  84935. * Typically in interval [16, 64]
  84936. */
  84937. get: function () {
  84938. return this._motionBlurSamples;
  84939. },
  84940. set: function (samples) {
  84941. if (this.motionBlurPostProcess) {
  84942. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  84943. }
  84944. this._motionBlurSamples = samples;
  84945. },
  84946. enumerable: true,
  84947. configurable: true
  84948. });
  84949. Object.defineProperty(StandardRenderingPipeline.prototype, "samples", {
  84950. /**
  84951. * Specifies MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  84952. */
  84953. get: function () {
  84954. return this._samples;
  84955. },
  84956. set: function (sampleCount) {
  84957. if (this._samples === sampleCount) {
  84958. return;
  84959. }
  84960. this._samples = sampleCount;
  84961. this._buildPipeline();
  84962. },
  84963. enumerable: true,
  84964. configurable: true
  84965. });
  84966. StandardRenderingPipeline.prototype._buildPipeline = function () {
  84967. var _this = this;
  84968. var ratio = this._ratio;
  84969. var scene = this._scene;
  84970. this._disposePostProcesses();
  84971. this._reset();
  84972. // Create pass post-process
  84973. if (!this._basePostProcess) {
  84974. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  84975. this.originalPostProcess.onApply = function (effect) {
  84976. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  84977. };
  84978. }
  84979. else {
  84980. this.originalPostProcess = this._basePostProcess;
  84981. }
  84982. if (this._bloomEnabled || this._vlsEnabled || this._lensFlareEnabled || this._depthOfFieldEnabled || this._motionBlurEnabled) {
  84983. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  84984. }
  84985. this._currentDepthOfFieldSource = this.originalPostProcess;
  84986. if (this._bloomEnabled) {
  84987. // Create down sample X4 post-process
  84988. this._createDownSampleX4PostProcess(scene, ratio / 2);
  84989. // Create bright pass post-process
  84990. this._createBrightPassPostProcess(scene, ratio / 2);
  84991. // Create gaussian blur post-processes (down sampling blurs)
  84992. this._createBlurPostProcesses(scene, ratio / 4, 1);
  84993. // Create texture adder post-process
  84994. this._createTextureAdderPostProcess(scene, ratio);
  84995. // Create depth-of-field source post-process
  84996. 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);
  84997. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  84998. }
  84999. if (this._vlsEnabled) {
  85000. // Create volumetric light
  85001. this._createVolumetricLightPostProcess(scene, ratio);
  85002. // Create volumetric light final post-process
  85003. 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);
  85004. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  85005. }
  85006. if (this._lensFlareEnabled) {
  85007. // Create lens flare post-process
  85008. this._createLensFlarePostProcess(scene, ratio);
  85009. // Create depth-of-field source post-process post lens-flare and disable it now
  85010. 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);
  85011. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  85012. }
  85013. if (this._hdrEnabled) {
  85014. // Create luminance
  85015. this._createLuminancePostProcesses(scene, this._floatTextureType);
  85016. // Create HDR
  85017. this._createHdrPostProcess(scene, ratio);
  85018. // Create depth-of-field source post-process post hdr and disable it now
  85019. 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);
  85020. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  85021. }
  85022. if (this._depthOfFieldEnabled) {
  85023. // Create gaussian blur used by depth-of-field
  85024. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  85025. // Create depth-of-field post-process
  85026. this._createDepthOfFieldPostProcess(scene, ratio);
  85027. }
  85028. if (this._motionBlurEnabled) {
  85029. // Create motion blur post-process
  85030. this._createMotionBlurPostProcess(scene, ratio);
  85031. }
  85032. if (this._fxaaEnabled) {
  85033. // Create fxaa post-process
  85034. this.fxaaPostProcess = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  85035. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRFxaa", function () { return _this.fxaaPostProcess; }, true));
  85036. }
  85037. if (this._cameras !== null) {
  85038. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  85039. }
  85040. if (!this._enableMSAAOnFirstPostProcess(this._samples) && this._samples > 1) {
  85041. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  85042. }
  85043. };
  85044. // Down Sample X4 Post-Processs
  85045. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  85046. var _this = this;
  85047. var downSampleX4Offsets = new Array(32);
  85048. 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);
  85049. this.downSampleX4PostProcess.onApply = function (effect) {
  85050. var id = 0;
  85051. var width = _this.downSampleX4PostProcess.width;
  85052. var height = _this.downSampleX4PostProcess.height;
  85053. for (var i = -2; i < 2; i++) {
  85054. for (var j = -2; j < 2; j++) {
  85055. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  85056. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  85057. id += 2;
  85058. }
  85059. }
  85060. effect.setArray2("dsOffsets", downSampleX4Offsets);
  85061. };
  85062. // Add to pipeline
  85063. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  85064. };
  85065. // Brightpass Post-Process
  85066. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  85067. var _this = this;
  85068. var brightOffsets = new Array(8);
  85069. 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);
  85070. this.brightPassPostProcess.onApply = function (effect) {
  85071. var sU = (1.0 / _this.brightPassPostProcess.width);
  85072. var sV = (1.0 / _this.brightPassPostProcess.height);
  85073. brightOffsets[0] = -0.5 * sU;
  85074. brightOffsets[1] = 0.5 * sV;
  85075. brightOffsets[2] = 0.5 * sU;
  85076. brightOffsets[3] = 0.5 * sV;
  85077. brightOffsets[4] = -0.5 * sU;
  85078. brightOffsets[5] = -0.5 * sV;
  85079. brightOffsets[6] = 0.5 * sU;
  85080. brightOffsets[7] = -0.5 * sV;
  85081. effect.setArray2("dsOffsets", brightOffsets);
  85082. effect.setFloat("brightThreshold", _this.brightThreshold);
  85083. };
  85084. // Add to pipeline
  85085. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  85086. };
  85087. // Create blur H&V post-processes
  85088. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  85089. var _this = this;
  85090. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  85091. var engine = scene.getEngine();
  85092. 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);
  85093. 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);
  85094. blurX.onActivateObservable.add(function () {
  85095. var dw = blurX.width / engine.getRenderWidth();
  85096. blurX.kernel = _this[blurWidthKey] * dw;
  85097. });
  85098. blurY.onActivateObservable.add(function () {
  85099. var dw = blurY.height / engine.getRenderHeight();
  85100. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  85101. });
  85102. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  85103. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  85104. this.blurHPostProcesses.push(blurX);
  85105. this.blurVPostProcesses.push(blurY);
  85106. };
  85107. // Create texture adder post-process
  85108. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  85109. var _this = this;
  85110. 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);
  85111. this.textureAdderPostProcess.onApply = function (effect) {
  85112. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  85113. effect.setTexture("lensSampler", _this.lensTexture);
  85114. effect.setFloat("exposure", _this.exposure);
  85115. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  85116. };
  85117. // Add to pipeline
  85118. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  85119. };
  85120. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  85121. var _this = this;
  85122. var geometryRenderer = scene.enableGeometryBufferRenderer();
  85123. geometryRenderer.enablePosition = true;
  85124. var geometry = geometryRenderer.getGBuffer();
  85125. // Base post-process
  85126. 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));
  85127. var depthValues = BABYLON.Vector2.Zero();
  85128. this.volumetricLightPostProcess.onApply = function (effect) {
  85129. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  85130. var generator = _this.sourceLight.getShadowGenerator();
  85131. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  85132. effect.setTexture("positionSampler", geometry.textures[2]);
  85133. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  85134. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  85135. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  85136. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  85137. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  85138. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  85139. depthValues.x = _this.sourceLight.getDepthMinZ(_this._scene.activeCamera);
  85140. depthValues.y = _this.sourceLight.getDepthMaxZ(_this._scene.activeCamera);
  85141. effect.setVector2("depthValues", depthValues);
  85142. }
  85143. };
  85144. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  85145. // Smooth
  85146. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  85147. // Merge
  85148. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  85149. this.volumetricLightMergePostProces.onApply = function (effect) {
  85150. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  85151. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  85152. };
  85153. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  85154. };
  85155. // Create luminance
  85156. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  85157. var _this = this;
  85158. // Create luminance
  85159. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  85160. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  85161. var offsets = [];
  85162. this.luminancePostProcess.onApply = function (effect) {
  85163. var sU = (1.0 / _this.luminancePostProcess.width);
  85164. var sV = (1.0 / _this.luminancePostProcess.height);
  85165. offsets[0] = -0.5 * sU;
  85166. offsets[1] = 0.5 * sV;
  85167. offsets[2] = 0.5 * sU;
  85168. offsets[3] = 0.5 * sV;
  85169. offsets[4] = -0.5 * sU;
  85170. offsets[5] = -0.5 * sV;
  85171. offsets[6] = 0.5 * sU;
  85172. offsets[7] = -0.5 * sV;
  85173. effect.setArray2("lumOffsets", offsets);
  85174. };
  85175. // Add to pipeline
  85176. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  85177. // Create down sample luminance
  85178. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  85179. var size = Math.pow(3, i);
  85180. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  85181. if (i === 0) {
  85182. defines += "#define FINAL_DOWN_SAMPLER";
  85183. }
  85184. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  85185. this.luminanceDownSamplePostProcesses.push(postProcess);
  85186. }
  85187. // Create callbacks and add effects
  85188. var lastLuminance = this.luminancePostProcess;
  85189. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  85190. var downSampleOffsets = new Array(18);
  85191. pp.onApply = function (effect) {
  85192. if (!lastLuminance) {
  85193. return;
  85194. }
  85195. var id = 0;
  85196. for (var x = -1; x < 2; x++) {
  85197. for (var y = -1; y < 2; y++) {
  85198. downSampleOffsets[id] = x / lastLuminance.width;
  85199. downSampleOffsets[id + 1] = y / lastLuminance.height;
  85200. id += 2;
  85201. }
  85202. }
  85203. effect.setArray2("dsOffsets", downSampleOffsets);
  85204. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  85205. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  85206. lastLuminance = _this.luminancePostProcess;
  85207. }
  85208. else {
  85209. lastLuminance = pp;
  85210. }
  85211. };
  85212. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  85213. pp.onAfterRender = function (effect) {
  85214. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  85215. 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);
  85216. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  85217. };
  85218. }
  85219. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  85220. });
  85221. };
  85222. // Create HDR post-process
  85223. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  85224. var _this = this;
  85225. 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);
  85226. var outputLiminance = 1;
  85227. var time = 0;
  85228. var lastTime = 0;
  85229. this.hdrPostProcess.onApply = function (effect) {
  85230. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  85231. time += scene.getEngine().getDeltaTime();
  85232. if (outputLiminance < 0) {
  85233. outputLiminance = _this._hdrCurrentLuminance;
  85234. }
  85235. else {
  85236. var dt = (lastTime - time) / 1000.0;
  85237. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  85238. outputLiminance += _this.hdrDecreaseRate * dt;
  85239. }
  85240. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  85241. outputLiminance -= _this.hdrIncreaseRate * dt;
  85242. }
  85243. else {
  85244. outputLiminance = _this._hdrCurrentLuminance;
  85245. }
  85246. }
  85247. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  85248. effect.setFloat("averageLuminance", outputLiminance);
  85249. lastTime = time;
  85250. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  85251. };
  85252. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  85253. };
  85254. // Create lens flare post-process
  85255. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  85256. var _this = this;
  85257. 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);
  85258. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  85259. this._createBlurPostProcesses(scene, ratio / 4, 2);
  85260. 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);
  85261. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  85262. var resolution = new BABYLON.Vector2(0, 0);
  85263. // Lens flare
  85264. this.lensFlarePostProcess.onApply = function (effect) {
  85265. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  85266. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  85267. effect.setFloat("strength", _this.lensFlareStrength);
  85268. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  85269. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  85270. // Shift
  85271. resolution.x = _this.lensFlarePostProcess.width;
  85272. resolution.y = _this.lensFlarePostProcess.height;
  85273. effect.setVector2("resolution", resolution);
  85274. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  85275. };
  85276. // Compose
  85277. 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);
  85278. 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);
  85279. this.lensFlareComposePostProcess.onApply = function (effect) {
  85280. if (!_this._scene.activeCamera) {
  85281. return;
  85282. }
  85283. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  85284. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  85285. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  85286. // Lens start rotation matrix
  85287. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  85288. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  85289. 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));
  85290. camRot *= 4.0;
  85291. 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);
  85292. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  85293. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  85294. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  85295. };
  85296. };
  85297. // Create depth-of-field post-process
  85298. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  85299. var _this = this;
  85300. 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);
  85301. this.depthOfFieldPostProcess.onApply = function (effect) {
  85302. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  85303. effect.setTexture("depthSampler", _this._getDepthTexture());
  85304. effect.setFloat("distance", _this.depthOfFieldDistance);
  85305. };
  85306. // Add to pipeline
  85307. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  85308. };
  85309. // Create motion blur post-process
  85310. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  85311. var _this = this;
  85312. 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);
  85313. var motionScale = 0;
  85314. var prevViewProjection = BABYLON.Matrix.Identity();
  85315. var invViewProjection = BABYLON.Matrix.Identity();
  85316. var viewProjection = BABYLON.Matrix.Identity();
  85317. var screenSize = BABYLON.Vector2.Zero();
  85318. this.motionBlurPostProcess.onApply = function (effect) {
  85319. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  85320. viewProjection.invertToRef(invViewProjection);
  85321. effect.setMatrix("inverseViewProjection", invViewProjection);
  85322. effect.setMatrix("prevViewProjection", prevViewProjection);
  85323. prevViewProjection = viewProjection;
  85324. screenSize.x = _this.motionBlurPostProcess.width;
  85325. screenSize.y = _this.motionBlurPostProcess.height;
  85326. effect.setVector2("screenSize", screenSize);
  85327. motionScale = scene.getEngine().getFps() / 60.0;
  85328. effect.setFloat("motionScale", motionScale);
  85329. effect.setFloat("motionStrength", _this.motionStrength);
  85330. effect.setTexture("depthSampler", _this._getDepthTexture());
  85331. };
  85332. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  85333. };
  85334. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  85335. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  85336. var renderer = this._scene.enableGeometryBufferRenderer();
  85337. return renderer.getGBuffer().textures[0];
  85338. }
  85339. return this._scene.enableDepthRenderer().getDepthMap();
  85340. };
  85341. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  85342. for (var i = 0; i < this._cameras.length; i++) {
  85343. var camera = this._cameras[i];
  85344. if (this.originalPostProcess) {
  85345. this.originalPostProcess.dispose(camera);
  85346. }
  85347. if (this.downSampleX4PostProcess) {
  85348. this.downSampleX4PostProcess.dispose(camera);
  85349. }
  85350. if (this.brightPassPostProcess) {
  85351. this.brightPassPostProcess.dispose(camera);
  85352. }
  85353. if (this.textureAdderPostProcess) {
  85354. this.textureAdderPostProcess.dispose(camera);
  85355. }
  85356. if (this.textureAdderFinalPostProcess) {
  85357. this.textureAdderFinalPostProcess.dispose(camera);
  85358. }
  85359. if (this.volumetricLightPostProcess) {
  85360. this.volumetricLightPostProcess.dispose(camera);
  85361. }
  85362. if (this.volumetricLightSmoothXPostProcess) {
  85363. this.volumetricLightSmoothXPostProcess.dispose(camera);
  85364. }
  85365. if (this.volumetricLightSmoothYPostProcess) {
  85366. this.volumetricLightSmoothYPostProcess.dispose(camera);
  85367. }
  85368. if (this.volumetricLightMergePostProces) {
  85369. this.volumetricLightMergePostProces.dispose(camera);
  85370. }
  85371. if (this.volumetricLightFinalPostProcess) {
  85372. this.volumetricLightFinalPostProcess.dispose(camera);
  85373. }
  85374. if (this.lensFlarePostProcess) {
  85375. this.lensFlarePostProcess.dispose(camera);
  85376. }
  85377. if (this.lensFlareComposePostProcess) {
  85378. this.lensFlareComposePostProcess.dispose(camera);
  85379. }
  85380. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  85381. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  85382. }
  85383. if (this.luminancePostProcess) {
  85384. this.luminancePostProcess.dispose(camera);
  85385. }
  85386. if (this.hdrPostProcess) {
  85387. this.hdrPostProcess.dispose(camera);
  85388. }
  85389. if (this.hdrFinalPostProcess) {
  85390. this.hdrFinalPostProcess.dispose(camera);
  85391. }
  85392. if (this.depthOfFieldPostProcess) {
  85393. this.depthOfFieldPostProcess.dispose(camera);
  85394. }
  85395. if (this.motionBlurPostProcess) {
  85396. this.motionBlurPostProcess.dispose(camera);
  85397. }
  85398. if (this.fxaaPostProcess) {
  85399. this.fxaaPostProcess.dispose(camera);
  85400. }
  85401. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  85402. this.blurHPostProcesses[j].dispose(camera);
  85403. }
  85404. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  85405. this.blurVPostProcesses[j].dispose(camera);
  85406. }
  85407. }
  85408. this.originalPostProcess = null;
  85409. this.downSampleX4PostProcess = null;
  85410. this.brightPassPostProcess = null;
  85411. this.textureAdderPostProcess = null;
  85412. this.textureAdderFinalPostProcess = null;
  85413. this.volumetricLightPostProcess = null;
  85414. this.volumetricLightSmoothXPostProcess = null;
  85415. this.volumetricLightSmoothYPostProcess = null;
  85416. this.volumetricLightMergePostProces = null;
  85417. this.volumetricLightFinalPostProcess = null;
  85418. this.lensFlarePostProcess = null;
  85419. this.lensFlareComposePostProcess = null;
  85420. this.luminancePostProcess = null;
  85421. this.hdrPostProcess = null;
  85422. this.hdrFinalPostProcess = null;
  85423. this.depthOfFieldPostProcess = null;
  85424. this.motionBlurPostProcess = null;
  85425. this.fxaaPostProcess = null;
  85426. this.luminanceDownSamplePostProcesses = [];
  85427. this.blurHPostProcesses = [];
  85428. this.blurVPostProcesses = [];
  85429. };
  85430. /**
  85431. * Dispose of the pipeline and stop all post processes
  85432. */
  85433. StandardRenderingPipeline.prototype.dispose = function () {
  85434. this._disposePostProcesses();
  85435. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  85436. _super.prototype.dispose.call(this);
  85437. };
  85438. /**
  85439. * Serialize the rendering pipeline (Used when exporting)
  85440. * @returns the serialized object
  85441. */
  85442. StandardRenderingPipeline.prototype.serialize = function () {
  85443. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  85444. if (this.sourceLight) {
  85445. serializationObject.sourceLightId = this.sourceLight.id;
  85446. }
  85447. serializationObject.customType = "StandardRenderingPipeline";
  85448. return serializationObject;
  85449. };
  85450. /**
  85451. * Parse the serialized pipeline
  85452. * @param source Source pipeline.
  85453. * @param scene The scene to load the pipeline to.
  85454. * @param rootUrl The URL of the serialized pipeline.
  85455. * @returns An instantiated pipeline from the serialized object.
  85456. */
  85457. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  85458. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  85459. if (source.sourceLightId) {
  85460. p.sourceLight = scene.getLightByID(source.sourceLightId);
  85461. }
  85462. return p;
  85463. };
  85464. /**
  85465. * Luminance steps
  85466. */
  85467. StandardRenderingPipeline.LuminanceSteps = 6;
  85468. __decorate([
  85469. BABYLON.serialize()
  85470. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  85471. __decorate([
  85472. BABYLON.serialize()
  85473. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  85474. __decorate([
  85475. BABYLON.serialize()
  85476. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  85477. __decorate([
  85478. BABYLON.serialize()
  85479. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  85480. __decorate([
  85481. BABYLON.serializeAsTexture("lensTexture")
  85482. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  85483. __decorate([
  85484. BABYLON.serialize()
  85485. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  85486. __decorate([
  85487. BABYLON.serialize()
  85488. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  85489. __decorate([
  85490. BABYLON.serialize()
  85491. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  85492. __decorate([
  85493. BABYLON.serialize()
  85494. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  85495. __decorate([
  85496. BABYLON.serialize()
  85497. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  85498. __decorate([
  85499. BABYLON.serialize()
  85500. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  85501. __decorate([
  85502. BABYLON.serializeAsTexture("lensColorTexture")
  85503. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  85504. __decorate([
  85505. BABYLON.serialize()
  85506. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  85507. __decorate([
  85508. BABYLON.serialize()
  85509. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  85510. __decorate([
  85511. BABYLON.serialize()
  85512. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  85513. __decorate([
  85514. BABYLON.serialize()
  85515. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  85516. __decorate([
  85517. BABYLON.serializeAsTexture("lensStarTexture")
  85518. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  85519. __decorate([
  85520. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  85521. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  85522. __decorate([
  85523. BABYLON.serialize()
  85524. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  85525. __decorate([
  85526. BABYLON.serialize()
  85527. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  85528. __decorate([
  85529. BABYLON.serialize()
  85530. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  85531. __decorate([
  85532. BABYLON.serialize()
  85533. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  85534. __decorate([
  85535. BABYLON.serialize()
  85536. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  85537. __decorate([
  85538. BABYLON.serialize()
  85539. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  85540. __decorate([
  85541. BABYLON.serialize()
  85542. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  85543. __decorate([
  85544. BABYLON.serialize()
  85545. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  85546. __decorate([
  85547. BABYLON.serialize()
  85548. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  85549. __decorate([
  85550. BABYLON.serialize()
  85551. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  85552. __decorate([
  85553. BABYLON.serialize()
  85554. ], StandardRenderingPipeline.prototype, "fxaaEnabled", null);
  85555. __decorate([
  85556. BABYLON.serialize()
  85557. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  85558. __decorate([
  85559. BABYLON.serialize()
  85560. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  85561. __decorate([
  85562. BABYLON.serialize()
  85563. ], StandardRenderingPipeline.prototype, "samples", null);
  85564. return StandardRenderingPipeline;
  85565. }(BABYLON.PostProcessRenderPipeline));
  85566. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  85567. })(BABYLON || (BABYLON = {}));
  85568. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  85569. var BABYLON;
  85570. (function (BABYLON) {
  85571. /**
  85572. * Fxaa post process
  85573. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#fxaa
  85574. */
  85575. var FxaaPostProcess = /** @class */ (function (_super) {
  85576. __extends(FxaaPostProcess, _super);
  85577. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  85578. if (camera === void 0) { camera = null; }
  85579. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  85580. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  85581. var defines = _this._getDefines();
  85582. _this.updateEffect(defines);
  85583. _this.onApplyObservable.add(function (effect) {
  85584. var texelSize = _this.texelSize;
  85585. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  85586. });
  85587. return _this;
  85588. }
  85589. FxaaPostProcess.prototype._getDefines = function () {
  85590. var engine = this.getEngine();
  85591. if (!engine) {
  85592. return null;
  85593. }
  85594. var glInfo = engine.getGlInfo();
  85595. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  85596. return "#define MALI 1\n";
  85597. }
  85598. return null;
  85599. };
  85600. return FxaaPostProcess;
  85601. }(BABYLON.PostProcess));
  85602. BABYLON.FxaaPostProcess = FxaaPostProcess;
  85603. })(BABYLON || (BABYLON = {}));
  85604. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  85605. var BABYLON;
  85606. (function (BABYLON) {
  85607. /**
  85608. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  85609. */
  85610. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  85611. __extends(ChromaticAberrationPostProcess, _super);
  85612. /**
  85613. * Creates a new instance ChromaticAberrationPostProcess
  85614. * @param name The name of the effect.
  85615. * @param screenWidth The width of the screen to apply the effect on.
  85616. * @param screenHeight The height of the screen to apply the effect on.
  85617. * @param options The required width/height ratio to downsize to before computing the render pass.
  85618. * @param camera The camera to apply the render pass to.
  85619. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  85620. * @param engine The engine which the post process will be applied. (default: current engine)
  85621. * @param reusable If the post process can be reused on the same frame. (default: false)
  85622. * @param textureType Type of textures used when performing the post process. (default: 0)
  85623. * @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)
  85624. */
  85625. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  85626. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  85627. if (blockCompilation === void 0) { blockCompilation = false; }
  85628. 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;
  85629. /**
  85630. * The amount of seperation of rgb channels (default: 30)
  85631. */
  85632. _this.aberrationAmount = 30;
  85633. /**
  85634. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  85635. */
  85636. _this.radialIntensity = 0;
  85637. /**
  85638. * 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))
  85639. */
  85640. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  85641. /**
  85642. * 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))
  85643. */
  85644. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  85645. _this.onApplyObservable.add(function (effect) {
  85646. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  85647. effect.setFloat('screen_width', screenWidth);
  85648. effect.setFloat('screen_height', screenHeight);
  85649. effect.setFloat('radialIntensity', _this.radialIntensity);
  85650. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  85651. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  85652. });
  85653. return _this;
  85654. }
  85655. return ChromaticAberrationPostProcess;
  85656. }(BABYLON.PostProcess));
  85657. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  85658. })(BABYLON || (BABYLON = {}));
  85659. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  85660. var BABYLON;
  85661. (function (BABYLON) {
  85662. /**
  85663. * The GrainPostProcess adds noise to the image at mid luminance levels
  85664. */
  85665. var GrainPostProcess = /** @class */ (function (_super) {
  85666. __extends(GrainPostProcess, _super);
  85667. /**
  85668. * Creates a new instance of @see GrainPostProcess
  85669. * @param name The name of the effect.
  85670. * @param options The required width/height ratio to downsize to before computing the render pass.
  85671. * @param camera The camera to apply the render pass to.
  85672. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  85673. * @param engine The engine which the post process will be applied. (default: current engine)
  85674. * @param reusable If the post process can be reused on the same frame. (default: false)
  85675. * @param textureType Type of textures used when performing the post process. (default: 0)
  85676. * @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)
  85677. */
  85678. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  85679. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  85680. if (blockCompilation === void 0) { blockCompilation = false; }
  85681. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  85682. /**
  85683. * The intensity of the grain added (default: 30)
  85684. */
  85685. _this.intensity = 30;
  85686. /**
  85687. * If the grain should be randomized on every frame
  85688. */
  85689. _this.animated = false;
  85690. _this.onApplyObservable.add(function (effect) {
  85691. effect.setFloat('intensity', _this.intensity);
  85692. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  85693. });
  85694. return _this;
  85695. }
  85696. return GrainPostProcess;
  85697. }(BABYLON.PostProcess));
  85698. BABYLON.GrainPostProcess = GrainPostProcess;
  85699. })(BABYLON || (BABYLON = {}));
  85700. //# sourceMappingURL=babylon.grainPostProcess.js.map
  85701. var BABYLON;
  85702. (function (BABYLON) {
  85703. /**
  85704. * The SharpenPostProcess applies a sharpen kernel to every pixel
  85705. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  85706. */
  85707. var SharpenPostProcess = /** @class */ (function (_super) {
  85708. __extends(SharpenPostProcess, _super);
  85709. /**
  85710. * Creates a new instance ConvolutionPostProcess
  85711. * @param name The name of the effect.
  85712. * @param options The required width/height ratio to downsize to before computing the render pass.
  85713. * @param camera The camera to apply the render pass to.
  85714. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  85715. * @param engine The engine which the post process will be applied. (default: current engine)
  85716. * @param reusable If the post process can be reused on the same frame. (default: false)
  85717. * @param textureType Type of textures used when performing the post process. (default: 0)
  85718. * @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)
  85719. */
  85720. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  85721. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  85722. if (blockCompilation === void 0) { blockCompilation = false; }
  85723. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  85724. /**
  85725. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  85726. */
  85727. _this.colorAmount = 1.0;
  85728. /**
  85729. * How much sharpness should be applied (default: 0.3)
  85730. */
  85731. _this.edgeAmount = 0.3;
  85732. _this.onApply = function (effect) {
  85733. effect.setFloat2("screenSize", _this.width, _this.height);
  85734. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  85735. };
  85736. return _this;
  85737. }
  85738. return SharpenPostProcess;
  85739. }(BABYLON.PostProcess));
  85740. BABYLON.SharpenPostProcess = SharpenPostProcess;
  85741. })(BABYLON || (BABYLON = {}));
  85742. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  85743. var BABYLON;
  85744. (function (BABYLON) {
  85745. /**
  85746. * The Blur Post Process which blurs an image based on a kernel and direction.
  85747. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  85748. */
  85749. var BlurPostProcess = /** @class */ (function (_super) {
  85750. __extends(BlurPostProcess, _super);
  85751. /**
  85752. * Creates a new instance BlurPostProcess
  85753. * @param name The name of the effect.
  85754. * @param direction The direction in which to blur the image.
  85755. * @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.
  85756. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  85757. * @param camera The camera to apply the render pass to.
  85758. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  85759. * @param engine The engine which the post process will be applied. (default: current engine)
  85760. * @param reusable If the post process can be reused on the same frame. (default: false)
  85761. * @param textureType Type of textures used when performing the post process. (default: 0)
  85762. * @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)
  85763. */
  85764. function BlurPostProcess(name,
  85765. /** The direction in which to blur the image. */
  85766. direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  85767. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  85768. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  85769. if (defines === void 0) { defines = ""; }
  85770. if (blockCompilation === void 0) { blockCompilation = false; }
  85771. 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;
  85772. _this.direction = direction;
  85773. _this.blockCompilation = blockCompilation;
  85774. _this._packedFloat = false;
  85775. _this._staticDefines = "";
  85776. _this._staticDefines = defines;
  85777. _this.onApplyObservable.add(function (effect) {
  85778. if (_this._outputTexture) {
  85779. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  85780. }
  85781. else {
  85782. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  85783. }
  85784. });
  85785. _this.kernel = kernel;
  85786. return _this;
  85787. }
  85788. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  85789. /**
  85790. * Gets the length in pixels of the blur sample region
  85791. */
  85792. get: function () {
  85793. return this._idealKernel;
  85794. },
  85795. /**
  85796. * Sets the length in pixels of the blur sample region
  85797. */
  85798. set: function (v) {
  85799. if (this._idealKernel === v) {
  85800. return;
  85801. }
  85802. v = Math.max(v, 1);
  85803. this._idealKernel = v;
  85804. this._kernel = this._nearestBestKernel(v);
  85805. if (!this.blockCompilation) {
  85806. this._updateParameters();
  85807. }
  85808. },
  85809. enumerable: true,
  85810. configurable: true
  85811. });
  85812. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  85813. /**
  85814. * Gets wether or not the blur is unpacking/repacking floats
  85815. */
  85816. get: function () {
  85817. return this._packedFloat;
  85818. },
  85819. /**
  85820. * Sets wether or not the blur needs to unpack/repack floats
  85821. */
  85822. set: function (v) {
  85823. if (this._packedFloat === v) {
  85824. return;
  85825. }
  85826. this._packedFloat = v;
  85827. if (!this.blockCompilation) {
  85828. this._updateParameters();
  85829. }
  85830. },
  85831. enumerable: true,
  85832. configurable: true
  85833. });
  85834. /**
  85835. * Updates the effect with the current post process compile time values and recompiles the shader.
  85836. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  85837. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  85838. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  85839. * @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
  85840. * @param onCompiled Called when the shader has been compiled.
  85841. * @param onError Called if there is an error when compiling a shader.
  85842. */
  85843. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  85844. if (defines === void 0) { defines = null; }
  85845. if (uniforms === void 0) { uniforms = null; }
  85846. if (samplers === void 0) { samplers = null; }
  85847. this._updateParameters(onCompiled, onError);
  85848. };
  85849. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  85850. // Generate sampling offsets and weights
  85851. var N = this._kernel;
  85852. var centerIndex = (N - 1) / 2;
  85853. // Generate Gaussian sampling weights over kernel
  85854. var offsets = [];
  85855. var weights = [];
  85856. var totalWeight = 0;
  85857. for (var i = 0; i < N; i++) {
  85858. var u = i / (N - 1);
  85859. var w = this._gaussianWeight(u * 2.0 - 1);
  85860. offsets[i] = (i - centerIndex);
  85861. weights[i] = w;
  85862. totalWeight += w;
  85863. }
  85864. // Normalize weights
  85865. for (var i = 0; i < weights.length; i++) {
  85866. weights[i] /= totalWeight;
  85867. }
  85868. // Optimize: combine samples to take advantage of hardware linear sampling
  85869. // Walk from left to center, combining pairs (symmetrically)
  85870. var linearSamplingWeights = [];
  85871. var linearSamplingOffsets = [];
  85872. var linearSamplingMap = [];
  85873. for (var i = 0; i <= centerIndex; i += 2) {
  85874. var j = Math.min(i + 1, Math.floor(centerIndex));
  85875. var singleCenterSample = i === j;
  85876. if (singleCenterSample) {
  85877. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  85878. }
  85879. else {
  85880. var sharedCell = j === centerIndex;
  85881. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  85882. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  85883. if (offsetLinear === 0) {
  85884. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  85885. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  85886. }
  85887. else {
  85888. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  85889. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  85890. }
  85891. }
  85892. }
  85893. for (var i = 0; i < linearSamplingMap.length; i++) {
  85894. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  85895. linearSamplingWeights[i] = linearSamplingMap[i].w;
  85896. }
  85897. // Replace with optimized
  85898. offsets = linearSamplingOffsets;
  85899. weights = linearSamplingWeights;
  85900. // Generate shaders
  85901. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  85902. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  85903. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  85904. var defines = "";
  85905. defines += this._staticDefines;
  85906. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  85907. if (this._staticDefines.indexOf("DOF") != -1) {
  85908. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  85909. varyingCount--;
  85910. }
  85911. for (var i = 0; i < varyingCount; i++) {
  85912. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  85913. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  85914. }
  85915. var depCount = 0;
  85916. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  85917. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  85918. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  85919. depCount++;
  85920. }
  85921. if (this.packedFloat) {
  85922. defines += "#define PACKEDFLOAT 1";
  85923. }
  85924. this.blockCompilation = false;
  85925. _super.prototype.updateEffect.call(this, defines, null, null, {
  85926. varyingCount: varyingCount,
  85927. depCount: depCount
  85928. }, onCompiled, onError);
  85929. };
  85930. /**
  85931. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  85932. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  85933. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  85934. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  85935. * The gaps between physical kernels are compensated for in the weighting of the samples
  85936. * @param idealKernel Ideal blur kernel.
  85937. * @return Nearest best kernel.
  85938. */
  85939. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  85940. var v = Math.round(idealKernel);
  85941. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  85942. var k = _a[_i];
  85943. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  85944. return Math.max(k, 3);
  85945. }
  85946. }
  85947. return Math.max(v, 3);
  85948. };
  85949. /**
  85950. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  85951. * @param x The point on the Gaussian distribution to sample.
  85952. * @return the value of the Gaussian function at x.
  85953. */
  85954. BlurPostProcess.prototype._gaussianWeight = function (x) {
  85955. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  85956. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  85957. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  85958. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  85959. // truncated at around 1.3% of peak strength.
  85960. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  85961. var sigma = (1 / 3);
  85962. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  85963. var exponent = -((x * x) / (2.0 * sigma * sigma));
  85964. var weight = (1.0 / denominator) * Math.exp(exponent);
  85965. return weight;
  85966. };
  85967. /**
  85968. * Generates a string that can be used as a floating point number in GLSL.
  85969. * @param x Value to print.
  85970. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  85971. * @return GLSL float string.
  85972. */
  85973. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  85974. if (decimalFigures === void 0) { decimalFigures = 8; }
  85975. return x.toFixed(decimalFigures).replace(/0+$/, '');
  85976. };
  85977. return BlurPostProcess;
  85978. }(BABYLON.PostProcess));
  85979. BABYLON.BlurPostProcess = BlurPostProcess;
  85980. })(BABYLON || (BABYLON = {}));
  85981. //# sourceMappingURL=babylon.blurPostProcess.js.map
  85982. var BABYLON;
  85983. (function (BABYLON) {
  85984. /**
  85985. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  85986. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  85987. * based on samples that have a large difference in distance than the center pixel.
  85988. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  85989. */
  85990. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  85991. __extends(DepthOfFieldBlurPostProcess, _super);
  85992. /**
  85993. * Creates a new instance CircleOfConfusionPostProcess
  85994. * @param name The name of the effect.
  85995. * @param scene The scene the effect belongs to.
  85996. * @param direction The direction the blur should be applied.
  85997. * @param kernel The size of the kernel used to blur.
  85998. * @param options The required width/height ratio to downsize to before computing the render pass.
  85999. * @param camera The camera to apply the render pass to.
  86000. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  86001. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  86002. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  86003. * @param engine The engine which the post process will be applied. (default: current engine)
  86004. * @param reusable If the post process can be reused on the same frame. (default: false)
  86005. * @param textureType Type of textures used when performing the post process. (default: 0)
  86006. * @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)
  86007. */
  86008. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  86009. if (imageToBlur === void 0) { imageToBlur = null; }
  86010. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  86011. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  86012. if (blockCompilation === void 0) { blockCompilation = false; }
  86013. 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;
  86014. _this.direction = direction;
  86015. _this.onApplyObservable.add(function (effect) {
  86016. if (imageToBlur != null) {
  86017. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  86018. }
  86019. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  86020. if (scene.activeCamera) {
  86021. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  86022. }
  86023. });
  86024. return _this;
  86025. }
  86026. return DepthOfFieldBlurPostProcess;
  86027. }(BABYLON.BlurPostProcess));
  86028. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  86029. })(BABYLON || (BABYLON = {}));
  86030. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  86031. var BABYLON;
  86032. (function (BABYLON) {
  86033. /**
  86034. * Options to be set when merging outputs from the default pipeline.
  86035. */
  86036. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  86037. function DepthOfFieldMergePostProcessOptions() {
  86038. }
  86039. return DepthOfFieldMergePostProcessOptions;
  86040. }());
  86041. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  86042. /**
  86043. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  86044. */
  86045. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  86046. __extends(DepthOfFieldMergePostProcess, _super);
  86047. /**
  86048. * Creates a new instance of DepthOfFieldMergePostProcess
  86049. * @param name The name of the effect.
  86050. * @param originalFromInput Post process which's input will be used for the merge.
  86051. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  86052. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  86053. * @param options The required width/height ratio to downsize to before computing the render pass.
  86054. * @param camera The camera to apply the render pass to.
  86055. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  86056. * @param engine The engine which the post process will be applied. (default: current engine)
  86057. * @param reusable If the post process can be reused on the same frame. (default: false)
  86058. * @param textureType Type of textures used when performing the post process. (default: 0)
  86059. * @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)
  86060. */
  86061. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  86062. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  86063. if (blockCompilation === void 0) { blockCompilation = false; }
  86064. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  86065. _this.blurSteps = blurSteps;
  86066. _this.onApplyObservable.add(function (effect) {
  86067. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  86068. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  86069. blurSteps.forEach(function (step, index) {
  86070. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  86071. });
  86072. });
  86073. if (!blockCompilation) {
  86074. _this.updateEffect();
  86075. }
  86076. return _this;
  86077. }
  86078. /**
  86079. * Updates the effect with the current post process compile time values and recompiles the shader.
  86080. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  86081. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  86082. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  86083. * @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
  86084. * @param onCompiled Called when the shader has been compiled.
  86085. * @param onError Called if there is an error when compiling a shader.
  86086. */
  86087. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  86088. if (defines === void 0) { defines = null; }
  86089. if (uniforms === void 0) { uniforms = null; }
  86090. if (samplers === void 0) { samplers = null; }
  86091. if (!defines) {
  86092. defines = "";
  86093. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  86094. }
  86095. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  86096. };
  86097. return DepthOfFieldMergePostProcess;
  86098. }(BABYLON.PostProcess));
  86099. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  86100. })(BABYLON || (BABYLON = {}));
  86101. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  86102. var BABYLON;
  86103. (function (BABYLON) {
  86104. /**
  86105. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  86106. */
  86107. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  86108. __extends(CircleOfConfusionPostProcess, _super);
  86109. /**
  86110. * Creates a new instance CircleOfConfusionPostProcess
  86111. * @param name The name of the effect.
  86112. * @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.
  86113. * @param options The required width/height ratio to downsize to before computing the render pass.
  86114. * @param camera The camera to apply the render pass to.
  86115. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  86116. * @param engine The engine which the post process will be applied. (default: current engine)
  86117. * @param reusable If the post process can be reused on the same frame. (default: false)
  86118. * @param textureType Type of textures used when performing the post process. (default: 0)
  86119. * @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)
  86120. */
  86121. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  86122. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  86123. if (blockCompilation === void 0) { blockCompilation = false; }
  86124. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  86125. /**
  86126. * 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.
  86127. */
  86128. _this.lensSize = 50;
  86129. /**
  86130. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  86131. */
  86132. _this.fStop = 1.4;
  86133. /**
  86134. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  86135. */
  86136. _this.focusDistance = 2000;
  86137. /**
  86138. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  86139. */
  86140. _this.focalLength = 50;
  86141. _this._depthTexture = null;
  86142. _this._depthTexture = depthTexture;
  86143. _this.onApplyObservable.add(function (effect) {
  86144. if (!_this._depthTexture) {
  86145. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  86146. return;
  86147. }
  86148. effect.setTexture("depthSampler", _this._depthTexture);
  86149. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  86150. var aperture = _this.lensSize / _this.fStop;
  86151. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  86152. effect.setFloat('focusDistance', _this.focusDistance);
  86153. effect.setFloat('cocPrecalculation', cocPrecalculation);
  86154. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  86155. });
  86156. return _this;
  86157. }
  86158. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  86159. /**
  86160. * 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.
  86161. */
  86162. set: function (value) {
  86163. this._depthTexture = value;
  86164. },
  86165. enumerable: true,
  86166. configurable: true
  86167. });
  86168. return CircleOfConfusionPostProcess;
  86169. }(BABYLON.PostProcess));
  86170. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  86171. })(BABYLON || (BABYLON = {}));
  86172. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  86173. var BABYLON;
  86174. (function (BABYLON) {
  86175. /**
  86176. * Specifies the level of max blur that should be applied when using the depth of field effect
  86177. */
  86178. var DepthOfFieldEffectBlurLevel;
  86179. (function (DepthOfFieldEffectBlurLevel) {
  86180. /**
  86181. * Subtle blur
  86182. */
  86183. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  86184. /**
  86185. * Medium blur
  86186. */
  86187. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  86188. /**
  86189. * Large blur
  86190. */
  86191. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  86192. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  86193. ;
  86194. /**
  86195. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  86196. */
  86197. var DepthOfFieldEffect = /** @class */ (function (_super) {
  86198. __extends(DepthOfFieldEffect, _super);
  86199. /**
  86200. * Creates a new instance DepthOfFieldEffect
  86201. * @param scene The scene the effect belongs to.
  86202. * @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.
  86203. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  86204. * @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)
  86205. */
  86206. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  86207. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  86208. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  86209. if (blockCompilation === void 0) { blockCompilation = false; }
  86210. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  86211. return _this._effects;
  86212. }, true) || this;
  86213. /**
  86214. * @hidden Internal post processes in depth of field effect
  86215. */
  86216. _this._effects = [];
  86217. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  86218. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  86219. // 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)
  86220. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  86221. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  86222. _this._depthOfFieldBlurY = [];
  86223. _this._depthOfFieldBlurX = [];
  86224. var blurCount = 1;
  86225. var kernelSize = 15;
  86226. switch (blurLevel) {
  86227. case DepthOfFieldEffectBlurLevel.High: {
  86228. blurCount = 3;
  86229. kernelSize = 51;
  86230. break;
  86231. }
  86232. case DepthOfFieldEffectBlurLevel.Medium: {
  86233. blurCount = 2;
  86234. kernelSize = 31;
  86235. break;
  86236. }
  86237. default: {
  86238. kernelSize = 15;
  86239. blurCount = 1;
  86240. break;
  86241. }
  86242. }
  86243. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  86244. var ratio = 1.0;
  86245. for (var i = 0; i < blurCount; i++) {
  86246. 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);
  86247. blurY.autoClear = false;
  86248. ratio = 0.75 / Math.pow(2, i);
  86249. 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);
  86250. blurX.autoClear = false;
  86251. _this._depthOfFieldBlurY.push(blurY);
  86252. _this._depthOfFieldBlurX.push(blurX);
  86253. }
  86254. // Set all post processes on the effect.
  86255. _this._effects = [_this._circleOfConfusion];
  86256. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  86257. _this._effects.push(_this._depthOfFieldBlurY[i]);
  86258. _this._effects.push(_this._depthOfFieldBlurX[i]);
  86259. }
  86260. // Merge blurred images with original image based on circleOfConfusion
  86261. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  86262. _this._dofMerge.autoClear = false;
  86263. _this._effects.push(_this._dofMerge);
  86264. return _this;
  86265. }
  86266. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  86267. get: function () {
  86268. return this._circleOfConfusion.focalLength;
  86269. },
  86270. /**
  86271. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  86272. */
  86273. set: function (value) {
  86274. this._circleOfConfusion.focalLength = value;
  86275. },
  86276. enumerable: true,
  86277. configurable: true
  86278. });
  86279. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  86280. get: function () {
  86281. return this._circleOfConfusion.fStop;
  86282. },
  86283. /**
  86284. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  86285. */
  86286. set: function (value) {
  86287. this._circleOfConfusion.fStop = value;
  86288. },
  86289. enumerable: true,
  86290. configurable: true
  86291. });
  86292. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  86293. get: function () {
  86294. return this._circleOfConfusion.focusDistance;
  86295. },
  86296. /**
  86297. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  86298. */
  86299. set: function (value) {
  86300. this._circleOfConfusion.focusDistance = value;
  86301. },
  86302. enumerable: true,
  86303. configurable: true
  86304. });
  86305. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  86306. get: function () {
  86307. return this._circleOfConfusion.lensSize;
  86308. },
  86309. /**
  86310. * 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.
  86311. */
  86312. set: function (value) {
  86313. this._circleOfConfusion.lensSize = value;
  86314. },
  86315. enumerable: true,
  86316. configurable: true
  86317. });
  86318. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  86319. /**
  86320. * 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.
  86321. */
  86322. set: function (value) {
  86323. this._circleOfConfusion.depthTexture = value;
  86324. },
  86325. enumerable: true,
  86326. configurable: true
  86327. });
  86328. /**
  86329. * Disposes each of the internal effects for a given camera.
  86330. * @param camera The camera to dispose the effect on.
  86331. */
  86332. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  86333. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  86334. this._effects[effectIndex].dispose(camera);
  86335. }
  86336. };
  86337. /**
  86338. * @hidden Internal
  86339. */
  86340. DepthOfFieldEffect.prototype._updateEffects = function () {
  86341. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  86342. this._effects[effectIndex].updateEffect();
  86343. }
  86344. };
  86345. /**
  86346. * Internal
  86347. * @returns if all the contained post processes are ready.
  86348. * @hidden
  86349. */
  86350. DepthOfFieldEffect.prototype._isReady = function () {
  86351. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  86352. if (!this._effects[effectIndex].isReady()) {
  86353. return false;
  86354. }
  86355. }
  86356. return true;
  86357. };
  86358. return DepthOfFieldEffect;
  86359. }(BABYLON.PostProcessRenderEffect));
  86360. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  86361. })(BABYLON || (BABYLON = {}));
  86362. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  86363. var BABYLON;
  86364. (function (BABYLON) {
  86365. /**
  86366. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  86367. */
  86368. var BloomMergePostProcess = /** @class */ (function (_super) {
  86369. __extends(BloomMergePostProcess, _super);
  86370. /**
  86371. * Creates a new instance of @see BloomMergePostProcess
  86372. * @param name The name of the effect.
  86373. * @param originalFromInput Post process which's input will be used for the merge.
  86374. * @param blurred Blurred highlights post process which's output will be used.
  86375. * @param weight Weight of the bloom to be added to the original input.
  86376. * @param options The required width/height ratio to downsize to before computing the render pass.
  86377. * @param camera The camera to apply the render pass to.
  86378. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  86379. * @param engine The engine which the post process will be applied. (default: current engine)
  86380. * @param reusable If the post process can be reused on the same frame. (default: false)
  86381. * @param textureType Type of textures used when performing the post process. (default: 0)
  86382. * @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)
  86383. */
  86384. function BloomMergePostProcess(name, originalFromInput, blurred,
  86385. /** Weight of the bloom to be added to the original input. */
  86386. weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  86387. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  86388. if (blockCompilation === void 0) { blockCompilation = false; }
  86389. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  86390. _this.weight = weight;
  86391. _this.onApplyObservable.add(function (effect) {
  86392. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  86393. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  86394. effect.setFloat("bloomWeight", _this.weight);
  86395. });
  86396. if (!blockCompilation) {
  86397. _this.updateEffect();
  86398. }
  86399. return _this;
  86400. }
  86401. return BloomMergePostProcess;
  86402. }(BABYLON.PostProcess));
  86403. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  86404. })(BABYLON || (BABYLON = {}));
  86405. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  86406. var BABYLON;
  86407. (function (BABYLON) {
  86408. /**
  86409. * 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.
  86410. */
  86411. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  86412. __extends(ExtractHighlightsPostProcess, _super);
  86413. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  86414. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  86415. if (blockCompilation === void 0) { blockCompilation = false; }
  86416. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  86417. /**
  86418. * The luminance threshold, pixels below this value will be set to black.
  86419. */
  86420. _this.threshold = 0.9;
  86421. /** @hidden */
  86422. _this._exposure = 1;
  86423. /**
  86424. * Post process which has the input texture to be used when performing highlight extraction
  86425. * @hidden
  86426. */
  86427. _this._inputPostProcess = null;
  86428. _this.onApplyObservable.add(function (effect) {
  86429. if (_this._inputPostProcess) {
  86430. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  86431. }
  86432. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  86433. effect.setFloat('exposure', _this._exposure);
  86434. });
  86435. return _this;
  86436. }
  86437. return ExtractHighlightsPostProcess;
  86438. }(BABYLON.PostProcess));
  86439. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  86440. })(BABYLON || (BABYLON = {}));
  86441. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  86442. var BABYLON;
  86443. (function (BABYLON) {
  86444. /**
  86445. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  86446. */
  86447. var BloomEffect = /** @class */ (function (_super) {
  86448. __extends(BloomEffect, _super);
  86449. /**
  86450. * Creates a new instance of @see BloomEffect
  86451. * @param scene The scene the effect belongs to.
  86452. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  86453. * @param bloomKernel The size of the kernel to be used when applying the blur.
  86454. * @param bloomWeight The the strength of bloom.
  86455. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  86456. * @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)
  86457. */
  86458. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  86459. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  86460. if (blockCompilation === void 0) { blockCompilation = false; }
  86461. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  86462. return _this._effects;
  86463. }, true) || this;
  86464. _this.bloomScale = bloomScale;
  86465. /**
  86466. * @hidden Internal
  86467. */
  86468. _this._effects = [];
  86469. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  86470. _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);
  86471. _this._blurX.alwaysForcePOT = true;
  86472. _this._blurX.autoClear = false;
  86473. _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);
  86474. _this._blurY.alwaysForcePOT = true;
  86475. _this._blurY.autoClear = false;
  86476. _this.kernel = bloomKernel;
  86477. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  86478. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  86479. _this._merge.autoClear = false;
  86480. _this._effects.push(_this._merge);
  86481. return _this;
  86482. }
  86483. Object.defineProperty(BloomEffect.prototype, "threshold", {
  86484. /**
  86485. * The luminance threshold to find bright areas of the image to bloom.
  86486. */
  86487. get: function () {
  86488. return this._downscale.threshold;
  86489. },
  86490. set: function (value) {
  86491. this._downscale.threshold = value;
  86492. },
  86493. enumerable: true,
  86494. configurable: true
  86495. });
  86496. Object.defineProperty(BloomEffect.prototype, "weight", {
  86497. /**
  86498. * The strength of the bloom.
  86499. */
  86500. get: function () {
  86501. return this._merge.weight;
  86502. },
  86503. set: function (value) {
  86504. this._merge.weight = value;
  86505. },
  86506. enumerable: true,
  86507. configurable: true
  86508. });
  86509. Object.defineProperty(BloomEffect.prototype, "kernel", {
  86510. /**
  86511. * Specifies the size of the bloom blur kernel, relative to the final output size
  86512. */
  86513. get: function () {
  86514. return this._blurX.kernel / this.bloomScale;
  86515. },
  86516. set: function (value) {
  86517. this._blurX.kernel = value * this.bloomScale;
  86518. this._blurY.kernel = value * this.bloomScale;
  86519. },
  86520. enumerable: true,
  86521. configurable: true
  86522. });
  86523. /**
  86524. * Disposes each of the internal effects for a given camera.
  86525. * @param camera The camera to dispose the effect on.
  86526. */
  86527. BloomEffect.prototype.disposeEffects = function (camera) {
  86528. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  86529. this._effects[effectIndex].dispose(camera);
  86530. }
  86531. };
  86532. /**
  86533. * @hidden Internal
  86534. */
  86535. BloomEffect.prototype._updateEffects = function () {
  86536. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  86537. this._effects[effectIndex].updateEffect();
  86538. }
  86539. };
  86540. /**
  86541. * Internal
  86542. * @returns if all the contained post processes are ready.
  86543. * @hidden
  86544. */
  86545. BloomEffect.prototype._isReady = function () {
  86546. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  86547. if (!this._effects[effectIndex].isReady()) {
  86548. return false;
  86549. }
  86550. }
  86551. return true;
  86552. };
  86553. return BloomEffect;
  86554. }(BABYLON.PostProcessRenderEffect));
  86555. BABYLON.BloomEffect = BloomEffect;
  86556. })(BABYLON || (BABYLON = {}));
  86557. //# sourceMappingURL=babylon.bloomEffect.js.map
  86558. var BABYLON;
  86559. (function (BABYLON) {
  86560. /**
  86561. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  86562. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  86563. */
  86564. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  86565. __extends(DefaultRenderingPipeline, _super);
  86566. /**
  86567. * @constructor
  86568. * @param {string} name - The rendering pipeline name (default: "")
  86569. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  86570. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  86571. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  86572. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  86573. */
  86574. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  86575. if (name === void 0) { name = ""; }
  86576. if (hdr === void 0) { hdr = true; }
  86577. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  86578. if (automaticBuild === void 0) { automaticBuild = true; }
  86579. var _this = _super.call(this, scene.getEngine(), name) || this;
  86580. _this._camerasToBeAttached = [];
  86581. /**
  86582. * ID of the sharpen post process,
  86583. */
  86584. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  86585. /**
  86586. * @ignore
  86587. * ID of the image processing post process;
  86588. */
  86589. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  86590. /**
  86591. * @ignore
  86592. * ID of the Fast Approximate Anti-Aliasing post process;
  86593. */
  86594. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  86595. /**
  86596. * ID of the chromatic aberration post process,
  86597. */
  86598. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  86599. /**
  86600. * ID of the grain post process
  86601. */
  86602. _this.GrainPostProcessId = "GrainPostProcessEffect";
  86603. /**
  86604. * Glow post process which adds a glow to emmisive areas of the image
  86605. */
  86606. _this._glowLayer = null;
  86607. /**
  86608. * Animations which can be used to tweak settings over a period of time
  86609. */
  86610. _this.animations = [];
  86611. _this._imageProcessingConfigurationObserver = null;
  86612. // Values
  86613. _this._sharpenEnabled = false;
  86614. _this._bloomEnabled = false;
  86615. _this._depthOfFieldEnabled = false;
  86616. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  86617. _this._fxaaEnabled = false;
  86618. _this._imageProcessingEnabled = true;
  86619. _this._bloomScale = 0.5;
  86620. _this._chromaticAberrationEnabled = false;
  86621. _this._grainEnabled = false;
  86622. _this._buildAllowed = true;
  86623. _this._resizeObserver = null;
  86624. _this._hardwareScaleLevel = 1.0;
  86625. _this._bloomKernel = 64;
  86626. /**
  86627. * Specifies the weight of the bloom in the final rendering
  86628. */
  86629. _this._bloomWeight = 0.15;
  86630. /**
  86631. * Specifies the luma threshold for the area that will be blurred by the bloom
  86632. */
  86633. _this._bloomThreshold = 0.9;
  86634. _this._samples = 1;
  86635. _this._hasCleared = false;
  86636. _this._prevPostProcess = null;
  86637. _this._prevPrevPostProcess = null;
  86638. _this._depthOfFieldSceneObserver = null;
  86639. _this._cameras = cameras || scene.cameras;
  86640. _this._cameras = _this._cameras.slice();
  86641. _this._camerasToBeAttached = _this._cameras.slice();
  86642. _this._buildAllowed = automaticBuild;
  86643. // Initialize
  86644. _this._scene = scene;
  86645. var caps = _this._scene.getEngine().getCaps();
  86646. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  86647. // Misc
  86648. if (_this._hdr) {
  86649. if (caps.textureHalfFloatRender) {
  86650. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  86651. }
  86652. else if (caps.textureFloatRender) {
  86653. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  86654. }
  86655. }
  86656. else {
  86657. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  86658. }
  86659. // Attach
  86660. scene.postProcessRenderPipelineManager.addPipeline(_this);
  86661. var engine = _this._scene.getEngine();
  86662. // Create post processes before hand so they can be modified before enabled.
  86663. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  86664. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  86665. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  86666. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  86667. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  86668. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  86669. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  86670. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  86671. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  86672. _this._resizeObserver = engine.onResizeObservable.add(function () {
  86673. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  86674. _this.bloomKernel = _this.bloomKernel;
  86675. });
  86676. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  86677. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  86678. });
  86679. _this._buildPipeline();
  86680. return _this;
  86681. }
  86682. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  86683. get: function () {
  86684. return this._sharpenEnabled;
  86685. },
  86686. /**
  86687. * Enable or disable the sharpen process from the pipeline
  86688. */
  86689. set: function (enabled) {
  86690. if (this._sharpenEnabled === enabled) {
  86691. return;
  86692. }
  86693. this._sharpenEnabled = enabled;
  86694. this._buildPipeline();
  86695. },
  86696. enumerable: true,
  86697. configurable: true
  86698. });
  86699. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  86700. /**
  86701. * Specifies the size of the bloom blur kernel, relative to the final output size
  86702. */
  86703. get: function () {
  86704. return this._bloomKernel;
  86705. },
  86706. set: function (value) {
  86707. this._bloomKernel = value;
  86708. this.bloom.kernel = value / this._hardwareScaleLevel;
  86709. },
  86710. enumerable: true,
  86711. configurable: true
  86712. });
  86713. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  86714. get: function () {
  86715. return this._bloomWeight;
  86716. },
  86717. /**
  86718. * The strength of the bloom.
  86719. */
  86720. set: function (value) {
  86721. if (this._bloomWeight === value) {
  86722. return;
  86723. }
  86724. this.bloom.weight = value;
  86725. this._bloomWeight = value;
  86726. },
  86727. enumerable: true,
  86728. configurable: true
  86729. });
  86730. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  86731. get: function () {
  86732. return this._bloomThreshold;
  86733. },
  86734. /**
  86735. * The strength of the bloom.
  86736. */
  86737. set: function (value) {
  86738. if (this._bloomThreshold === value) {
  86739. return;
  86740. }
  86741. this.bloom.threshold = value;
  86742. this._bloomThreshold = value;
  86743. },
  86744. enumerable: true,
  86745. configurable: true
  86746. });
  86747. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  86748. get: function () {
  86749. return this._bloomScale;
  86750. },
  86751. /**
  86752. * The scale of the bloom, lower value will provide better performance.
  86753. */
  86754. set: function (value) {
  86755. if (this._bloomScale === value) {
  86756. return;
  86757. }
  86758. this._bloomScale = value;
  86759. // recreate bloom and dispose old as this setting is not dynamic
  86760. this._rebuildBloom();
  86761. this._buildPipeline();
  86762. },
  86763. enumerable: true,
  86764. configurable: true
  86765. });
  86766. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  86767. get: function () {
  86768. return this._bloomEnabled;
  86769. },
  86770. /**
  86771. * Enable or disable the bloom from the pipeline
  86772. */
  86773. set: function (enabled) {
  86774. if (this._bloomEnabled === enabled) {
  86775. return;
  86776. }
  86777. this._bloomEnabled = enabled;
  86778. this._buildPipeline();
  86779. },
  86780. enumerable: true,
  86781. configurable: true
  86782. });
  86783. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  86784. // recreate bloom and dispose old as this setting is not dynamic
  86785. var oldBloom = this.bloom;
  86786. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  86787. this.bloom.threshold = oldBloom.threshold;
  86788. for (var i = 0; i < this._cameras.length; i++) {
  86789. oldBloom.disposeEffects(this._cameras[i]);
  86790. }
  86791. };
  86792. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  86793. /**
  86794. * If the depth of field is enabled.
  86795. */
  86796. get: function () {
  86797. return this._depthOfFieldEnabled;
  86798. },
  86799. set: function (enabled) {
  86800. if (this._depthOfFieldEnabled === enabled) {
  86801. return;
  86802. }
  86803. this._depthOfFieldEnabled = enabled;
  86804. this._buildPipeline();
  86805. },
  86806. enumerable: true,
  86807. configurable: true
  86808. });
  86809. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  86810. /**
  86811. * Blur level of the depth of field effect. (Higher blur will effect performance)
  86812. */
  86813. get: function () {
  86814. return this._depthOfFieldBlurLevel;
  86815. },
  86816. set: function (value) {
  86817. if (this._depthOfFieldBlurLevel === value) {
  86818. return;
  86819. }
  86820. this._depthOfFieldBlurLevel = value;
  86821. // recreate dof and dispose old as this setting is not dynamic
  86822. var oldDof = this.depthOfField;
  86823. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  86824. this.depthOfField.focalLength = oldDof.focalLength;
  86825. this.depthOfField.focusDistance = oldDof.focusDistance;
  86826. this.depthOfField.fStop = oldDof.fStop;
  86827. this.depthOfField.lensSize = oldDof.lensSize;
  86828. for (var i = 0; i < this._cameras.length; i++) {
  86829. oldDof.disposeEffects(this._cameras[i]);
  86830. }
  86831. this._buildPipeline();
  86832. },
  86833. enumerable: true,
  86834. configurable: true
  86835. });
  86836. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  86837. get: function () {
  86838. return this._fxaaEnabled;
  86839. },
  86840. /**
  86841. * If the anti aliasing is enabled.
  86842. */
  86843. set: function (enabled) {
  86844. if (this._fxaaEnabled === enabled) {
  86845. return;
  86846. }
  86847. this._fxaaEnabled = enabled;
  86848. this._buildPipeline();
  86849. },
  86850. enumerable: true,
  86851. configurable: true
  86852. });
  86853. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  86854. get: function () {
  86855. return this._samples;
  86856. },
  86857. /**
  86858. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  86859. */
  86860. set: function (sampleCount) {
  86861. if (this._samples === sampleCount) {
  86862. return;
  86863. }
  86864. this._samples = sampleCount;
  86865. this._buildPipeline();
  86866. },
  86867. enumerable: true,
  86868. configurable: true
  86869. });
  86870. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  86871. get: function () {
  86872. return this._imageProcessingEnabled;
  86873. },
  86874. /**
  86875. * If image processing is enabled.
  86876. */
  86877. set: function (enabled) {
  86878. if (this._imageProcessingEnabled === enabled) {
  86879. return;
  86880. }
  86881. this._imageProcessingEnabled = enabled;
  86882. this._buildPipeline();
  86883. },
  86884. enumerable: true,
  86885. configurable: true
  86886. });
  86887. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  86888. get: function () {
  86889. return this._glowLayer == null;
  86890. },
  86891. /**
  86892. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  86893. */
  86894. set: function (enabled) {
  86895. if (enabled && !this._glowLayer) {
  86896. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  86897. }
  86898. else if (!enabled && this._glowLayer) {
  86899. this._glowLayer.dispose();
  86900. this._glowLayer = null;
  86901. }
  86902. },
  86903. enumerable: true,
  86904. configurable: true
  86905. });
  86906. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  86907. get: function () {
  86908. return this._chromaticAberrationEnabled;
  86909. },
  86910. /**
  86911. * Enable or disable the chromaticAberration process from the pipeline
  86912. */
  86913. set: function (enabled) {
  86914. if (this._chromaticAberrationEnabled === enabled) {
  86915. return;
  86916. }
  86917. this._chromaticAberrationEnabled = enabled;
  86918. this._buildPipeline();
  86919. },
  86920. enumerable: true,
  86921. configurable: true
  86922. });
  86923. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  86924. get: function () {
  86925. return this._grainEnabled;
  86926. },
  86927. /**
  86928. * Enable or disable the grain process from the pipeline
  86929. */
  86930. set: function (enabled) {
  86931. if (this._grainEnabled === enabled) {
  86932. return;
  86933. }
  86934. this._grainEnabled = enabled;
  86935. this._buildPipeline();
  86936. },
  86937. enumerable: true,
  86938. configurable: true
  86939. });
  86940. /**
  86941. * Force the compilation of the entire pipeline.
  86942. */
  86943. DefaultRenderingPipeline.prototype.prepare = function () {
  86944. var previousState = this._buildAllowed;
  86945. this._buildAllowed = true;
  86946. this._buildPipeline();
  86947. this._buildAllowed = previousState;
  86948. };
  86949. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  86950. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  86951. if (this._hasCleared) {
  86952. postProcess.autoClear = false;
  86953. }
  86954. else {
  86955. postProcess.autoClear = true;
  86956. this._scene.autoClear = false;
  86957. this._hasCleared = true;
  86958. }
  86959. if (!skipTextureSharing) {
  86960. if (this._prevPrevPostProcess) {
  86961. postProcess.shareOutputWith(this._prevPrevPostProcess);
  86962. }
  86963. else {
  86964. postProcess.useOwnOutput();
  86965. }
  86966. if (this._prevPostProcess) {
  86967. this._prevPrevPostProcess = this._prevPostProcess;
  86968. }
  86969. this._prevPostProcess = postProcess;
  86970. }
  86971. };
  86972. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  86973. var _this = this;
  86974. if (!this._buildAllowed) {
  86975. return;
  86976. }
  86977. this._scene.autoClear = true;
  86978. var engine = this._scene.getEngine();
  86979. this._disposePostProcesses();
  86980. if (this._cameras !== null) {
  86981. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  86982. // get back cameras to be used to reattach pipeline
  86983. this._cameras = this._camerasToBeAttached.slice();
  86984. }
  86985. this._reset();
  86986. this._prevPostProcess = null;
  86987. this._prevPrevPostProcess = null;
  86988. this._hasCleared = false;
  86989. if (this.depthOfFieldEnabled) {
  86990. // Multi camera suport
  86991. if (this._cameras.length > 1) {
  86992. for (var _i = 0, _a = this._cameras; _i < _a.length; _i++) {
  86993. var camera = _a[_i];
  86994. var depthRenderer = this._scene.enableDepthRenderer(camera);
  86995. depthRenderer.useOnlyInActiveCamera = true;
  86996. }
  86997. this._depthOfFieldSceneObserver = this._scene.onAfterRenderTargetsRenderObservable.add(function (scene) {
  86998. if (_this._cameras.indexOf(scene.activeCamera) > -1) {
  86999. _this.depthOfField.depthTexture = scene.enableDepthRenderer(scene.activeCamera).getDepthMap();
  87000. }
  87001. });
  87002. }
  87003. else {
  87004. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  87005. var depthRenderer = this._scene.enableDepthRenderer(this._cameras[0]);
  87006. this.depthOfField.depthTexture = depthRenderer.getDepthMap();
  87007. }
  87008. if (!this.depthOfField._isReady()) {
  87009. this.depthOfField._updateEffects();
  87010. }
  87011. this.addEffect(this.depthOfField);
  87012. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  87013. }
  87014. else {
  87015. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  87016. }
  87017. if (this.bloomEnabled) {
  87018. if (!this.bloom._isReady()) {
  87019. this.bloom._updateEffects();
  87020. }
  87021. this.addEffect(this.bloom);
  87022. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  87023. }
  87024. if (this._imageProcessingEnabled) {
  87025. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  87026. if (this._hdr) {
  87027. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  87028. this._setAutoClearAndTextureSharing(this.imageProcessing);
  87029. }
  87030. else {
  87031. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  87032. }
  87033. }
  87034. if (this.sharpenEnabled) {
  87035. if (!this.sharpen.isReady()) {
  87036. this.sharpen.updateEffect();
  87037. }
  87038. this.addEffect(this._sharpenEffect);
  87039. this._setAutoClearAndTextureSharing(this.sharpen);
  87040. }
  87041. if (this.grainEnabled) {
  87042. if (!this.grain.isReady()) {
  87043. this.grain.updateEffect();
  87044. }
  87045. this.addEffect(this._grainEffect);
  87046. this._setAutoClearAndTextureSharing(this.grain);
  87047. }
  87048. if (this.chromaticAberrationEnabled) {
  87049. if (!this.chromaticAberration.isReady()) {
  87050. this.chromaticAberration.updateEffect();
  87051. }
  87052. this.addEffect(this._chromaticAberrationEffect);
  87053. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  87054. }
  87055. if (this.fxaaEnabled) {
  87056. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  87057. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  87058. this._setAutoClearAndTextureSharing(this.fxaa, true);
  87059. }
  87060. if (this._cameras !== null) {
  87061. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  87062. }
  87063. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  87064. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  87065. }
  87066. };
  87067. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  87068. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  87069. for (var i = 0; i < this._cameras.length; i++) {
  87070. var camera = this._cameras[i];
  87071. if (this.imageProcessing) {
  87072. this.imageProcessing.dispose(camera);
  87073. }
  87074. if (this.fxaa) {
  87075. this.fxaa.dispose(camera);
  87076. }
  87077. // These are created in the constructor and should not be disposed on every pipeline change
  87078. if (disposeNonRecreated) {
  87079. if (this.sharpen) {
  87080. this.sharpen.dispose(camera);
  87081. }
  87082. if (this.depthOfField) {
  87083. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  87084. this.depthOfField.disposeEffects(camera);
  87085. }
  87086. if (this.bloom) {
  87087. this.bloom.disposeEffects(camera);
  87088. }
  87089. if (this.chromaticAberration) {
  87090. this.chromaticAberration.dispose(camera);
  87091. }
  87092. if (this.grain) {
  87093. this.grain.dispose(camera);
  87094. }
  87095. if (this._glowLayer) {
  87096. this._glowLayer.dispose();
  87097. }
  87098. }
  87099. }
  87100. this.imageProcessing = null;
  87101. this.fxaa = null;
  87102. if (disposeNonRecreated) {
  87103. this.sharpen = null;
  87104. this._sharpenEffect = null;
  87105. this.depthOfField = null;
  87106. this.bloom = null;
  87107. this.chromaticAberration = null;
  87108. this._chromaticAberrationEffect = null;
  87109. this.grain = null;
  87110. this._grainEffect = null;
  87111. this._glowLayer = null;
  87112. }
  87113. };
  87114. /**
  87115. * Adds a camera to the pipeline
  87116. * @param camera the camera to be added
  87117. */
  87118. DefaultRenderingPipeline.prototype.addCamera = function (camera) {
  87119. this._camerasToBeAttached.push(camera);
  87120. this._buildPipeline();
  87121. };
  87122. /**
  87123. * Removes a camera from the pipeline
  87124. * @param camera the camera to remove
  87125. */
  87126. DefaultRenderingPipeline.prototype.removeCamera = function (camera) {
  87127. var index = this._camerasToBeAttached.indexOf(camera);
  87128. this._camerasToBeAttached.splice(index, 1);
  87129. this._buildPipeline();
  87130. };
  87131. /**
  87132. * Dispose of the pipeline and stop all post processes
  87133. */
  87134. DefaultRenderingPipeline.prototype.dispose = function () {
  87135. this._disposePostProcesses(true);
  87136. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  87137. this._scene.autoClear = true;
  87138. if (this._resizeObserver) {
  87139. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  87140. this._resizeObserver = null;
  87141. }
  87142. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  87143. _super.prototype.dispose.call(this);
  87144. };
  87145. /**
  87146. * Serialize the rendering pipeline (Used when exporting)
  87147. * @returns the serialized object
  87148. */
  87149. DefaultRenderingPipeline.prototype.serialize = function () {
  87150. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  87151. serializationObject.customType = "DefaultRenderingPipeline";
  87152. return serializationObject;
  87153. };
  87154. /**
  87155. * Parse the serialized pipeline
  87156. * @param source Source pipeline.
  87157. * @param scene The scene to load the pipeline to.
  87158. * @param rootUrl The URL of the serialized pipeline.
  87159. * @returns An instantiated pipeline from the serialized object.
  87160. */
  87161. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  87162. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  87163. };
  87164. __decorate([
  87165. BABYLON.serialize()
  87166. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  87167. __decorate([
  87168. BABYLON.serialize()
  87169. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  87170. __decorate([
  87171. BABYLON.serialize()
  87172. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  87173. __decorate([
  87174. BABYLON.serialize()
  87175. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  87176. __decorate([
  87177. BABYLON.serialize()
  87178. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  87179. __decorate([
  87180. BABYLON.serialize()
  87181. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  87182. __decorate([
  87183. BABYLON.serialize()
  87184. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  87185. __decorate([
  87186. BABYLON.serialize()
  87187. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  87188. __decorate([
  87189. BABYLON.serialize()
  87190. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  87191. __decorate([
  87192. BABYLON.serialize()
  87193. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  87194. __decorate([
  87195. BABYLON.serialize()
  87196. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  87197. __decorate([
  87198. BABYLON.serialize()
  87199. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  87200. __decorate([
  87201. BABYLON.serialize()
  87202. ], DefaultRenderingPipeline.prototype, "samples", null);
  87203. __decorate([
  87204. BABYLON.serialize()
  87205. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  87206. __decorate([
  87207. BABYLON.serialize()
  87208. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  87209. __decorate([
  87210. BABYLON.serialize()
  87211. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  87212. __decorate([
  87213. BABYLON.serialize()
  87214. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  87215. return DefaultRenderingPipeline;
  87216. }(BABYLON.PostProcessRenderPipeline));
  87217. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  87218. })(BABYLON || (BABYLON = {}));
  87219. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  87220. var BABYLON;
  87221. (function (BABYLON) {
  87222. /**
  87223. * @hidden
  87224. */
  87225. var ImageProcessingConfigurationDefines = /** @class */ (function (_super) {
  87226. __extends(ImageProcessingConfigurationDefines, _super);
  87227. function ImageProcessingConfigurationDefines() {
  87228. var _this = _super.call(this) || this;
  87229. _this.IMAGEPROCESSING = false;
  87230. _this.VIGNETTE = false;
  87231. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  87232. _this.VIGNETTEBLENDMODEOPAQUE = false;
  87233. _this.TONEMAPPING = false;
  87234. _this.TONEMAPPING_ACES = false;
  87235. _this.CONTRAST = false;
  87236. _this.COLORCURVES = false;
  87237. _this.COLORGRADING = false;
  87238. _this.COLORGRADING3D = false;
  87239. _this.SAMPLER3DGREENDEPTH = false;
  87240. _this.SAMPLER3DBGRMAP = false;
  87241. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  87242. _this.EXPOSURE = false;
  87243. _this.rebuild();
  87244. return _this;
  87245. }
  87246. return ImageProcessingConfigurationDefines;
  87247. }(BABYLON.MaterialDefines));
  87248. BABYLON.ImageProcessingConfigurationDefines = ImageProcessingConfigurationDefines;
  87249. /**
  87250. * This groups together the common properties used for image processing either in direct forward pass
  87251. * or through post processing effect depending on the use of the image processing pipeline in your scene
  87252. * or not.
  87253. */
  87254. var ImageProcessingConfiguration = /** @class */ (function () {
  87255. function ImageProcessingConfiguration() {
  87256. /**
  87257. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  87258. */
  87259. this.colorCurves = new BABYLON.ColorCurves();
  87260. this._colorCurvesEnabled = false;
  87261. this._colorGradingEnabled = false;
  87262. this._colorGradingWithGreenDepth = true;
  87263. this._colorGradingBGR = true;
  87264. /** @hidden */
  87265. this._exposure = 1.0;
  87266. this._toneMappingEnabled = false;
  87267. this._toneMappingType = ImageProcessingConfiguration.TONEMAPPING_STANDARD;
  87268. this._contrast = 1.0;
  87269. /**
  87270. * Vignette stretch size.
  87271. */
  87272. this.vignetteStretch = 0;
  87273. /**
  87274. * Vignette centre X Offset.
  87275. */
  87276. this.vignetteCentreX = 0;
  87277. /**
  87278. * Vignette centre Y Offset.
  87279. */
  87280. this.vignetteCentreY = 0;
  87281. /**
  87282. * Vignette weight or intensity of the vignette effect.
  87283. */
  87284. this.vignetteWeight = 1.5;
  87285. /**
  87286. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  87287. * if vignetteEnabled is set to true.
  87288. */
  87289. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  87290. /**
  87291. * Camera field of view used by the Vignette effect.
  87292. */
  87293. this.vignetteCameraFov = 0.5;
  87294. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  87295. this._vignetteEnabled = false;
  87296. this._applyByPostProcess = false;
  87297. this._isEnabled = true;
  87298. /**
  87299. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  87300. */
  87301. this.onUpdateParameters = new BABYLON.Observable();
  87302. }
  87303. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  87304. /**
  87305. * Gets wether the color curves effect is enabled.
  87306. */
  87307. get: function () {
  87308. return this._colorCurvesEnabled;
  87309. },
  87310. /**
  87311. * Sets wether the color curves effect is enabled.
  87312. */
  87313. set: function (value) {
  87314. if (this._colorCurvesEnabled === value) {
  87315. return;
  87316. }
  87317. this._colorCurvesEnabled = value;
  87318. this._updateParameters();
  87319. },
  87320. enumerable: true,
  87321. configurable: true
  87322. });
  87323. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingTexture", {
  87324. /**
  87325. * Color grading LUT texture used in the effect if colorGradingEnabled is set to true
  87326. */
  87327. get: function () {
  87328. return this._colorGradingTexture;
  87329. },
  87330. /**
  87331. * Color grading LUT texture used in the effect if colorGradingEnabled is set to true
  87332. */
  87333. set: function (value) {
  87334. if (this._colorGradingTexture === value) {
  87335. return;
  87336. }
  87337. this._colorGradingTexture = value;
  87338. this._updateParameters();
  87339. },
  87340. enumerable: true,
  87341. configurable: true
  87342. });
  87343. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  87344. /**
  87345. * Gets wether the color grading effect is enabled.
  87346. */
  87347. get: function () {
  87348. return this._colorGradingEnabled;
  87349. },
  87350. /**
  87351. * Sets wether the color grading effect is enabled.
  87352. */
  87353. set: function (value) {
  87354. if (this._colorGradingEnabled === value) {
  87355. return;
  87356. }
  87357. this._colorGradingEnabled = value;
  87358. this._updateParameters();
  87359. },
  87360. enumerable: true,
  87361. configurable: true
  87362. });
  87363. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  87364. /**
  87365. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  87366. */
  87367. get: function () {
  87368. return this._colorGradingWithGreenDepth;
  87369. },
  87370. /**
  87371. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  87372. */
  87373. set: function (value) {
  87374. if (this._colorGradingWithGreenDepth === value) {
  87375. return;
  87376. }
  87377. this._colorGradingWithGreenDepth = value;
  87378. this._updateParameters();
  87379. },
  87380. enumerable: true,
  87381. configurable: true
  87382. });
  87383. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  87384. /**
  87385. * Gets wether the color grading texture contains BGR values.
  87386. */
  87387. get: function () {
  87388. return this._colorGradingBGR;
  87389. },
  87390. /**
  87391. * Sets wether the color grading texture contains BGR values.
  87392. */
  87393. set: function (value) {
  87394. if (this._colorGradingBGR === value) {
  87395. return;
  87396. }
  87397. this._colorGradingBGR = value;
  87398. this._updateParameters();
  87399. },
  87400. enumerable: true,
  87401. configurable: true
  87402. });
  87403. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  87404. /**
  87405. * Gets the Exposure used in the effect.
  87406. */
  87407. get: function () {
  87408. return this._exposure;
  87409. },
  87410. /**
  87411. * Sets the Exposure used in the effect.
  87412. */
  87413. set: function (value) {
  87414. if (this._exposure === value) {
  87415. return;
  87416. }
  87417. this._exposure = value;
  87418. this._updateParameters();
  87419. },
  87420. enumerable: true,
  87421. configurable: true
  87422. });
  87423. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  87424. /**
  87425. * Gets wether the tone mapping effect is enabled.
  87426. */
  87427. get: function () {
  87428. return this._toneMappingEnabled;
  87429. },
  87430. /**
  87431. * Sets wether the tone mapping effect is enabled.
  87432. */
  87433. set: function (value) {
  87434. if (this._toneMappingEnabled === value) {
  87435. return;
  87436. }
  87437. this._toneMappingEnabled = value;
  87438. this._updateParameters();
  87439. },
  87440. enumerable: true,
  87441. configurable: true
  87442. });
  87443. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingType", {
  87444. /**
  87445. * Gets the type of tone mapping effect.
  87446. */
  87447. get: function () {
  87448. return this._toneMappingType;
  87449. },
  87450. /**
  87451. * Sets the type of tone mapping effect used in BabylonJS.
  87452. */
  87453. set: function (value) {
  87454. if (this._toneMappingType === value) {
  87455. return;
  87456. }
  87457. this._toneMappingType = value;
  87458. this._updateParameters();
  87459. },
  87460. enumerable: true,
  87461. configurable: true
  87462. });
  87463. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  87464. /**
  87465. * Gets the contrast used in the effect.
  87466. */
  87467. get: function () {
  87468. return this._contrast;
  87469. },
  87470. /**
  87471. * Sets the contrast used in the effect.
  87472. */
  87473. set: function (value) {
  87474. if (this._contrast === value) {
  87475. return;
  87476. }
  87477. this._contrast = value;
  87478. this._updateParameters();
  87479. },
  87480. enumerable: true,
  87481. configurable: true
  87482. });
  87483. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  87484. /**
  87485. * Gets the vignette blend mode allowing different kind of effect.
  87486. */
  87487. get: function () {
  87488. return this._vignetteBlendMode;
  87489. },
  87490. /**
  87491. * Sets the vignette blend mode allowing different kind of effect.
  87492. */
  87493. set: function (value) {
  87494. if (this._vignetteBlendMode === value) {
  87495. return;
  87496. }
  87497. this._vignetteBlendMode = value;
  87498. this._updateParameters();
  87499. },
  87500. enumerable: true,
  87501. configurable: true
  87502. });
  87503. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  87504. /**
  87505. * Gets wether the vignette effect is enabled.
  87506. */
  87507. get: function () {
  87508. return this._vignetteEnabled;
  87509. },
  87510. /**
  87511. * Sets wether the vignette effect is enabled.
  87512. */
  87513. set: function (value) {
  87514. if (this._vignetteEnabled === value) {
  87515. return;
  87516. }
  87517. this._vignetteEnabled = value;
  87518. this._updateParameters();
  87519. },
  87520. enumerable: true,
  87521. configurable: true
  87522. });
  87523. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  87524. /**
  87525. * Gets wether the image processing is applied through a post process or not.
  87526. */
  87527. get: function () {
  87528. return this._applyByPostProcess;
  87529. },
  87530. /**
  87531. * Sets wether the image processing is applied through a post process or not.
  87532. */
  87533. set: function (value) {
  87534. if (this._applyByPostProcess === value) {
  87535. return;
  87536. }
  87537. this._applyByPostProcess = value;
  87538. this._updateParameters();
  87539. },
  87540. enumerable: true,
  87541. configurable: true
  87542. });
  87543. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  87544. /**
  87545. * Gets wether the image processing is enabled or not.
  87546. */
  87547. get: function () {
  87548. return this._isEnabled;
  87549. },
  87550. /**
  87551. * Sets wether the image processing is enabled or not.
  87552. */
  87553. set: function (value) {
  87554. if (this._isEnabled === value) {
  87555. return;
  87556. }
  87557. this._isEnabled = value;
  87558. this._updateParameters();
  87559. },
  87560. enumerable: true,
  87561. configurable: true
  87562. });
  87563. /**
  87564. * Method called each time the image processing information changes requires to recompile the effect.
  87565. */
  87566. ImageProcessingConfiguration.prototype._updateParameters = function () {
  87567. this.onUpdateParameters.notifyObservers(this);
  87568. };
  87569. /**
  87570. * Gets the current class name.
  87571. * @return "ImageProcessingConfiguration"
  87572. */
  87573. ImageProcessingConfiguration.prototype.getClassName = function () {
  87574. return "ImageProcessingConfiguration";
  87575. };
  87576. /**
  87577. * Prepare the list of uniforms associated with the Image Processing effects.
  87578. * @param uniforms The list of uniforms used in the effect
  87579. * @param defines the list of defines currently in use
  87580. */
  87581. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  87582. if (defines.EXPOSURE) {
  87583. uniforms.push("exposureLinear");
  87584. }
  87585. if (defines.CONTRAST) {
  87586. uniforms.push("contrast");
  87587. }
  87588. if (defines.COLORGRADING) {
  87589. uniforms.push("colorTransformSettings");
  87590. }
  87591. if (defines.VIGNETTE) {
  87592. uniforms.push("vInverseScreenSize");
  87593. uniforms.push("vignetteSettings1");
  87594. uniforms.push("vignetteSettings2");
  87595. }
  87596. if (defines.COLORCURVES) {
  87597. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  87598. }
  87599. };
  87600. /**
  87601. * Prepare the list of samplers associated with the Image Processing effects.
  87602. * @param samplersList The list of uniforms used in the effect
  87603. * @param defines the list of defines currently in use
  87604. */
  87605. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  87606. if (defines.COLORGRADING) {
  87607. samplersList.push("txColorTransform");
  87608. }
  87609. };
  87610. /**
  87611. * Prepare the list of defines associated to the shader.
  87612. * @param defines the list of defines to complete
  87613. * @param forPostProcess Define if we are currently in post process mode or not
  87614. */
  87615. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  87616. if (forPostProcess === void 0) { forPostProcess = false; }
  87617. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  87618. defines.VIGNETTE = false;
  87619. defines.TONEMAPPING = false;
  87620. defines.TONEMAPPING_ACES = false;
  87621. defines.CONTRAST = false;
  87622. defines.EXPOSURE = false;
  87623. defines.COLORCURVES = false;
  87624. defines.COLORGRADING = false;
  87625. defines.COLORGRADING3D = false;
  87626. defines.IMAGEPROCESSING = false;
  87627. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  87628. return;
  87629. }
  87630. defines.VIGNETTE = this.vignetteEnabled;
  87631. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  87632. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  87633. defines.TONEMAPPING = this.toneMappingEnabled;
  87634. switch (this._toneMappingType) {
  87635. case ImageProcessingConfiguration.TONEMAPPING_ACES:
  87636. defines.TONEMAPPING_ACES = true;
  87637. break;
  87638. }
  87639. defines.CONTRAST = (this.contrast !== 1.0);
  87640. defines.EXPOSURE = (this.exposure !== 1.0);
  87641. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  87642. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  87643. if (defines.COLORGRADING) {
  87644. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  87645. }
  87646. else {
  87647. defines.COLORGRADING3D = false;
  87648. }
  87649. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  87650. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  87651. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  87652. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  87653. };
  87654. /**
  87655. * Returns true if all the image processing information are ready.
  87656. * @returns True if ready, otherwise, false
  87657. */
  87658. ImageProcessingConfiguration.prototype.isReady = function () {
  87659. // Color Grading texure can not be none blocking.
  87660. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  87661. };
  87662. /**
  87663. * Binds the image processing to the shader.
  87664. * @param effect The effect to bind to
  87665. * @param aspectRatio Define the current aspect ratio of the effect
  87666. */
  87667. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  87668. if (aspectRatio === void 0) { aspectRatio = 1; }
  87669. // Color Curves
  87670. if (this._colorCurvesEnabled && this.colorCurves) {
  87671. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  87672. }
  87673. // Vignette
  87674. if (this._vignetteEnabled) {
  87675. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  87676. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  87677. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  87678. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  87679. var vignetteScaleX = vignetteScaleY * aspectRatio;
  87680. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  87681. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  87682. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  87683. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  87684. var vignettePower = -2.0 * this.vignetteWeight;
  87685. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  87686. }
  87687. // Exposure
  87688. effect.setFloat("exposureLinear", this.exposure);
  87689. // Contrast
  87690. effect.setFloat("contrast", this.contrast);
  87691. // Color transform settings
  87692. if (this.colorGradingTexture) {
  87693. effect.setTexture("txColorTransform", this.colorGradingTexture);
  87694. var textureSize = this.colorGradingTexture.getSize().height;
  87695. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  87696. 0.5 / textureSize, // textureOffset
  87697. textureSize, // textureSize
  87698. this.colorGradingTexture.level // weight
  87699. );
  87700. }
  87701. };
  87702. /**
  87703. * Clones the current image processing instance.
  87704. * @return The cloned image processing
  87705. */
  87706. ImageProcessingConfiguration.prototype.clone = function () {
  87707. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  87708. };
  87709. /**
  87710. * Serializes the current image processing instance to a json representation.
  87711. * @return a JSON representation
  87712. */
  87713. ImageProcessingConfiguration.prototype.serialize = function () {
  87714. return BABYLON.SerializationHelper.Serialize(this);
  87715. };
  87716. /**
  87717. * Parses the image processing from a json representation.
  87718. * @param source the JSON source to parse
  87719. * @return The parsed image processing
  87720. */
  87721. ImageProcessingConfiguration.Parse = function (source) {
  87722. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  87723. };
  87724. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  87725. /**
  87726. * Used to apply the vignette as a mix with the pixel color.
  87727. */
  87728. get: function () {
  87729. return this._VIGNETTEMODE_MULTIPLY;
  87730. },
  87731. enumerable: true,
  87732. configurable: true
  87733. });
  87734. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  87735. /**
  87736. * Used to apply the vignette as a replacement of the pixel color.
  87737. */
  87738. get: function () {
  87739. return this._VIGNETTEMODE_OPAQUE;
  87740. },
  87741. enumerable: true,
  87742. configurable: true
  87743. });
  87744. /**
  87745. * Default tone mapping applied in BabylonJS.
  87746. */
  87747. ImageProcessingConfiguration.TONEMAPPING_STANDARD = 0;
  87748. /**
  87749. * ACES Tone mapping (used by default in unreal and unity). This can help getting closer
  87750. * to other engines rendering to increase portability.
  87751. */
  87752. ImageProcessingConfiguration.TONEMAPPING_ACES = 1;
  87753. // Static constants associated to the image processing.
  87754. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  87755. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  87756. __decorate([
  87757. BABYLON.serializeAsColorCurves()
  87758. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  87759. __decorate([
  87760. BABYLON.serialize()
  87761. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  87762. __decorate([
  87763. BABYLON.serializeAsTexture("colorGradingTexture")
  87764. ], ImageProcessingConfiguration.prototype, "_colorGradingTexture", void 0);
  87765. __decorate([
  87766. BABYLON.serialize()
  87767. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  87768. __decorate([
  87769. BABYLON.serialize()
  87770. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  87771. __decorate([
  87772. BABYLON.serialize()
  87773. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  87774. __decorate([
  87775. BABYLON.serialize()
  87776. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  87777. __decorate([
  87778. BABYLON.serialize()
  87779. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  87780. __decorate([
  87781. BABYLON.serialize()
  87782. ], ImageProcessingConfiguration.prototype, "_toneMappingType", void 0);
  87783. __decorate([
  87784. BABYLON.serialize()
  87785. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  87786. __decorate([
  87787. BABYLON.serialize()
  87788. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  87789. __decorate([
  87790. BABYLON.serialize()
  87791. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  87792. __decorate([
  87793. BABYLON.serialize()
  87794. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  87795. __decorate([
  87796. BABYLON.serialize()
  87797. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  87798. __decorate([
  87799. BABYLON.serializeAsColor4()
  87800. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  87801. __decorate([
  87802. BABYLON.serialize()
  87803. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  87804. __decorate([
  87805. BABYLON.serialize()
  87806. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  87807. __decorate([
  87808. BABYLON.serialize()
  87809. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  87810. __decorate([
  87811. BABYLON.serialize()
  87812. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  87813. __decorate([
  87814. BABYLON.serialize()
  87815. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  87816. return ImageProcessingConfiguration;
  87817. }());
  87818. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  87819. })(BABYLON || (BABYLON = {}));
  87820. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  87821. var BABYLON;
  87822. (function (BABYLON) {
  87823. /**
  87824. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  87825. * It can help converting any input color in a desired output one. This can then be used to create effects
  87826. * from sepia, black and white to sixties or futuristic rendering...
  87827. *
  87828. * The only supported format is currently 3dl.
  87829. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table
  87830. */
  87831. var ColorGradingTexture = /** @class */ (function (_super) {
  87832. __extends(ColorGradingTexture, _super);
  87833. /**
  87834. * Instantiates a ColorGradingTexture from the following parameters.
  87835. *
  87836. * @param url The location of the color gradind data (currently only supporting 3dl)
  87837. * @param scene The scene the texture will be used in
  87838. */
  87839. function ColorGradingTexture(url, scene) {
  87840. var _this = _super.call(this, scene) || this;
  87841. if (!url) {
  87842. return _this;
  87843. }
  87844. _this._engine = scene.getEngine();
  87845. _this._textureMatrix = BABYLON.Matrix.Identity();
  87846. _this.name = url;
  87847. _this.url = url;
  87848. _this.hasAlpha = false;
  87849. _this.isCube = false;
  87850. _this.is3D = _this._engine.webGLVersion > 1;
  87851. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87852. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87853. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87854. _this.anisotropicFilteringLevel = 1;
  87855. _this._texture = _this._getFromCache(url, true);
  87856. if (!_this._texture) {
  87857. if (!scene.useDelayedTextureLoading) {
  87858. _this.loadTexture();
  87859. }
  87860. else {
  87861. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  87862. }
  87863. }
  87864. return _this;
  87865. }
  87866. /**
  87867. * Returns the texture matrix used in most of the material.
  87868. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  87869. */
  87870. ColorGradingTexture.prototype.getTextureMatrix = function () {
  87871. return this._textureMatrix;
  87872. };
  87873. /**
  87874. * Occurs when the file being loaded is a .3dl LUT file.
  87875. */
  87876. ColorGradingTexture.prototype.load3dlTexture = function () {
  87877. var engine = this._engine;
  87878. var texture;
  87879. if (engine.webGLVersion === 1) {
  87880. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  87881. }
  87882. else {
  87883. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  87884. }
  87885. this._texture = texture;
  87886. var callback = function (text) {
  87887. if (typeof text !== "string") {
  87888. return;
  87889. }
  87890. var data = null;
  87891. var tempData = null;
  87892. var line;
  87893. var lines = text.split('\n');
  87894. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  87895. var maxColor = 0;
  87896. for (var i = 0; i < lines.length; i++) {
  87897. line = lines[i];
  87898. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  87899. continue;
  87900. if (line.indexOf('#') === 0)
  87901. continue;
  87902. var words = line.split(" ");
  87903. if (size === 0) {
  87904. // Number of space + one
  87905. size = words.length;
  87906. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  87907. tempData = new Float32Array(size * size * size * 4);
  87908. continue;
  87909. }
  87910. if (size != 0) {
  87911. var r = Math.max(parseInt(words[0]), 0);
  87912. var g = Math.max(parseInt(words[1]), 0);
  87913. var b = Math.max(parseInt(words[2]), 0);
  87914. maxColor = Math.max(r, maxColor);
  87915. maxColor = Math.max(g, maxColor);
  87916. maxColor = Math.max(b, maxColor);
  87917. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  87918. if (tempData) {
  87919. tempData[pixelStorageIndex + 0] = r;
  87920. tempData[pixelStorageIndex + 1] = g;
  87921. tempData[pixelStorageIndex + 2] = b;
  87922. }
  87923. // Keep for reference in case of back compat problems.
  87924. // pixelIndexSlice++;
  87925. // if (pixelIndexSlice % size == 0) {
  87926. // pixelIndexH++;
  87927. // pixelIndexSlice = 0;
  87928. // if (pixelIndexH % size == 0) {
  87929. // pixelIndexW++;
  87930. // pixelIndexH = 0;
  87931. // }
  87932. // }
  87933. pixelIndexH++;
  87934. if (pixelIndexH % size == 0) {
  87935. pixelIndexSlice++;
  87936. pixelIndexH = 0;
  87937. if (pixelIndexSlice % size == 0) {
  87938. pixelIndexW++;
  87939. pixelIndexSlice = 0;
  87940. }
  87941. }
  87942. }
  87943. }
  87944. if (tempData && data) {
  87945. for (var i = 0; i < tempData.length; i++) {
  87946. if (i > 0 && (i + 1) % 4 === 0) {
  87947. data[i] = 255;
  87948. }
  87949. else {
  87950. var value = tempData[i];
  87951. data[i] = (value / maxColor * 255);
  87952. }
  87953. }
  87954. }
  87955. if (texture.is3D) {
  87956. texture.updateSize(size, size, size);
  87957. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  87958. }
  87959. else {
  87960. texture.updateSize(size * size, size);
  87961. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  87962. }
  87963. };
  87964. var scene = this.getScene();
  87965. if (scene) {
  87966. scene._loadFile(this.url, callback);
  87967. }
  87968. else {
  87969. this._engine._loadFile(this.url, callback);
  87970. }
  87971. return this._texture;
  87972. };
  87973. /**
  87974. * Starts the loading process of the texture.
  87975. */
  87976. ColorGradingTexture.prototype.loadTexture = function () {
  87977. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  87978. this.load3dlTexture();
  87979. }
  87980. };
  87981. /**
  87982. * Clones the color gradind texture.
  87983. */
  87984. ColorGradingTexture.prototype.clone = function () {
  87985. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  87986. // Base texture
  87987. newTexture.level = this.level;
  87988. return newTexture;
  87989. };
  87990. /**
  87991. * Called during delayed load for textures.
  87992. */
  87993. ColorGradingTexture.prototype.delayLoad = function () {
  87994. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  87995. return;
  87996. }
  87997. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  87998. this._texture = this._getFromCache(this.url, true);
  87999. if (!this._texture) {
  88000. this.loadTexture();
  88001. }
  88002. };
  88003. /**
  88004. * Parses a color grading texture serialized by Babylon.
  88005. * @param parsedTexture The texture information being parsedTexture
  88006. * @param scene The scene to load the texture in
  88007. * @param rootUrl The root url of the data assets to load
  88008. * @return A color gradind texture
  88009. */
  88010. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  88011. var texture = null;
  88012. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  88013. texture = new ColorGradingTexture(parsedTexture.name, scene);
  88014. texture.name = parsedTexture.name;
  88015. texture.level = parsedTexture.level;
  88016. }
  88017. return texture;
  88018. };
  88019. /**
  88020. * Serializes the LUT texture to json format.
  88021. */
  88022. ColorGradingTexture.prototype.serialize = function () {
  88023. if (!this.name) {
  88024. return null;
  88025. }
  88026. var serializationObject = {};
  88027. serializationObject.name = this.name;
  88028. serializationObject.level = this.level;
  88029. serializationObject.customType = "BABYLON.ColorGradingTexture";
  88030. return serializationObject;
  88031. };
  88032. /**
  88033. * Empty line regex stored for GC.
  88034. */
  88035. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  88036. return ColorGradingTexture;
  88037. }(BABYLON.BaseTexture));
  88038. BABYLON.ColorGradingTexture = ColorGradingTexture;
  88039. })(BABYLON || (BABYLON = {}));
  88040. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  88041. var BABYLON;
  88042. (function (BABYLON) {
  88043. /**
  88044. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  88045. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  88046. * 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;
  88047. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  88048. */
  88049. var ColorCurves = /** @class */ (function () {
  88050. function ColorCurves() {
  88051. this._dirty = true;
  88052. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  88053. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  88054. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  88055. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  88056. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  88057. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  88058. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  88059. this._globalHue = 30;
  88060. this._globalDensity = 0;
  88061. this._globalSaturation = 0;
  88062. this._globalExposure = 0;
  88063. this._highlightsHue = 30;
  88064. this._highlightsDensity = 0;
  88065. this._highlightsSaturation = 0;
  88066. this._highlightsExposure = 0;
  88067. this._midtonesHue = 30;
  88068. this._midtonesDensity = 0;
  88069. this._midtonesSaturation = 0;
  88070. this._midtonesExposure = 0;
  88071. this._shadowsHue = 30;
  88072. this._shadowsDensity = 0;
  88073. this._shadowsSaturation = 0;
  88074. this._shadowsExposure = 0;
  88075. }
  88076. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  88077. /**
  88078. * Gets the global Hue value.
  88079. * 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).
  88080. */
  88081. get: function () {
  88082. return this._globalHue;
  88083. },
  88084. /**
  88085. * Sets the global Hue value.
  88086. * 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).
  88087. */
  88088. set: function (value) {
  88089. this._globalHue = value;
  88090. this._dirty = true;
  88091. },
  88092. enumerable: true,
  88093. configurable: true
  88094. });
  88095. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  88096. /**
  88097. * Gets the global Density value.
  88098. * 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.
  88099. * Values less than zero provide a filter of opposite hue.
  88100. */
  88101. get: function () {
  88102. return this._globalDensity;
  88103. },
  88104. /**
  88105. * Sets the global Density value.
  88106. * 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.
  88107. * Values less than zero provide a filter of opposite hue.
  88108. */
  88109. set: function (value) {
  88110. this._globalDensity = value;
  88111. this._dirty = true;
  88112. },
  88113. enumerable: true,
  88114. configurable: true
  88115. });
  88116. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  88117. /**
  88118. * Gets the global Saturation value.
  88119. * 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.
  88120. */
  88121. get: function () {
  88122. return this._globalSaturation;
  88123. },
  88124. /**
  88125. * Sets the global Saturation value.
  88126. * 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.
  88127. */
  88128. set: function (value) {
  88129. this._globalSaturation = value;
  88130. this._dirty = true;
  88131. },
  88132. enumerable: true,
  88133. configurable: true
  88134. });
  88135. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  88136. /**
  88137. * Gets the global Exposure value.
  88138. * 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.
  88139. */
  88140. get: function () {
  88141. return this._globalExposure;
  88142. },
  88143. /**
  88144. * Sets the global Exposure value.
  88145. * 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.
  88146. */
  88147. set: function (value) {
  88148. this._globalExposure = value;
  88149. this._dirty = true;
  88150. },
  88151. enumerable: true,
  88152. configurable: true
  88153. });
  88154. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  88155. /**
  88156. * Gets the highlights Hue value.
  88157. * 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).
  88158. */
  88159. get: function () {
  88160. return this._highlightsHue;
  88161. },
  88162. /**
  88163. * Sets the highlights Hue value.
  88164. * 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).
  88165. */
  88166. set: function (value) {
  88167. this._highlightsHue = value;
  88168. this._dirty = true;
  88169. },
  88170. enumerable: true,
  88171. configurable: true
  88172. });
  88173. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  88174. /**
  88175. * Gets the highlights Density value.
  88176. * 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.
  88177. * Values less than zero provide a filter of opposite hue.
  88178. */
  88179. get: function () {
  88180. return this._highlightsDensity;
  88181. },
  88182. /**
  88183. * Sets the highlights Density value.
  88184. * 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.
  88185. * Values less than zero provide a filter of opposite hue.
  88186. */
  88187. set: function (value) {
  88188. this._highlightsDensity = value;
  88189. this._dirty = true;
  88190. },
  88191. enumerable: true,
  88192. configurable: true
  88193. });
  88194. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  88195. /**
  88196. * Gets the highlights Saturation value.
  88197. * 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.
  88198. */
  88199. get: function () {
  88200. return this._highlightsSaturation;
  88201. },
  88202. /**
  88203. * Sets the highlights Saturation value.
  88204. * 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.
  88205. */
  88206. set: function (value) {
  88207. this._highlightsSaturation = value;
  88208. this._dirty = true;
  88209. },
  88210. enumerable: true,
  88211. configurable: true
  88212. });
  88213. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  88214. /**
  88215. * Gets the highlights Exposure value.
  88216. * 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.
  88217. */
  88218. get: function () {
  88219. return this._highlightsExposure;
  88220. },
  88221. /**
  88222. * Sets the highlights Exposure value.
  88223. * 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.
  88224. */
  88225. set: function (value) {
  88226. this._highlightsExposure = value;
  88227. this._dirty = true;
  88228. },
  88229. enumerable: true,
  88230. configurable: true
  88231. });
  88232. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  88233. /**
  88234. * Gets the midtones Hue value.
  88235. * 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).
  88236. */
  88237. get: function () {
  88238. return this._midtonesHue;
  88239. },
  88240. /**
  88241. * Sets the midtones Hue value.
  88242. * 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).
  88243. */
  88244. set: function (value) {
  88245. this._midtonesHue = value;
  88246. this._dirty = true;
  88247. },
  88248. enumerable: true,
  88249. configurable: true
  88250. });
  88251. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  88252. /**
  88253. * Gets the midtones Density value.
  88254. * 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.
  88255. * Values less than zero provide a filter of opposite hue.
  88256. */
  88257. get: function () {
  88258. return this._midtonesDensity;
  88259. },
  88260. /**
  88261. * Sets the midtones Density value.
  88262. * 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.
  88263. * Values less than zero provide a filter of opposite hue.
  88264. */
  88265. set: function (value) {
  88266. this._midtonesDensity = value;
  88267. this._dirty = true;
  88268. },
  88269. enumerable: true,
  88270. configurable: true
  88271. });
  88272. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  88273. /**
  88274. * Gets the midtones Saturation value.
  88275. * 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.
  88276. */
  88277. get: function () {
  88278. return this._midtonesSaturation;
  88279. },
  88280. /**
  88281. * Sets the midtones Saturation value.
  88282. * 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.
  88283. */
  88284. set: function (value) {
  88285. this._midtonesSaturation = value;
  88286. this._dirty = true;
  88287. },
  88288. enumerable: true,
  88289. configurable: true
  88290. });
  88291. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  88292. /**
  88293. * Gets the midtones Exposure value.
  88294. * 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.
  88295. */
  88296. get: function () {
  88297. return this._midtonesExposure;
  88298. },
  88299. /**
  88300. * Sets the midtones Exposure value.
  88301. * 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.
  88302. */
  88303. set: function (value) {
  88304. this._midtonesExposure = value;
  88305. this._dirty = true;
  88306. },
  88307. enumerable: true,
  88308. configurable: true
  88309. });
  88310. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  88311. /**
  88312. * Gets the shadows Hue value.
  88313. * 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).
  88314. */
  88315. get: function () {
  88316. return this._shadowsHue;
  88317. },
  88318. /**
  88319. * Sets the shadows Hue value.
  88320. * 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).
  88321. */
  88322. set: function (value) {
  88323. this._shadowsHue = value;
  88324. this._dirty = true;
  88325. },
  88326. enumerable: true,
  88327. configurable: true
  88328. });
  88329. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  88330. /**
  88331. * Gets the shadows Density value.
  88332. * 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.
  88333. * Values less than zero provide a filter of opposite hue.
  88334. */
  88335. get: function () {
  88336. return this._shadowsDensity;
  88337. },
  88338. /**
  88339. * Sets the shadows Density value.
  88340. * 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.
  88341. * Values less than zero provide a filter of opposite hue.
  88342. */
  88343. set: function (value) {
  88344. this._shadowsDensity = value;
  88345. this._dirty = true;
  88346. },
  88347. enumerable: true,
  88348. configurable: true
  88349. });
  88350. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  88351. /**
  88352. * Gets the shadows Saturation value.
  88353. * 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.
  88354. */
  88355. get: function () {
  88356. return this._shadowsSaturation;
  88357. },
  88358. /**
  88359. * Sets the shadows Saturation value.
  88360. * 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.
  88361. */
  88362. set: function (value) {
  88363. this._shadowsSaturation = value;
  88364. this._dirty = true;
  88365. },
  88366. enumerable: true,
  88367. configurable: true
  88368. });
  88369. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  88370. /**
  88371. * Gets the shadows Exposure value.
  88372. * 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.
  88373. */
  88374. get: function () {
  88375. return this._shadowsExposure;
  88376. },
  88377. /**
  88378. * Sets the shadows Exposure value.
  88379. * 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.
  88380. */
  88381. set: function (value) {
  88382. this._shadowsExposure = value;
  88383. this._dirty = true;
  88384. },
  88385. enumerable: true,
  88386. configurable: true
  88387. });
  88388. /**
  88389. * Returns the class name
  88390. * @returns The class name
  88391. */
  88392. ColorCurves.prototype.getClassName = function () {
  88393. return "ColorCurves";
  88394. };
  88395. /**
  88396. * Binds the color curves to the shader.
  88397. * @param colorCurves The color curve to bind
  88398. * @param effect The effect to bind to
  88399. * @param positiveUniform The positive uniform shader parameter
  88400. * @param neutralUniform The neutral uniform shader parameter
  88401. * @param negativeUniform The negative uniform shader parameter
  88402. */
  88403. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  88404. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  88405. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  88406. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  88407. if (colorCurves._dirty) {
  88408. colorCurves._dirty = false;
  88409. // Fill in global info.
  88410. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  88411. // Compute highlights info.
  88412. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  88413. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  88414. // Compute midtones info.
  88415. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  88416. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  88417. // Compute shadows info.
  88418. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  88419. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  88420. // Compute deltas (neutral is midtones).
  88421. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  88422. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  88423. }
  88424. if (effect) {
  88425. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  88426. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  88427. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  88428. }
  88429. };
  88430. /**
  88431. * Prepare the list of uniforms associated with the ColorCurves effects.
  88432. * @param uniformsList The list of uniforms used in the effect
  88433. */
  88434. ColorCurves.PrepareUniforms = function (uniformsList) {
  88435. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  88436. };
  88437. /**
  88438. * Returns color grading data based on a hue, density, saturation and exposure value.
  88439. * @param filterHue The hue of the color filter.
  88440. * @param filterDensity The density of the color filter.
  88441. * @param saturation The saturation.
  88442. * @param exposure The exposure.
  88443. * @param result The result data container.
  88444. */
  88445. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  88446. if (hue == null) {
  88447. return;
  88448. }
  88449. hue = ColorCurves.clamp(hue, 0, 360);
  88450. density = ColorCurves.clamp(density, -100, 100);
  88451. saturation = ColorCurves.clamp(saturation, -100, 100);
  88452. exposure = ColorCurves.clamp(exposure, -100, 100);
  88453. // Remap the slider/config filter density with non-linear mapping and also scale by half
  88454. // so that the maximum filter density is only 50% control. This provides fine control
  88455. // for small values and reasonable range.
  88456. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  88457. density *= 0.5;
  88458. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  88459. if (density < 0) {
  88460. density *= -1;
  88461. hue = (hue + 180) % 360;
  88462. }
  88463. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  88464. result.scaleToRef(2, result);
  88465. result.a = 1 + 0.01 * saturation;
  88466. };
  88467. /**
  88468. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  88469. * @param value The input slider value in range [-100,100].
  88470. * @returns Adjusted value.
  88471. */
  88472. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  88473. value /= 100;
  88474. var x = Math.abs(value);
  88475. x = Math.pow(x, 2);
  88476. if (value < 0) {
  88477. x *= -1;
  88478. }
  88479. x *= 100;
  88480. return x;
  88481. };
  88482. /**
  88483. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  88484. * @param hue The hue (H) input.
  88485. * @param saturation The saturation (S) input.
  88486. * @param brightness The brightness (B) input.
  88487. * @result An RGBA color represented as Vector4.
  88488. */
  88489. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  88490. var h = ColorCurves.clamp(hue, 0, 360);
  88491. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  88492. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  88493. if (s === 0) {
  88494. result.r = v;
  88495. result.g = v;
  88496. result.b = v;
  88497. }
  88498. else {
  88499. // sector 0 to 5
  88500. h /= 60;
  88501. var i = Math.floor(h);
  88502. // fractional part of h
  88503. var f = h - i;
  88504. var p = v * (1 - s);
  88505. var q = v * (1 - s * f);
  88506. var t = v * (1 - s * (1 - f));
  88507. switch (i) {
  88508. case 0:
  88509. result.r = v;
  88510. result.g = t;
  88511. result.b = p;
  88512. break;
  88513. case 1:
  88514. result.r = q;
  88515. result.g = v;
  88516. result.b = p;
  88517. break;
  88518. case 2:
  88519. result.r = p;
  88520. result.g = v;
  88521. result.b = t;
  88522. break;
  88523. case 3:
  88524. result.r = p;
  88525. result.g = q;
  88526. result.b = v;
  88527. break;
  88528. case 4:
  88529. result.r = t;
  88530. result.g = p;
  88531. result.b = v;
  88532. break;
  88533. default: // case 5:
  88534. result.r = v;
  88535. result.g = p;
  88536. result.b = q;
  88537. break;
  88538. }
  88539. }
  88540. result.a = 1;
  88541. };
  88542. /**
  88543. * Returns a value clamped between min and max
  88544. * @param value The value to clamp
  88545. * @param min The minimum of value
  88546. * @param max The maximum of value
  88547. * @returns The clamped value.
  88548. */
  88549. ColorCurves.clamp = function (value, min, max) {
  88550. return Math.min(Math.max(value, min), max);
  88551. };
  88552. /**
  88553. * Clones the current color curve instance.
  88554. * @return The cloned curves
  88555. */
  88556. ColorCurves.prototype.clone = function () {
  88557. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  88558. };
  88559. /**
  88560. * Serializes the current color curve instance to a json representation.
  88561. * @return a JSON representation
  88562. */
  88563. ColorCurves.prototype.serialize = function () {
  88564. return BABYLON.SerializationHelper.Serialize(this);
  88565. };
  88566. /**
  88567. * Parses the color curve from a json representation.
  88568. * @param source the JSON source to parse
  88569. * @return The parsed curves
  88570. */
  88571. ColorCurves.Parse = function (source) {
  88572. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  88573. };
  88574. __decorate([
  88575. BABYLON.serialize()
  88576. ], ColorCurves.prototype, "_globalHue", void 0);
  88577. __decorate([
  88578. BABYLON.serialize()
  88579. ], ColorCurves.prototype, "_globalDensity", void 0);
  88580. __decorate([
  88581. BABYLON.serialize()
  88582. ], ColorCurves.prototype, "_globalSaturation", void 0);
  88583. __decorate([
  88584. BABYLON.serialize()
  88585. ], ColorCurves.prototype, "_globalExposure", void 0);
  88586. __decorate([
  88587. BABYLON.serialize()
  88588. ], ColorCurves.prototype, "_highlightsHue", void 0);
  88589. __decorate([
  88590. BABYLON.serialize()
  88591. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  88592. __decorate([
  88593. BABYLON.serialize()
  88594. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  88595. __decorate([
  88596. BABYLON.serialize()
  88597. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  88598. __decorate([
  88599. BABYLON.serialize()
  88600. ], ColorCurves.prototype, "_midtonesHue", void 0);
  88601. __decorate([
  88602. BABYLON.serialize()
  88603. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  88604. __decorate([
  88605. BABYLON.serialize()
  88606. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  88607. __decorate([
  88608. BABYLON.serialize()
  88609. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  88610. return ColorCurves;
  88611. }());
  88612. BABYLON.ColorCurves = ColorCurves;
  88613. })(BABYLON || (BABYLON = {}));
  88614. //# sourceMappingURL=babylon.colorCurves.js.map
  88615. var BABYLON;
  88616. (function (BABYLON) {
  88617. /**
  88618. * Post process which applies a refractin texture
  88619. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#refraction
  88620. */
  88621. var RefractionPostProcess = /** @class */ (function (_super) {
  88622. __extends(RefractionPostProcess, _super);
  88623. /**
  88624. * Initializes the RefractionPostProcess
  88625. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#refraction
  88626. * @param name The name of the effect.
  88627. * @param refractionTextureUrl Url of the refraction texture to use
  88628. * @param color the base color of the refraction (used to taint the rendering)
  88629. * @param depth simulated refraction depth
  88630. * @param colorLevel the coefficient of the base color (0 to remove base color tainting)
  88631. * @param camera The camera to apply the render pass to.
  88632. * @param options The required width/height ratio to downsize to before computing the render pass.
  88633. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  88634. * @param engine The engine which the post process will be applied. (default: current engine)
  88635. * @param reusable If the post process can be reused on the same frame. (default: false)
  88636. */
  88637. function RefractionPostProcess(name, refractionTextureUrl,
  88638. /** the base color of the refraction (used to taint the rendering) */
  88639. color,
  88640. /** simulated refraction depth */
  88641. depth,
  88642. /** the coefficient of the base color (0 to remove base color tainting) */
  88643. colorLevel, options, camera, samplingMode, engine, reusable) {
  88644. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  88645. _this.color = color;
  88646. _this.depth = depth;
  88647. _this.colorLevel = colorLevel;
  88648. _this._ownRefractionTexture = true;
  88649. _this.onActivateObservable.add(function (cam) {
  88650. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  88651. });
  88652. _this.onApplyObservable.add(function (effect) {
  88653. effect.setColor3("baseColor", _this.color);
  88654. effect.setFloat("depth", _this.depth);
  88655. effect.setFloat("colorLevel", _this.colorLevel);
  88656. effect.setTexture("refractionSampler", _this._refTexture);
  88657. });
  88658. return _this;
  88659. }
  88660. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  88661. /**
  88662. * Gets or sets the refraction texture
  88663. * Please note that you are responsible for disposing the texture if you set it manually
  88664. */
  88665. get: function () {
  88666. return this._refTexture;
  88667. },
  88668. set: function (value) {
  88669. if (this._refTexture && this._ownRefractionTexture) {
  88670. this._refTexture.dispose();
  88671. }
  88672. this._refTexture = value;
  88673. this._ownRefractionTexture = false;
  88674. },
  88675. enumerable: true,
  88676. configurable: true
  88677. });
  88678. // Methods
  88679. /**
  88680. * Disposes of the post process
  88681. * @param camera Camera to dispose post process on
  88682. */
  88683. RefractionPostProcess.prototype.dispose = function (camera) {
  88684. if (this._refTexture && this._ownRefractionTexture) {
  88685. this._refTexture.dispose();
  88686. this._refTexture = null;
  88687. }
  88688. _super.prototype.dispose.call(this, camera);
  88689. };
  88690. return RefractionPostProcess;
  88691. }(BABYLON.PostProcess));
  88692. BABYLON.RefractionPostProcess = RefractionPostProcess;
  88693. })(BABYLON || (BABYLON = {}));
  88694. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  88695. var BABYLON;
  88696. (function (BABYLON) {
  88697. /**
  88698. * Post process used to render in black and white
  88699. */
  88700. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  88701. __extends(BlackAndWhitePostProcess, _super);
  88702. /**
  88703. * Creates a black and white post process
  88704. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#black-and-white
  88705. * @param name The name of the effect.
  88706. * @param options The required width/height ratio to downsize to before computing the render pass.
  88707. * @param camera The camera to apply the render pass to.
  88708. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  88709. * @param engine The engine which the post process will be applied. (default: current engine)
  88710. * @param reusable If the post process can be reused on the same frame. (default: false)
  88711. */
  88712. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  88713. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  88714. /**
  88715. * Linear about to convert he result to black and white (default: 1)
  88716. */
  88717. _this.degree = 1;
  88718. _this.onApplyObservable.add(function (effect) {
  88719. effect.setFloat("degree", _this.degree);
  88720. });
  88721. return _this;
  88722. }
  88723. return BlackAndWhitePostProcess;
  88724. }(BABYLON.PostProcess));
  88725. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  88726. })(BABYLON || (BABYLON = {}));
  88727. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  88728. var BABYLON;
  88729. (function (BABYLON) {
  88730. /**
  88731. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  88732. * input texture to perform effects such as edge detection or sharpening
  88733. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  88734. */
  88735. var ConvolutionPostProcess = /** @class */ (function (_super) {
  88736. __extends(ConvolutionPostProcess, _super);
  88737. /**
  88738. * Creates a new instance ConvolutionPostProcess
  88739. * @param name The name of the effect.
  88740. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  88741. * @param options The required width/height ratio to downsize to before computing the render pass.
  88742. * @param camera The camera to apply the render pass to.
  88743. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  88744. * @param engine The engine which the post process will be applied. (default: current engine)
  88745. * @param reusable If the post process can be reused on the same frame. (default: false)
  88746. * @param textureType Type of textures used when performing the post process. (default: 0)
  88747. */
  88748. function ConvolutionPostProcess(name,
  88749. /** Array of 9 values corrisponding to the 3x3 kernel to be applied */
  88750. kernel, options, camera, samplingMode, engine, reusable, textureType) {
  88751. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  88752. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  88753. _this.kernel = kernel;
  88754. _this.onApply = function (effect) {
  88755. effect.setFloat2("screenSize", _this.width, _this.height);
  88756. effect.setArray("kernel", _this.kernel);
  88757. };
  88758. return _this;
  88759. }
  88760. // Statics
  88761. /**
  88762. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  88763. */
  88764. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  88765. /**
  88766. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  88767. */
  88768. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  88769. /**
  88770. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  88771. */
  88772. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  88773. /**
  88774. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  88775. */
  88776. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  88777. /**
  88778. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  88779. */
  88780. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  88781. /**
  88782. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  88783. */
  88784. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  88785. return ConvolutionPostProcess;
  88786. }(BABYLON.PostProcess));
  88787. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  88788. })(BABYLON || (BABYLON = {}));
  88789. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  88790. var BABYLON;
  88791. (function (BABYLON) {
  88792. /**
  88793. * Applies a kernel filter to the image
  88794. */
  88795. var FilterPostProcess = /** @class */ (function (_super) {
  88796. __extends(FilterPostProcess, _super);
  88797. /**
  88798. *
  88799. * @param name The name of the effect.
  88800. * @param kernelMatrix The matrix to be applied to the image
  88801. * @param options The required width/height ratio to downsize to before computing the render pass.
  88802. * @param camera The camera to apply the render pass to.
  88803. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  88804. * @param engine The engine which the post process will be applied. (default: current engine)
  88805. * @param reusable If the post process can be reused on the same frame. (default: false)
  88806. */
  88807. function FilterPostProcess(name,
  88808. /** The matrix to be applied to the image */
  88809. kernelMatrix, options, camera, samplingMode, engine, reusable) {
  88810. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  88811. _this.kernelMatrix = kernelMatrix;
  88812. _this.onApply = function (effect) {
  88813. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  88814. };
  88815. return _this;
  88816. }
  88817. return FilterPostProcess;
  88818. }(BABYLON.PostProcess));
  88819. BABYLON.FilterPostProcess = FilterPostProcess;
  88820. })(BABYLON || (BABYLON = {}));
  88821. //# sourceMappingURL=babylon.filterPostProcess.js.map
  88822. var BABYLON;
  88823. (function (BABYLON) {
  88824. /**
  88825. * Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  88826. */
  88827. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  88828. __extends(VolumetricLightScatteringPostProcess, _super);
  88829. /**
  88830. * @constructor
  88831. * @param {string} name - The post-process name
  88832. * @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)
  88833. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  88834. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  88835. * @param {number} samples - The post-process quality, default 100
  88836. * @param {number} samplingMode - The post-process filtering mode
  88837. * @param {BABYLON.Engine} engine - The babylon engine
  88838. * @param {boolean} reusable - If the post-process is reusable
  88839. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null a "scene" must be provided
  88840. */
  88841. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  88842. if (samples === void 0) { samples = 100; }
  88843. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  88844. 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;
  88845. _this._screenCoordinates = BABYLON.Vector2.Zero();
  88846. /**
  88847. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  88848. */
  88849. _this.customMeshPosition = BABYLON.Vector3.Zero();
  88850. /**
  88851. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  88852. */
  88853. _this.useCustomMeshPosition = false;
  88854. /**
  88855. * If the post-process should inverse the light scattering direction
  88856. */
  88857. _this.invert = true;
  88858. /**
  88859. * Array containing the excluded meshes not rendered in the internal pass
  88860. */
  88861. _this.excludedMeshes = new Array();
  88862. /**
  88863. * Controls the overall intensity of the post-process
  88864. */
  88865. _this.exposure = 0.3;
  88866. /**
  88867. * Dissipates each sample's contribution in range [0, 1]
  88868. */
  88869. _this.decay = 0.96815;
  88870. /**
  88871. * Controls the overall intensity of each sample
  88872. */
  88873. _this.weight = 0.58767;
  88874. /**
  88875. * Controls the density of each sample
  88876. */
  88877. _this.density = 0.926;
  88878. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  88879. engine = scene.getEngine();
  88880. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  88881. // Configure mesh
  88882. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  88883. // Configure
  88884. _this._createPass(scene, ratio.passRatio || ratio);
  88885. _this.onActivate = function (camera) {
  88886. if (!_this.isSupported) {
  88887. _this.dispose(camera);
  88888. }
  88889. _this.onActivate = null;
  88890. };
  88891. _this.onApplyObservable.add(function (effect) {
  88892. _this._updateMeshScreenCoordinates(scene);
  88893. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  88894. effect.setFloat("exposure", _this.exposure);
  88895. effect.setFloat("decay", _this.decay);
  88896. effect.setFloat("weight", _this.weight);
  88897. effect.setFloat("density", _this.density);
  88898. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  88899. });
  88900. return _this;
  88901. }
  88902. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  88903. /**
  88904. * @hidden
  88905. * VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead
  88906. */
  88907. get: function () {
  88908. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  88909. return false;
  88910. },
  88911. set: function (useDiffuseColor) {
  88912. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  88913. },
  88914. enumerable: true,
  88915. configurable: true
  88916. });
  88917. /**
  88918. * Returns the string "VolumetricLightScatteringPostProcess"
  88919. * @returns "VolumetricLightScatteringPostProcess"
  88920. */
  88921. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  88922. return "VolumetricLightScatteringPostProcess";
  88923. };
  88924. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  88925. var mesh = subMesh.getMesh();
  88926. // Render this.mesh as default
  88927. if (mesh === this.mesh && mesh.material) {
  88928. return mesh.material.isReady(mesh);
  88929. }
  88930. var defines = [];
  88931. var attribs = [BABYLON.VertexBuffer.PositionKind];
  88932. var material = subMesh.getMaterial();
  88933. // Alpha test
  88934. if (material) {
  88935. if (material.needAlphaTesting()) {
  88936. defines.push("#define ALPHATEST");
  88937. }
  88938. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  88939. attribs.push(BABYLON.VertexBuffer.UVKind);
  88940. defines.push("#define UV1");
  88941. }
  88942. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  88943. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  88944. defines.push("#define UV2");
  88945. }
  88946. }
  88947. // Bones
  88948. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  88949. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  88950. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  88951. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  88952. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  88953. }
  88954. else {
  88955. defines.push("#define NUM_BONE_INFLUENCERS 0");
  88956. }
  88957. // Instances
  88958. if (useInstances) {
  88959. defines.push("#define INSTANCES");
  88960. attribs.push("world0");
  88961. attribs.push("world1");
  88962. attribs.push("world2");
  88963. attribs.push("world3");
  88964. }
  88965. // Get correct effect
  88966. var join = defines.join("\n");
  88967. if (this._cachedDefines !== join) {
  88968. this._cachedDefines = join;
  88969. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  88970. }
  88971. return this._volumetricLightScatteringPass.isReady();
  88972. };
  88973. /**
  88974. * Sets the new light position for light scattering effect
  88975. * @param position The new custom light position
  88976. */
  88977. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  88978. this.customMeshPosition = position;
  88979. };
  88980. /**
  88981. * Returns the light position for light scattering effect
  88982. * @return {BABYLON.Vector3} The custom light position
  88983. */
  88984. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  88985. return this.customMeshPosition;
  88986. };
  88987. /**
  88988. * Disposes the internal assets and detaches the post-process from the camera
  88989. */
  88990. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  88991. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  88992. if (rttIndex !== -1) {
  88993. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  88994. }
  88995. this._volumetricLightScatteringRTT.dispose();
  88996. _super.prototype.dispose.call(this, camera);
  88997. };
  88998. /**
  88999. * Returns the render target texture used by the post-process
  89000. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  89001. */
  89002. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  89003. return this._volumetricLightScatteringRTT;
  89004. };
  89005. // Private methods
  89006. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  89007. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  89008. return true;
  89009. }
  89010. return false;
  89011. };
  89012. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  89013. var _this = this;
  89014. var engine = scene.getEngine();
  89015. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  89016. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89017. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89018. this._volumetricLightScatteringRTT.renderList = null;
  89019. this._volumetricLightScatteringRTT.renderParticles = false;
  89020. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  89021. var camera = this.getCamera();
  89022. if (camera) {
  89023. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  89024. }
  89025. else {
  89026. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  89027. }
  89028. // Custom render function for submeshes
  89029. var renderSubMesh = function (subMesh) {
  89030. var mesh = subMesh.getRenderingMesh();
  89031. if (_this._meshExcluded(mesh)) {
  89032. return;
  89033. }
  89034. var material = subMesh.getMaterial();
  89035. if (!material) {
  89036. return;
  89037. }
  89038. var scene = mesh.getScene();
  89039. var engine = scene.getEngine();
  89040. // Culling
  89041. engine.setState(material.backFaceCulling);
  89042. // Managing instances
  89043. var batch = mesh._getInstancesRenderList(subMesh._id);
  89044. if (batch.mustReturn) {
  89045. return;
  89046. }
  89047. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  89048. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  89049. var effect = _this._volumetricLightScatteringPass;
  89050. if (mesh === _this.mesh) {
  89051. if (subMesh.effect) {
  89052. effect = subMesh.effect;
  89053. }
  89054. else {
  89055. effect = material.getEffect();
  89056. }
  89057. }
  89058. engine.enableEffect(effect);
  89059. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  89060. if (mesh === _this.mesh) {
  89061. material.bind(mesh.getWorldMatrix(), mesh);
  89062. }
  89063. else {
  89064. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  89065. // Alpha test
  89066. if (material && material.needAlphaTesting()) {
  89067. var alphaTexture = material.getAlphaTestTexture();
  89068. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  89069. if (alphaTexture) {
  89070. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  89071. }
  89072. }
  89073. // Bones
  89074. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  89075. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  89076. }
  89077. }
  89078. // Draw
  89079. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  89080. }
  89081. };
  89082. // Render target texture callbacks
  89083. var savedSceneClearColor;
  89084. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  89085. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  89086. savedSceneClearColor = scene.clearColor;
  89087. scene.clearColor = sceneClearColor;
  89088. });
  89089. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  89090. scene.clearColor = savedSceneClearColor;
  89091. });
  89092. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  89093. var engine = scene.getEngine();
  89094. var index;
  89095. if (depthOnlySubMeshes.length) {
  89096. engine.setColorWrite(false);
  89097. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  89098. renderSubMesh(depthOnlySubMeshes.data[index]);
  89099. }
  89100. engine.setColorWrite(true);
  89101. }
  89102. for (index = 0; index < opaqueSubMeshes.length; index++) {
  89103. renderSubMesh(opaqueSubMeshes.data[index]);
  89104. }
  89105. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  89106. renderSubMesh(alphaTestSubMeshes.data[index]);
  89107. }
  89108. if (transparentSubMeshes.length) {
  89109. // Sort sub meshes
  89110. for (index = 0; index < transparentSubMeshes.length; index++) {
  89111. var submesh = transparentSubMeshes.data[index];
  89112. var boundingInfo = submesh.getBoundingInfo();
  89113. if (boundingInfo && scene.activeCamera) {
  89114. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  89115. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  89116. }
  89117. }
  89118. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  89119. sortedArray.sort(function (a, b) {
  89120. // Alpha index first
  89121. if (a._alphaIndex > b._alphaIndex) {
  89122. return 1;
  89123. }
  89124. if (a._alphaIndex < b._alphaIndex) {
  89125. return -1;
  89126. }
  89127. // Then distance to camera
  89128. if (a._distanceToCamera < b._distanceToCamera) {
  89129. return 1;
  89130. }
  89131. if (a._distanceToCamera > b._distanceToCamera) {
  89132. return -1;
  89133. }
  89134. return 0;
  89135. });
  89136. // Render sub meshes
  89137. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  89138. for (index = 0; index < sortedArray.length; index++) {
  89139. renderSubMesh(sortedArray[index]);
  89140. }
  89141. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  89142. }
  89143. };
  89144. };
  89145. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  89146. var transform = scene.getTransformMatrix();
  89147. var meshPosition;
  89148. if (this.useCustomMeshPosition) {
  89149. meshPosition = this.customMeshPosition;
  89150. }
  89151. else if (this.attachedNode) {
  89152. meshPosition = this.attachedNode.position;
  89153. }
  89154. else {
  89155. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  89156. }
  89157. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  89158. this._screenCoordinates.x = pos.x / this._viewPort.width;
  89159. this._screenCoordinates.y = pos.y / this._viewPort.height;
  89160. if (this.invert)
  89161. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  89162. };
  89163. // Static methods
  89164. /**
  89165. * Creates a default mesh for the Volumeric Light Scattering post-process
  89166. * @param name The mesh name
  89167. * @param scene The scene where to create the mesh
  89168. * @return {BABYLON.Mesh} the default mesh
  89169. */
  89170. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  89171. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  89172. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  89173. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  89174. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  89175. mesh.material = material;
  89176. return mesh;
  89177. };
  89178. __decorate([
  89179. BABYLON.serializeAsVector3()
  89180. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  89181. __decorate([
  89182. BABYLON.serialize()
  89183. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  89184. __decorate([
  89185. BABYLON.serialize()
  89186. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  89187. __decorate([
  89188. BABYLON.serializeAsMeshReference()
  89189. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  89190. __decorate([
  89191. BABYLON.serialize()
  89192. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  89193. __decorate([
  89194. BABYLON.serialize()
  89195. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  89196. __decorate([
  89197. BABYLON.serialize()
  89198. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  89199. __decorate([
  89200. BABYLON.serialize()
  89201. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  89202. __decorate([
  89203. BABYLON.serialize()
  89204. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  89205. return VolumetricLightScatteringPostProcess;
  89206. }(BABYLON.PostProcess));
  89207. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  89208. })(BABYLON || (BABYLON = {}));
  89209. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  89210. var BABYLON;
  89211. (function (BABYLON) {
  89212. /**
  89213. *
  89214. * This post-process allows the modification of rendered colors by using
  89215. * a 'look-up table' (LUT). This effect is also called Color Grading.
  89216. *
  89217. * The object needs to be provided an url to a texture containing the color
  89218. * look-up table: the texture must be 256 pixels wide and 16 pixels high.
  89219. * Use an image editing software to tweak the LUT to match your needs.
  89220. *
  89221. * For an example of a color LUT, see here:
  89222. * @see http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  89223. * For explanations on color grading, see here:
  89224. * @see http://udn.epicgames.com/Three/ColorGrading.html
  89225. *
  89226. */
  89227. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  89228. __extends(ColorCorrectionPostProcess, _super);
  89229. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  89230. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  89231. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  89232. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  89233. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89234. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89235. _this.onApply = function (effect) {
  89236. effect.setTexture("colorTable", _this._colorTableTexture);
  89237. };
  89238. return _this;
  89239. }
  89240. return ColorCorrectionPostProcess;
  89241. }(BABYLON.PostProcess));
  89242. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  89243. })(BABYLON || (BABYLON = {}));
  89244. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  89245. var BABYLON;
  89246. (function (BABYLON) {
  89247. /** Defines operator used for tonemapping */
  89248. var TonemappingOperator;
  89249. (function (TonemappingOperator) {
  89250. /** Hable */
  89251. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  89252. /** Reinhard */
  89253. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  89254. /** HejiDawson */
  89255. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  89256. /** Photographic */
  89257. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  89258. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  89259. ;
  89260. /**
  89261. * Defines a post process to apply tone mapping
  89262. */
  89263. var TonemapPostProcess = /** @class */ (function (_super) {
  89264. __extends(TonemapPostProcess, _super);
  89265. /**
  89266. * Creates a new TonemapPostProcess
  89267. * @param name defines the name of the postprocess
  89268. * @param _operator defines the operator to use
  89269. * @param exposureAdjustment defines the required exposure adjustement
  89270. * @param camera defines the camera to use (can be null)
  89271. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  89272. * @param engine defines the hosting engine (can be ignore if camera is set)
  89273. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  89274. */
  89275. function TonemapPostProcess(name, _operator,
  89276. /** Defines the required exposure adjustement */
  89277. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  89278. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  89279. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  89280. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  89281. _this._operator = _operator;
  89282. _this.exposureAdjustment = exposureAdjustment;
  89283. var defines = "#define ";
  89284. if (_this._operator === TonemappingOperator.Hable)
  89285. defines += "HABLE_TONEMAPPING";
  89286. else if (_this._operator === TonemappingOperator.Reinhard)
  89287. defines += "REINHARD_TONEMAPPING";
  89288. else if (_this._operator === TonemappingOperator.HejiDawson)
  89289. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  89290. else if (_this._operator === TonemappingOperator.Photographic)
  89291. defines += "PHOTOGRAPHIC_TONEMAPPING";
  89292. //sadly a second call to create the effect.
  89293. _this.updateEffect(defines);
  89294. _this.onApply = function (effect) {
  89295. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  89296. };
  89297. return _this;
  89298. }
  89299. return TonemapPostProcess;
  89300. }(BABYLON.PostProcess));
  89301. BABYLON.TonemapPostProcess = TonemapPostProcess;
  89302. })(BABYLON || (BABYLON = {}));
  89303. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  89304. var BABYLON;
  89305. (function (BABYLON) {
  89306. /**
  89307. * DisplayPassPostProcess which produces an output the same as it's input
  89308. */
  89309. var DisplayPassPostProcess = /** @class */ (function (_super) {
  89310. __extends(DisplayPassPostProcess, _super);
  89311. /**
  89312. * Creates the DisplayPassPostProcess
  89313. * @param name The name of the effect.
  89314. * @param options The required width/height ratio to downsize to before computing the render pass.
  89315. * @param camera The camera to apply the render pass to.
  89316. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  89317. * @param engine The engine which the post process will be applied. (default: current engine)
  89318. * @param reusable If the post process can be reused on the same frame. (default: false)
  89319. */
  89320. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  89321. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  89322. }
  89323. return DisplayPassPostProcess;
  89324. }(BABYLON.PostProcess));
  89325. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  89326. })(BABYLON || (BABYLON = {}));
  89327. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  89328. var BABYLON;
  89329. (function (BABYLON) {
  89330. /**
  89331. * Extracts highlights from the image
  89332. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  89333. */
  89334. var HighlightsPostProcess = /** @class */ (function (_super) {
  89335. __extends(HighlightsPostProcess, _super);
  89336. /**
  89337. * Extracts highlights from the image
  89338. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  89339. * @param name The name of the effect.
  89340. * @param options The required width/height ratio to downsize to before computing the render pass.
  89341. * @param camera The camera to apply the render pass to.
  89342. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  89343. * @param engine The engine which the post process will be applied. (default: current engine)
  89344. * @param reusable If the post process can be reused on the same frame. (default: false)
  89345. * @param textureType Type of texture for the post process (default: Engine.TEXTURETYPE_UNSIGNED_INT)
  89346. */
  89347. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  89348. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  89349. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  89350. }
  89351. return HighlightsPostProcess;
  89352. }(BABYLON.PostProcess));
  89353. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  89354. })(BABYLON || (BABYLON = {}));
  89355. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  89356. var BABYLON;
  89357. (function (BABYLON) {
  89358. /**
  89359. * ImageProcessingPostProcess
  89360. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#imageprocessing
  89361. */
  89362. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  89363. __extends(ImageProcessingPostProcess, _super);
  89364. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  89365. if (camera === void 0) { camera = null; }
  89366. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  89367. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  89368. _this._fromLinearSpace = true;
  89369. /**
  89370. * Defines cache preventing GC.
  89371. */
  89372. _this._defines = {
  89373. IMAGEPROCESSING: false,
  89374. VIGNETTE: false,
  89375. VIGNETTEBLENDMODEMULTIPLY: false,
  89376. VIGNETTEBLENDMODEOPAQUE: false,
  89377. TONEMAPPING: false,
  89378. TONEMAPPING_ACES: false,
  89379. CONTRAST: false,
  89380. COLORCURVES: false,
  89381. COLORGRADING: false,
  89382. COLORGRADING3D: false,
  89383. FROMLINEARSPACE: false,
  89384. SAMPLER3DGREENDEPTH: false,
  89385. SAMPLER3DBGRMAP: false,
  89386. IMAGEPROCESSINGPOSTPROCESS: false,
  89387. EXPOSURE: false,
  89388. };
  89389. // Setup the configuration as forced by the constructor. This would then not force the
  89390. // scene materials output in linear space and let untouched the default forward pass.
  89391. if (imageProcessingConfiguration) {
  89392. imageProcessingConfiguration.applyByPostProcess = true;
  89393. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  89394. // This will cause the shader to be compiled
  89395. _this.fromLinearSpace = false;
  89396. }
  89397. // Setup the default processing configuration to the scene.
  89398. else {
  89399. _this._attachImageProcessingConfiguration(null, true);
  89400. _this.imageProcessingConfiguration.applyByPostProcess = true;
  89401. }
  89402. _this.onApply = function (effect) {
  89403. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  89404. };
  89405. return _this;
  89406. }
  89407. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  89408. /**
  89409. * Gets the image processing configuration used either in this material.
  89410. */
  89411. get: function () {
  89412. return this._imageProcessingConfiguration;
  89413. },
  89414. /**
  89415. * Sets the Default image processing configuration used either in the this material.
  89416. *
  89417. * If sets to null, the scene one is in use.
  89418. */
  89419. set: function (value) {
  89420. this._attachImageProcessingConfiguration(value);
  89421. },
  89422. enumerable: true,
  89423. configurable: true
  89424. });
  89425. /**
  89426. * Attaches a new image processing configuration to the PBR Material.
  89427. * @param configuration
  89428. */
  89429. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  89430. var _this = this;
  89431. if (doNotBuild === void 0) { doNotBuild = false; }
  89432. if (configuration === this._imageProcessingConfiguration) {
  89433. return;
  89434. }
  89435. // Detaches observer.
  89436. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  89437. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  89438. }
  89439. // Pick the scene configuration if needed.
  89440. if (!configuration) {
  89441. var scene = null;
  89442. var engine = this.getEngine();
  89443. var camera = this.getCamera();
  89444. if (camera) {
  89445. scene = camera.getScene();
  89446. }
  89447. else if (engine && engine.scenes) {
  89448. var scenes = engine.scenes;
  89449. scene = scenes[scenes.length - 1];
  89450. }
  89451. else {
  89452. scene = BABYLON.Engine.LastCreatedScene;
  89453. }
  89454. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  89455. }
  89456. else {
  89457. this._imageProcessingConfiguration = configuration;
  89458. }
  89459. // Attaches observer.
  89460. if (this._imageProcessingConfiguration) {
  89461. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  89462. _this._updateParameters();
  89463. });
  89464. }
  89465. // Ensure the effect will be rebuilt.
  89466. if (!doNotBuild) {
  89467. this._updateParameters();
  89468. }
  89469. };
  89470. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  89471. /**
  89472. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  89473. */
  89474. get: function () {
  89475. return this.imageProcessingConfiguration.colorCurves;
  89476. },
  89477. /**
  89478. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  89479. */
  89480. set: function (value) {
  89481. this.imageProcessingConfiguration.colorCurves = value;
  89482. },
  89483. enumerable: true,
  89484. configurable: true
  89485. });
  89486. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  89487. /**
  89488. * Gets wether the color curves effect is enabled.
  89489. */
  89490. get: function () {
  89491. return this.imageProcessingConfiguration.colorCurvesEnabled;
  89492. },
  89493. /**
  89494. * Sets wether the color curves effect is enabled.
  89495. */
  89496. set: function (value) {
  89497. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  89498. },
  89499. enumerable: true,
  89500. configurable: true
  89501. });
  89502. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  89503. /**
  89504. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  89505. */
  89506. get: function () {
  89507. return this.imageProcessingConfiguration.colorGradingTexture;
  89508. },
  89509. /**
  89510. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  89511. */
  89512. set: function (value) {
  89513. this.imageProcessingConfiguration.colorGradingTexture = value;
  89514. },
  89515. enumerable: true,
  89516. configurable: true
  89517. });
  89518. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  89519. /**
  89520. * Gets wether the color grading effect is enabled.
  89521. */
  89522. get: function () {
  89523. return this.imageProcessingConfiguration.colorGradingEnabled;
  89524. },
  89525. /**
  89526. * Gets wether the color grading effect is enabled.
  89527. */
  89528. set: function (value) {
  89529. this.imageProcessingConfiguration.colorGradingEnabled = value;
  89530. },
  89531. enumerable: true,
  89532. configurable: true
  89533. });
  89534. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  89535. /**
  89536. * Gets exposure used in the effect.
  89537. */
  89538. get: function () {
  89539. return this.imageProcessingConfiguration.exposure;
  89540. },
  89541. /**
  89542. * Sets exposure used in the effect.
  89543. */
  89544. set: function (value) {
  89545. this.imageProcessingConfiguration.exposure = value;
  89546. },
  89547. enumerable: true,
  89548. configurable: true
  89549. });
  89550. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  89551. /**
  89552. * Gets wether tonemapping is enabled or not.
  89553. */
  89554. get: function () {
  89555. return this._imageProcessingConfiguration.toneMappingEnabled;
  89556. },
  89557. /**
  89558. * Sets wether tonemapping is enabled or not
  89559. */
  89560. set: function (value) {
  89561. this._imageProcessingConfiguration.toneMappingEnabled = value;
  89562. },
  89563. enumerable: true,
  89564. configurable: true
  89565. });
  89566. ;
  89567. ;
  89568. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  89569. /**
  89570. * Gets contrast used in the effect.
  89571. */
  89572. get: function () {
  89573. return this.imageProcessingConfiguration.contrast;
  89574. },
  89575. /**
  89576. * Sets contrast used in the effect.
  89577. */
  89578. set: function (value) {
  89579. this.imageProcessingConfiguration.contrast = value;
  89580. },
  89581. enumerable: true,
  89582. configurable: true
  89583. });
  89584. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  89585. /**
  89586. * Gets Vignette stretch size.
  89587. */
  89588. get: function () {
  89589. return this.imageProcessingConfiguration.vignetteStretch;
  89590. },
  89591. /**
  89592. * Sets Vignette stretch size.
  89593. */
  89594. set: function (value) {
  89595. this.imageProcessingConfiguration.vignetteStretch = value;
  89596. },
  89597. enumerable: true,
  89598. configurable: true
  89599. });
  89600. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  89601. /**
  89602. * Gets Vignette centre X Offset.
  89603. */
  89604. get: function () {
  89605. return this.imageProcessingConfiguration.vignetteCentreX;
  89606. },
  89607. /**
  89608. * Sets Vignette centre X Offset.
  89609. */
  89610. set: function (value) {
  89611. this.imageProcessingConfiguration.vignetteCentreX = value;
  89612. },
  89613. enumerable: true,
  89614. configurable: true
  89615. });
  89616. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  89617. /**
  89618. * Gets Vignette centre Y Offset.
  89619. */
  89620. get: function () {
  89621. return this.imageProcessingConfiguration.vignetteCentreY;
  89622. },
  89623. /**
  89624. * Sets Vignette centre Y Offset.
  89625. */
  89626. set: function (value) {
  89627. this.imageProcessingConfiguration.vignetteCentreY = value;
  89628. },
  89629. enumerable: true,
  89630. configurable: true
  89631. });
  89632. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  89633. /**
  89634. * Gets Vignette weight or intensity of the vignette effect.
  89635. */
  89636. get: function () {
  89637. return this.imageProcessingConfiguration.vignetteWeight;
  89638. },
  89639. /**
  89640. * Sets Vignette weight or intensity of the vignette effect.
  89641. */
  89642. set: function (value) {
  89643. this.imageProcessingConfiguration.vignetteWeight = value;
  89644. },
  89645. enumerable: true,
  89646. configurable: true
  89647. });
  89648. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  89649. /**
  89650. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  89651. * if vignetteEnabled is set to true.
  89652. */
  89653. get: function () {
  89654. return this.imageProcessingConfiguration.vignetteColor;
  89655. },
  89656. /**
  89657. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  89658. * if vignetteEnabled is set to true.
  89659. */
  89660. set: function (value) {
  89661. this.imageProcessingConfiguration.vignetteColor = value;
  89662. },
  89663. enumerable: true,
  89664. configurable: true
  89665. });
  89666. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  89667. /**
  89668. * Gets Camera field of view used by the Vignette effect.
  89669. */
  89670. get: function () {
  89671. return this.imageProcessingConfiguration.vignetteCameraFov;
  89672. },
  89673. /**
  89674. * Sets Camera field of view used by the Vignette effect.
  89675. */
  89676. set: function (value) {
  89677. this.imageProcessingConfiguration.vignetteCameraFov = value;
  89678. },
  89679. enumerable: true,
  89680. configurable: true
  89681. });
  89682. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  89683. /**
  89684. * Gets the vignette blend mode allowing different kind of effect.
  89685. */
  89686. get: function () {
  89687. return this.imageProcessingConfiguration.vignetteBlendMode;
  89688. },
  89689. /**
  89690. * Sets the vignette blend mode allowing different kind of effect.
  89691. */
  89692. set: function (value) {
  89693. this.imageProcessingConfiguration.vignetteBlendMode = value;
  89694. },
  89695. enumerable: true,
  89696. configurable: true
  89697. });
  89698. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  89699. /**
  89700. * Gets wether the vignette effect is enabled.
  89701. */
  89702. get: function () {
  89703. return this.imageProcessingConfiguration.vignetteEnabled;
  89704. },
  89705. /**
  89706. * Sets wether the vignette effect is enabled.
  89707. */
  89708. set: function (value) {
  89709. this.imageProcessingConfiguration.vignetteEnabled = value;
  89710. },
  89711. enumerable: true,
  89712. configurable: true
  89713. });
  89714. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  89715. /**
  89716. * Gets wether the input of the processing is in Gamma or Linear Space.
  89717. */
  89718. get: function () {
  89719. return this._fromLinearSpace;
  89720. },
  89721. /**
  89722. * Sets wether the input of the processing is in Gamma or Linear Space.
  89723. */
  89724. set: function (value) {
  89725. if (this._fromLinearSpace === value) {
  89726. return;
  89727. }
  89728. this._fromLinearSpace = value;
  89729. this._updateParameters();
  89730. },
  89731. enumerable: true,
  89732. configurable: true
  89733. });
  89734. /**
  89735. * "ImageProcessingPostProcess"
  89736. * @returns "ImageProcessingPostProcess"
  89737. */
  89738. ImageProcessingPostProcess.prototype.getClassName = function () {
  89739. return "ImageProcessingPostProcess";
  89740. };
  89741. ImageProcessingPostProcess.prototype._updateParameters = function () {
  89742. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  89743. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  89744. var defines = "";
  89745. for (var define in this._defines) {
  89746. if (this._defines[define]) {
  89747. defines += "#define " + define + ";\r\n";
  89748. }
  89749. }
  89750. var samplers = ["textureSampler"];
  89751. var uniforms = ["scale"];
  89752. if (BABYLON.ImageProcessingConfiguration) {
  89753. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  89754. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  89755. }
  89756. this.updateEffect(defines, uniforms, samplers);
  89757. };
  89758. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  89759. _super.prototype.dispose.call(this, camera);
  89760. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  89761. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  89762. }
  89763. if (this._imageProcessingConfiguration) {
  89764. this.imageProcessingConfiguration.applyByPostProcess = false;
  89765. }
  89766. };
  89767. __decorate([
  89768. BABYLON.serialize()
  89769. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  89770. return ImageProcessingPostProcess;
  89771. }(BABYLON.PostProcess));
  89772. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  89773. })(BABYLON || (BABYLON = {}));
  89774. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  89775. var BABYLON;
  89776. (function (BABYLON) {
  89777. /**
  89778. * Class used to store bone information
  89779. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  89780. */
  89781. var Bone = /** @class */ (function (_super) {
  89782. __extends(Bone, _super);
  89783. /**
  89784. * Create a new bone
  89785. * @param name defines the bone name
  89786. * @param skeleton defines the parent skeleton
  89787. * @param parentBone defines the parent (can be null if the bone is the root)
  89788. * @param localMatrix defines the local matrix
  89789. * @param restPose defines the rest pose matrix
  89790. * @param baseMatrix defines the base matrix
  89791. * @param index defines index of the bone in the hiearchy
  89792. */
  89793. function Bone(
  89794. /**
  89795. * defines the bone name
  89796. */
  89797. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  89798. if (parentBone === void 0) { parentBone = null; }
  89799. if (localMatrix === void 0) { localMatrix = null; }
  89800. if (restPose === void 0) { restPose = null; }
  89801. if (baseMatrix === void 0) { baseMatrix = null; }
  89802. if (index === void 0) { index = null; }
  89803. var _this = _super.call(this, name, skeleton.getScene()) || this;
  89804. _this.name = name;
  89805. /**
  89806. * Gets the list of child bones
  89807. */
  89808. _this.children = new Array();
  89809. /** Gets the animations associated with this bone */
  89810. _this.animations = new Array();
  89811. /**
  89812. * @hidden Internal only
  89813. * Set this value to map this bone to a different index in the transform matrices
  89814. * Set this value to -1 to exclude the bone from the transform matrices
  89815. */
  89816. _this._index = null;
  89817. _this._absoluteTransform = new BABYLON.Matrix();
  89818. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  89819. _this._scalingDeterminant = 1;
  89820. _this._worldTransform = new BABYLON.Matrix();
  89821. _this._needToDecompose = true;
  89822. _this._needToCompose = false;
  89823. _this._skeleton = skeleton;
  89824. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  89825. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  89826. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  89827. _this._index = index;
  89828. skeleton.bones.push(_this);
  89829. _this.setParent(parentBone, false);
  89830. if (baseMatrix || localMatrix) {
  89831. _this._updateDifferenceMatrix();
  89832. }
  89833. return _this;
  89834. }
  89835. Object.defineProperty(Bone.prototype, "_matrix", {
  89836. /** @hidden */
  89837. get: function () {
  89838. this._compose();
  89839. return this._localMatrix;
  89840. },
  89841. /** @hidden */
  89842. set: function (value) {
  89843. this._localMatrix.copyFrom(value);
  89844. this._needToDecompose = true;
  89845. },
  89846. enumerable: true,
  89847. configurable: true
  89848. });
  89849. // Members
  89850. /**
  89851. * Gets the parent skeleton
  89852. * @returns a skeleton
  89853. */
  89854. Bone.prototype.getSkeleton = function () {
  89855. return this._skeleton;
  89856. };
  89857. /**
  89858. * Gets parent bone
  89859. * @returns a bone or null if the bone is the root of the bone hierarchy
  89860. */
  89861. Bone.prototype.getParent = function () {
  89862. return this._parent;
  89863. };
  89864. /**
  89865. * Sets the parent bone
  89866. * @param parent defines the parent (can be null if the bone is the root)
  89867. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  89868. */
  89869. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  89870. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  89871. if (this._parent === parent) {
  89872. return;
  89873. }
  89874. if (this._parent) {
  89875. var index = this._parent.children.indexOf(this);
  89876. if (index !== -1) {
  89877. this._parent.children.splice(index, 1);
  89878. }
  89879. }
  89880. this._parent = parent;
  89881. if (this._parent) {
  89882. this._parent.children.push(this);
  89883. }
  89884. if (updateDifferenceMatrix) {
  89885. this._updateDifferenceMatrix();
  89886. }
  89887. this.markAsDirty();
  89888. };
  89889. /**
  89890. * Gets the local matrix
  89891. * @returns a matrix
  89892. */
  89893. Bone.prototype.getLocalMatrix = function () {
  89894. this._compose();
  89895. return this._localMatrix;
  89896. };
  89897. /**
  89898. * Gets the base matrix (initial matrix which remains unchanged)
  89899. * @returns a matrix
  89900. */
  89901. Bone.prototype.getBaseMatrix = function () {
  89902. return this._baseMatrix;
  89903. };
  89904. /**
  89905. * Gets the rest pose matrix
  89906. * @returns a matrix
  89907. */
  89908. Bone.prototype.getRestPose = function () {
  89909. return this._restPose;
  89910. };
  89911. /**
  89912. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  89913. */
  89914. Bone.prototype.getWorldMatrix = function () {
  89915. return this._worldTransform;
  89916. };
  89917. /**
  89918. * Sets the local matrix to rest pose matrix
  89919. */
  89920. Bone.prototype.returnToRest = function () {
  89921. this.updateMatrix(this._restPose.clone());
  89922. };
  89923. /**
  89924. * Gets the inverse of the absolute transform matrix.
  89925. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  89926. * @returns a matrix
  89927. */
  89928. Bone.prototype.getInvertedAbsoluteTransform = function () {
  89929. return this._invertedAbsoluteTransform;
  89930. };
  89931. /**
  89932. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  89933. * @returns a matrix
  89934. */
  89935. Bone.prototype.getAbsoluteTransform = function () {
  89936. return this._absoluteTransform;
  89937. };
  89938. Object.defineProperty(Bone.prototype, "position", {
  89939. // Properties (matches AbstractMesh properties)
  89940. /** Gets or sets current position (in local space) */
  89941. get: function () {
  89942. this._decompose();
  89943. return this._localPosition;
  89944. },
  89945. set: function (newPosition) {
  89946. this._decompose();
  89947. this._localPosition.copyFrom(newPosition);
  89948. this._markAsDirtyAndCompose();
  89949. },
  89950. enumerable: true,
  89951. configurable: true
  89952. });
  89953. Object.defineProperty(Bone.prototype, "rotation", {
  89954. /** Gets or sets current rotation (in local space) */
  89955. get: function () {
  89956. return this.getRotation();
  89957. },
  89958. set: function (newRotation) {
  89959. this.setRotation(newRotation);
  89960. },
  89961. enumerable: true,
  89962. configurable: true
  89963. });
  89964. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  89965. /** Gets or sets current rotation quaternion (in local space) */
  89966. get: function () {
  89967. this._decompose();
  89968. return this._localRotation;
  89969. },
  89970. set: function (newRotation) {
  89971. this.setRotationQuaternion(newRotation);
  89972. },
  89973. enumerable: true,
  89974. configurable: true
  89975. });
  89976. Object.defineProperty(Bone.prototype, "scaling", {
  89977. /** Gets or sets current scaling (in local space) */
  89978. get: function () {
  89979. return this.getScale();
  89980. },
  89981. set: function (newScaling) {
  89982. this.setScale(newScaling);
  89983. },
  89984. enumerable: true,
  89985. configurable: true
  89986. });
  89987. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  89988. /**
  89989. * Gets the animation properties override
  89990. */
  89991. get: function () {
  89992. return this._skeleton.animationPropertiesOverride;
  89993. },
  89994. enumerable: true,
  89995. configurable: true
  89996. });
  89997. // Methods
  89998. Bone.prototype._decompose = function () {
  89999. if (!this._needToDecompose) {
  90000. return;
  90001. }
  90002. this._needToDecompose = false;
  90003. if (!this._localScaling) {
  90004. this._localScaling = BABYLON.Vector3.Zero();
  90005. this._localRotation = BABYLON.Quaternion.Zero();
  90006. this._localPosition = BABYLON.Vector3.Zero();
  90007. }
  90008. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  90009. };
  90010. Bone.prototype._compose = function () {
  90011. if (!this._needToCompose) {
  90012. return;
  90013. }
  90014. this._needToCompose = false;
  90015. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  90016. };
  90017. /**
  90018. * Update the base and local matrices
  90019. * @param matrix defines the new base or local matrix
  90020. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  90021. * @param updateLocalMatrix defines if the local matrix should be updated
  90022. */
  90023. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  90024. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  90025. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  90026. this._baseMatrix.copyFrom(matrix);
  90027. if (updateDifferenceMatrix) {
  90028. this._updateDifferenceMatrix();
  90029. }
  90030. if (updateLocalMatrix) {
  90031. this._localMatrix.copyFrom(matrix);
  90032. this._markAsDirtyAndDecompose();
  90033. }
  90034. else {
  90035. this.markAsDirty();
  90036. }
  90037. };
  90038. /** @hidden */
  90039. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  90040. if (updateChildren === void 0) { updateChildren = true; }
  90041. if (!rootMatrix) {
  90042. rootMatrix = this._baseMatrix;
  90043. }
  90044. if (this._parent) {
  90045. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  90046. }
  90047. else {
  90048. this._absoluteTransform.copyFrom(rootMatrix);
  90049. }
  90050. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  90051. if (updateChildren) {
  90052. for (var index = 0; index < this.children.length; index++) {
  90053. this.children[index]._updateDifferenceMatrix();
  90054. }
  90055. }
  90056. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  90057. };
  90058. /**
  90059. * Flag the bone as dirty (Forcing it to update everything)
  90060. */
  90061. Bone.prototype.markAsDirty = function () {
  90062. this._currentRenderId++;
  90063. this._childRenderId++;
  90064. this._skeleton._markAsDirty();
  90065. };
  90066. Bone.prototype._markAsDirtyAndCompose = function () {
  90067. this.markAsDirty();
  90068. this._needToCompose = true;
  90069. };
  90070. Bone.prototype._markAsDirtyAndDecompose = function () {
  90071. this.markAsDirty();
  90072. this._needToDecompose = true;
  90073. };
  90074. /**
  90075. * Copy an animation range from another bone
  90076. * @param source defines the source bone
  90077. * @param rangeName defines the range name to copy
  90078. * @param frameOffset defines the frame offset
  90079. * @param rescaleAsRequired defines if rescaling must be applied if required
  90080. * @param skelDimensionsRatio defines the scaling ratio
  90081. * @returns true if operation was successful
  90082. */
  90083. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  90084. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  90085. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  90086. // all animation may be coming from a library skeleton, so may need to create animation
  90087. if (this.animations.length === 0) {
  90088. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  90089. this.animations[0].setKeys([]);
  90090. }
  90091. // get animation info / verify there is such a range from the source bone
  90092. var sourceRange = source.animations[0].getRange(rangeName);
  90093. if (!sourceRange) {
  90094. return false;
  90095. }
  90096. var from = sourceRange.from;
  90097. var to = sourceRange.to;
  90098. var sourceKeys = source.animations[0].getKeys();
  90099. // rescaling prep
  90100. var sourceBoneLength = source.length;
  90101. var sourceParent = source.getParent();
  90102. var parent = this.getParent();
  90103. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  90104. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  90105. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  90106. var destKeys = this.animations[0].getKeys();
  90107. // loop vars declaration
  90108. var orig;
  90109. var origTranslation;
  90110. var mat;
  90111. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  90112. orig = sourceKeys[key];
  90113. if (orig.frame >= from && orig.frame <= to) {
  90114. if (rescaleAsRequired) {
  90115. mat = orig.value.clone();
  90116. // scale based on parent ratio, when bone has parent
  90117. if (parentScalingReqd) {
  90118. origTranslation = mat.getTranslation();
  90119. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  90120. // scale based on skeleton dimension ratio when root bone, and value is passed
  90121. }
  90122. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  90123. origTranslation = mat.getTranslation();
  90124. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  90125. // use original when root bone, and no data for skelDimensionsRatio
  90126. }
  90127. else {
  90128. mat = orig.value;
  90129. }
  90130. }
  90131. else {
  90132. mat = orig.value;
  90133. }
  90134. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  90135. }
  90136. }
  90137. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  90138. return true;
  90139. };
  90140. /**
  90141. * Translate the bone in local or world space
  90142. * @param vec The amount to translate the bone
  90143. * @param space The space that the translation is in
  90144. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90145. */
  90146. Bone.prototype.translate = function (vec, space, mesh) {
  90147. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90148. var lm = this.getLocalMatrix();
  90149. if (space == BABYLON.Space.LOCAL) {
  90150. lm.m[12] += vec.x;
  90151. lm.m[13] += vec.y;
  90152. lm.m[14] += vec.z;
  90153. }
  90154. else {
  90155. var wm = null;
  90156. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  90157. if (mesh) {
  90158. wm = mesh.getWorldMatrix();
  90159. }
  90160. this._skeleton.computeAbsoluteTransforms();
  90161. var tmat = Bone._tmpMats[0];
  90162. var tvec = Bone._tmpVecs[0];
  90163. if (this._parent) {
  90164. if (mesh && wm) {
  90165. tmat.copyFrom(this._parent.getAbsoluteTransform());
  90166. tmat.multiplyToRef(wm, tmat);
  90167. }
  90168. else {
  90169. tmat.copyFrom(this._parent.getAbsoluteTransform());
  90170. }
  90171. }
  90172. tmat.m[12] = 0;
  90173. tmat.m[13] = 0;
  90174. tmat.m[14] = 0;
  90175. tmat.invert();
  90176. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  90177. lm.m[12] += tvec.x;
  90178. lm.m[13] += tvec.y;
  90179. lm.m[14] += tvec.z;
  90180. }
  90181. this._markAsDirtyAndDecompose();
  90182. };
  90183. /**
  90184. * Set the postion of the bone in local or world space
  90185. * @param position The position to set the bone
  90186. * @param space The space that the position is in
  90187. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90188. */
  90189. Bone.prototype.setPosition = function (position, space, mesh) {
  90190. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90191. var lm = this.getLocalMatrix();
  90192. if (space == BABYLON.Space.LOCAL) {
  90193. lm.m[12] = position.x;
  90194. lm.m[13] = position.y;
  90195. lm.m[14] = position.z;
  90196. }
  90197. else {
  90198. var wm = null;
  90199. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  90200. if (mesh) {
  90201. wm = mesh.getWorldMatrix();
  90202. }
  90203. this._skeleton.computeAbsoluteTransforms();
  90204. var tmat = Bone._tmpMats[0];
  90205. var vec = Bone._tmpVecs[0];
  90206. if (this._parent) {
  90207. if (mesh && wm) {
  90208. tmat.copyFrom(this._parent.getAbsoluteTransform());
  90209. tmat.multiplyToRef(wm, tmat);
  90210. }
  90211. else {
  90212. tmat.copyFrom(this._parent.getAbsoluteTransform());
  90213. }
  90214. }
  90215. tmat.invert();
  90216. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  90217. lm.m[12] = vec.x;
  90218. lm.m[13] = vec.y;
  90219. lm.m[14] = vec.z;
  90220. }
  90221. this._markAsDirtyAndDecompose();
  90222. };
  90223. /**
  90224. * Set the absolute position of the bone (world space)
  90225. * @param position The position to set the bone
  90226. * @param mesh The mesh that this bone is attached to
  90227. */
  90228. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  90229. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  90230. };
  90231. /**
  90232. * Scale the bone on the x, y and z axes (in local space)
  90233. * @param x The amount to scale the bone on the x axis
  90234. * @param y The amount to scale the bone on the y axis
  90235. * @param z The amount to scale the bone on the z axis
  90236. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  90237. */
  90238. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  90239. if (scaleChildren === void 0) { scaleChildren = false; }
  90240. var locMat = this.getLocalMatrix();
  90241. // Apply new scaling on top of current local matrix
  90242. var scaleMat = Bone._tmpMats[0];
  90243. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  90244. scaleMat.multiplyToRef(locMat, locMat);
  90245. // Invert scaling matrix and apply the inverse to all children
  90246. scaleMat.invert();
  90247. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  90248. var child = _a[_i];
  90249. var cm = child.getLocalMatrix();
  90250. cm.multiplyToRef(scaleMat, cm);
  90251. cm.m[12] *= x;
  90252. cm.m[13] *= y;
  90253. cm.m[14] *= z;
  90254. child._markAsDirtyAndDecompose();
  90255. }
  90256. this._markAsDirtyAndDecompose();
  90257. if (scaleChildren) {
  90258. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  90259. var child = _c[_b];
  90260. child.scale(x, y, z, scaleChildren);
  90261. }
  90262. }
  90263. };
  90264. /**
  90265. * Set the bone scaling in local space
  90266. * @param scale defines the scaling vector
  90267. */
  90268. Bone.prototype.setScale = function (scale) {
  90269. this._decompose();
  90270. this._localScaling.copyFrom(scale);
  90271. this._markAsDirtyAndCompose();
  90272. };
  90273. /**
  90274. * Gets the current scaling in local space
  90275. * @returns the current scaling vector
  90276. */
  90277. Bone.prototype.getScale = function () {
  90278. this._decompose();
  90279. return this._localScaling;
  90280. };
  90281. /**
  90282. * Gets the current scaling in local space and stores it in a target vector
  90283. * @param result defines the target vector
  90284. */
  90285. Bone.prototype.getScaleToRef = function (result) {
  90286. this._decompose();
  90287. result.copyFrom(this._localScaling);
  90288. };
  90289. /**
  90290. * Set the yaw, pitch, and roll of the bone in local or world space
  90291. * @param yaw The rotation of the bone on the y axis
  90292. * @param pitch The rotation of the bone on the x axis
  90293. * @param roll The rotation of the bone on the z axis
  90294. * @param space The space that the axes of rotation are in
  90295. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90296. */
  90297. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  90298. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90299. if (space === BABYLON.Space.LOCAL) {
  90300. var quat = Bone._tmpQuat;
  90301. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  90302. this.setRotationQuaternion(quat, space, mesh);
  90303. return;
  90304. }
  90305. var rotMatInv = Bone._tmpMats[0];
  90306. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  90307. return;
  90308. }
  90309. var rotMat = Bone._tmpMats[1];
  90310. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  90311. rotMatInv.multiplyToRef(rotMat, rotMat);
  90312. this._rotateWithMatrix(rotMat, space, mesh);
  90313. };
  90314. /**
  90315. * Add a rotation to the bone on an axis in local or world space
  90316. * @param axis The axis to rotate the bone on
  90317. * @param amount The amount to rotate the bone
  90318. * @param space The space that the axis is in
  90319. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90320. */
  90321. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  90322. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90323. var rmat = Bone._tmpMats[0];
  90324. rmat.m[12] = 0;
  90325. rmat.m[13] = 0;
  90326. rmat.m[14] = 0;
  90327. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  90328. this._rotateWithMatrix(rmat, space, mesh);
  90329. };
  90330. /**
  90331. * Set the rotation of the bone to a particular axis angle in local or world space
  90332. * @param axis The axis to rotate the bone on
  90333. * @param angle The angle that the bone should be rotated to
  90334. * @param space The space that the axis is in
  90335. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90336. */
  90337. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  90338. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90339. if (space === BABYLON.Space.LOCAL) {
  90340. var quat = Bone._tmpQuat;
  90341. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  90342. this.setRotationQuaternion(quat, space, mesh);
  90343. return;
  90344. }
  90345. var rotMatInv = Bone._tmpMats[0];
  90346. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  90347. return;
  90348. }
  90349. var rotMat = Bone._tmpMats[1];
  90350. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  90351. rotMatInv.multiplyToRef(rotMat, rotMat);
  90352. this._rotateWithMatrix(rotMat, space, mesh);
  90353. };
  90354. /**
  90355. * Set the euler rotation of the bone in local of world space
  90356. * @param rotation The euler rotation that the bone should be set to
  90357. * @param space The space that the rotation is in
  90358. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90359. */
  90360. Bone.prototype.setRotation = function (rotation, space, mesh) {
  90361. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90362. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  90363. };
  90364. /**
  90365. * Set the quaternion rotation of the bone in local of world space
  90366. * @param quat The quaternion rotation that the bone should be set to
  90367. * @param space The space that the rotation is in
  90368. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90369. */
  90370. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  90371. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90372. if (space === BABYLON.Space.LOCAL) {
  90373. this._decompose();
  90374. this._localRotation.copyFrom(quat);
  90375. this._markAsDirtyAndCompose();
  90376. return;
  90377. }
  90378. var rotMatInv = Bone._tmpMats[0];
  90379. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  90380. return;
  90381. }
  90382. var rotMat = Bone._tmpMats[1];
  90383. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  90384. rotMatInv.multiplyToRef(rotMat, rotMat);
  90385. this._rotateWithMatrix(rotMat, space, mesh);
  90386. };
  90387. /**
  90388. * Set the rotation matrix of the bone in local of world space
  90389. * @param rotMat The rotation matrix that the bone should be set to
  90390. * @param space The space that the rotation is in
  90391. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90392. */
  90393. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  90394. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90395. if (space === BABYLON.Space.LOCAL) {
  90396. var quat = Bone._tmpQuat;
  90397. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  90398. this.setRotationQuaternion(quat, space, mesh);
  90399. return;
  90400. }
  90401. var rotMatInv = Bone._tmpMats[0];
  90402. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  90403. return;
  90404. }
  90405. var rotMat2 = Bone._tmpMats[1];
  90406. rotMat2.copyFrom(rotMat);
  90407. rotMatInv.multiplyToRef(rotMat, rotMat2);
  90408. this._rotateWithMatrix(rotMat2, space, mesh);
  90409. };
  90410. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  90411. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90412. var lmat = this.getLocalMatrix();
  90413. var lx = lmat.m[12];
  90414. var ly = lmat.m[13];
  90415. var lz = lmat.m[14];
  90416. var parent = this.getParent();
  90417. var parentScale = Bone._tmpMats[3];
  90418. var parentScaleInv = Bone._tmpMats[4];
  90419. if (parent && space == BABYLON.Space.WORLD) {
  90420. if (mesh) {
  90421. parentScale.copyFrom(mesh.getWorldMatrix());
  90422. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  90423. }
  90424. else {
  90425. parentScale.copyFrom(parent.getAbsoluteTransform());
  90426. }
  90427. parentScaleInv.copyFrom(parentScale);
  90428. parentScaleInv.invert();
  90429. lmat.multiplyToRef(parentScale, lmat);
  90430. lmat.multiplyToRef(rmat, lmat);
  90431. lmat.multiplyToRef(parentScaleInv, lmat);
  90432. }
  90433. else {
  90434. if (space == BABYLON.Space.WORLD && mesh) {
  90435. parentScale.copyFrom(mesh.getWorldMatrix());
  90436. parentScaleInv.copyFrom(parentScale);
  90437. parentScaleInv.invert();
  90438. lmat.multiplyToRef(parentScale, lmat);
  90439. lmat.multiplyToRef(rmat, lmat);
  90440. lmat.multiplyToRef(parentScaleInv, lmat);
  90441. }
  90442. else {
  90443. lmat.multiplyToRef(rmat, lmat);
  90444. }
  90445. }
  90446. lmat.m[12] = lx;
  90447. lmat.m[13] = ly;
  90448. lmat.m[14] = lz;
  90449. this.computeAbsoluteTransforms();
  90450. this._markAsDirtyAndDecompose();
  90451. };
  90452. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  90453. var scaleMatrix = Bone._tmpMats[2];
  90454. rotMatInv.copyFrom(this.getAbsoluteTransform());
  90455. if (mesh) {
  90456. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  90457. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  90458. }
  90459. rotMatInv.invert();
  90460. if (isNaN(rotMatInv.m[0])) {
  90461. // Matrix failed to invert.
  90462. // This can happen if scale is zero for example.
  90463. return false;
  90464. }
  90465. scaleMatrix.m[0] *= this._scalingDeterminant;
  90466. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  90467. return true;
  90468. };
  90469. /**
  90470. * Get the position of the bone in local or world space
  90471. * @param space The space that the returned position is in
  90472. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90473. * @returns The position of the bone
  90474. */
  90475. Bone.prototype.getPosition = function (space, mesh) {
  90476. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90477. if (mesh === void 0) { mesh = null; }
  90478. var pos = BABYLON.Vector3.Zero();
  90479. this.getPositionToRef(space, mesh, pos);
  90480. return pos;
  90481. };
  90482. /**
  90483. * Copy the position of the bone to a vector3 in local or world space
  90484. * @param space The space that the returned position is in
  90485. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90486. * @param result The vector3 to copy the position to
  90487. */
  90488. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  90489. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90490. if (space == BABYLON.Space.LOCAL) {
  90491. var lm = this.getLocalMatrix();
  90492. result.x = lm.m[12];
  90493. result.y = lm.m[13];
  90494. result.z = lm.m[14];
  90495. }
  90496. else {
  90497. var wm = null;
  90498. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  90499. if (mesh) {
  90500. wm = mesh.getWorldMatrix();
  90501. }
  90502. this._skeleton.computeAbsoluteTransforms();
  90503. var tmat = Bone._tmpMats[0];
  90504. if (mesh && wm) {
  90505. tmat.copyFrom(this.getAbsoluteTransform());
  90506. tmat.multiplyToRef(wm, tmat);
  90507. }
  90508. else {
  90509. tmat = this.getAbsoluteTransform();
  90510. }
  90511. result.x = tmat.m[12];
  90512. result.y = tmat.m[13];
  90513. result.z = tmat.m[14];
  90514. }
  90515. };
  90516. /**
  90517. * Get the absolute position of the bone (world space)
  90518. * @param mesh The mesh that this bone is attached to
  90519. * @returns The absolute position of the bone
  90520. */
  90521. Bone.prototype.getAbsolutePosition = function (mesh) {
  90522. if (mesh === void 0) { mesh = null; }
  90523. var pos = BABYLON.Vector3.Zero();
  90524. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  90525. return pos;
  90526. };
  90527. /**
  90528. * Copy the absolute position of the bone (world space) to the result param
  90529. * @param mesh The mesh that this bone is attached to
  90530. * @param result The vector3 to copy the absolute position to
  90531. */
  90532. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  90533. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  90534. };
  90535. /**
  90536. * Compute the absolute transforms of this bone and its children
  90537. */
  90538. Bone.prototype.computeAbsoluteTransforms = function () {
  90539. this._compose();
  90540. if (this._parent) {
  90541. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  90542. }
  90543. else {
  90544. this._absoluteTransform.copyFrom(this._localMatrix);
  90545. var poseMatrix = this._skeleton.getPoseMatrix();
  90546. if (poseMatrix) {
  90547. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  90548. }
  90549. }
  90550. var children = this.children;
  90551. var len = children.length;
  90552. for (var i = 0; i < len; i++) {
  90553. children[i].computeAbsoluteTransforms();
  90554. }
  90555. };
  90556. /**
  90557. * Get the world direction from an axis that is in the local space of the bone
  90558. * @param localAxis The local direction that is used to compute the world direction
  90559. * @param mesh The mesh that this bone is attached to
  90560. * @returns The world direction
  90561. */
  90562. Bone.prototype.getDirection = function (localAxis, mesh) {
  90563. if (mesh === void 0) { mesh = null; }
  90564. var result = BABYLON.Vector3.Zero();
  90565. this.getDirectionToRef(localAxis, mesh, result);
  90566. return result;
  90567. };
  90568. /**
  90569. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  90570. * @param localAxis The local direction that is used to compute the world direction
  90571. * @param mesh The mesh that this bone is attached to
  90572. * @param result The vector3 that the world direction will be copied to
  90573. */
  90574. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  90575. if (mesh === void 0) { mesh = null; }
  90576. var wm = null;
  90577. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  90578. if (mesh) {
  90579. wm = mesh.getWorldMatrix();
  90580. }
  90581. this._skeleton.computeAbsoluteTransforms();
  90582. var mat = Bone._tmpMats[0];
  90583. mat.copyFrom(this.getAbsoluteTransform());
  90584. if (mesh && wm) {
  90585. mat.multiplyToRef(wm, mat);
  90586. }
  90587. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  90588. result.normalize();
  90589. };
  90590. /**
  90591. * Get the euler rotation of the bone in local or world space
  90592. * @param space The space that the rotation should be in
  90593. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90594. * @returns The euler rotation
  90595. */
  90596. Bone.prototype.getRotation = function (space, mesh) {
  90597. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90598. if (mesh === void 0) { mesh = null; }
  90599. var result = BABYLON.Vector3.Zero();
  90600. this.getRotationToRef(space, mesh, result);
  90601. return result;
  90602. };
  90603. /**
  90604. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  90605. * @param space The space that the rotation should be in
  90606. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90607. * @param result The vector3 that the rotation should be copied to
  90608. */
  90609. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  90610. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90611. if (mesh === void 0) { mesh = null; }
  90612. var quat = Bone._tmpQuat;
  90613. this.getRotationQuaternionToRef(space, mesh, quat);
  90614. quat.toEulerAnglesToRef(result);
  90615. };
  90616. /**
  90617. * Get the quaternion rotation of the bone in either local or world space
  90618. * @param space The space that the rotation should be in
  90619. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90620. * @returns The quaternion rotation
  90621. */
  90622. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  90623. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90624. if (mesh === void 0) { mesh = null; }
  90625. var result = BABYLON.Quaternion.Identity();
  90626. this.getRotationQuaternionToRef(space, mesh, result);
  90627. return result;
  90628. };
  90629. /**
  90630. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  90631. * @param space The space that the rotation should be in
  90632. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90633. * @param result The quaternion that the rotation should be copied to
  90634. */
  90635. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  90636. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90637. if (mesh === void 0) { mesh = null; }
  90638. if (space == BABYLON.Space.LOCAL) {
  90639. this._decompose();
  90640. result.copyFrom(this._localRotation);
  90641. }
  90642. else {
  90643. var mat = Bone._tmpMats[0];
  90644. var amat = this.getAbsoluteTransform();
  90645. if (mesh) {
  90646. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  90647. }
  90648. else {
  90649. mat.copyFrom(amat);
  90650. }
  90651. mat.m[0] *= this._scalingDeterminant;
  90652. mat.m[1] *= this._scalingDeterminant;
  90653. mat.m[2] *= this._scalingDeterminant;
  90654. mat.decompose(undefined, result, undefined);
  90655. }
  90656. };
  90657. /**
  90658. * Get the rotation matrix of the bone in local or world space
  90659. * @param space The space that the rotation should be in
  90660. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90661. * @returns The rotation matrix
  90662. */
  90663. Bone.prototype.getRotationMatrix = function (space, mesh) {
  90664. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90665. var result = BABYLON.Matrix.Identity();
  90666. this.getRotationMatrixToRef(space, mesh, result);
  90667. return result;
  90668. };
  90669. /**
  90670. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  90671. * @param space The space that the rotation should be in
  90672. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90673. * @param result The quaternion that the rotation should be copied to
  90674. */
  90675. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  90676. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90677. if (space == BABYLON.Space.LOCAL) {
  90678. this.getLocalMatrix().getRotationMatrixToRef(result);
  90679. }
  90680. else {
  90681. var mat = Bone._tmpMats[0];
  90682. var amat = this.getAbsoluteTransform();
  90683. if (mesh) {
  90684. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  90685. }
  90686. else {
  90687. mat.copyFrom(amat);
  90688. }
  90689. mat.m[0] *= this._scalingDeterminant;
  90690. mat.m[1] *= this._scalingDeterminant;
  90691. mat.m[2] *= this._scalingDeterminant;
  90692. mat.getRotationMatrixToRef(result);
  90693. }
  90694. };
  90695. /**
  90696. * Get the world position of a point that is in the local space of the bone
  90697. * @param position The local position
  90698. * @param mesh The mesh that this bone is attached to
  90699. * @returns The world position
  90700. */
  90701. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  90702. if (mesh === void 0) { mesh = null; }
  90703. var result = BABYLON.Vector3.Zero();
  90704. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  90705. return result;
  90706. };
  90707. /**
  90708. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  90709. * @param position The local position
  90710. * @param mesh The mesh that this bone is attached to
  90711. * @param result The vector3 that the world position should be copied to
  90712. */
  90713. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  90714. if (mesh === void 0) { mesh = null; }
  90715. var wm = null;
  90716. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  90717. if (mesh) {
  90718. wm = mesh.getWorldMatrix();
  90719. }
  90720. this._skeleton.computeAbsoluteTransforms();
  90721. var tmat = Bone._tmpMats[0];
  90722. if (mesh && wm) {
  90723. tmat.copyFrom(this.getAbsoluteTransform());
  90724. tmat.multiplyToRef(wm, tmat);
  90725. }
  90726. else {
  90727. tmat = this.getAbsoluteTransform();
  90728. }
  90729. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  90730. };
  90731. /**
  90732. * Get the local position of a point that is in world space
  90733. * @param position The world position
  90734. * @param mesh The mesh that this bone is attached to
  90735. * @returns The local position
  90736. */
  90737. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  90738. if (mesh === void 0) { mesh = null; }
  90739. var result = BABYLON.Vector3.Zero();
  90740. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  90741. return result;
  90742. };
  90743. /**
  90744. * Get the local position of a point that is in world space and copy it to the result param
  90745. * @param position The world position
  90746. * @param mesh The mesh that this bone is attached to
  90747. * @param result The vector3 that the local position should be copied to
  90748. */
  90749. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  90750. if (mesh === void 0) { mesh = null; }
  90751. var wm = null;
  90752. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  90753. if (mesh) {
  90754. wm = mesh.getWorldMatrix();
  90755. }
  90756. this._skeleton.computeAbsoluteTransforms();
  90757. var tmat = Bone._tmpMats[0];
  90758. tmat.copyFrom(this.getAbsoluteTransform());
  90759. if (mesh && wm) {
  90760. tmat.multiplyToRef(wm, tmat);
  90761. }
  90762. tmat.invert();
  90763. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  90764. };
  90765. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  90766. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  90767. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  90768. return Bone;
  90769. }(BABYLON.Node));
  90770. BABYLON.Bone = Bone;
  90771. })(BABYLON || (BABYLON = {}));
  90772. //# sourceMappingURL=babylon.bone.js.map
  90773. var BABYLON;
  90774. (function (BABYLON) {
  90775. /**
  90776. * Class used to apply inverse kinematics to bones
  90777. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  90778. */
  90779. var BoneIKController = /** @class */ (function () {
  90780. /**
  90781. * Creates a new BoneIKController
  90782. * @param mesh defines the mesh to control
  90783. * @param bone defines the bone to control
  90784. * @param options defines options to set up the controller
  90785. */
  90786. function BoneIKController(mesh, bone, options) {
  90787. /**
  90788. * Gets or sets the target position
  90789. */
  90790. this.targetPosition = BABYLON.Vector3.Zero();
  90791. /**
  90792. * Gets or sets the pole target position
  90793. */
  90794. this.poleTargetPosition = BABYLON.Vector3.Zero();
  90795. /**
  90796. * Gets or sets the pole target local offset
  90797. */
  90798. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  90799. /**
  90800. * Gets or sets the pole angle
  90801. */
  90802. this.poleAngle = 0;
  90803. /**
  90804. * 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)
  90805. */
  90806. this.slerpAmount = 1;
  90807. this._bone1Quat = BABYLON.Quaternion.Identity();
  90808. this._bone1Mat = BABYLON.Matrix.Identity();
  90809. this._bone2Ang = Math.PI;
  90810. this._maxAngle = Math.PI;
  90811. this._rightHandedSystem = false;
  90812. this._bendAxis = BABYLON.Vector3.Right();
  90813. this._slerping = false;
  90814. this._adjustRoll = 0;
  90815. this._bone2 = bone;
  90816. this._bone1 = bone.getParent();
  90817. if (!this._bone1) {
  90818. return;
  90819. }
  90820. this.mesh = mesh;
  90821. var bonePos = bone.getPosition();
  90822. if (bone.getAbsoluteTransform().determinant() > 0) {
  90823. this._rightHandedSystem = true;
  90824. this._bendAxis.x = 0;
  90825. this._bendAxis.y = 0;
  90826. this._bendAxis.z = -1;
  90827. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  90828. this._adjustRoll = Math.PI * .5;
  90829. this._bendAxis.z = 1;
  90830. }
  90831. }
  90832. if (this._bone1.length) {
  90833. var boneScale1 = this._bone1.getScale();
  90834. var boneScale2 = this._bone2.getScale();
  90835. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  90836. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  90837. }
  90838. else if (this._bone1.children[0]) {
  90839. mesh.computeWorldMatrix(true);
  90840. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  90841. var pos2 = this._bone2.getAbsolutePosition(mesh);
  90842. var pos3 = this._bone1.getAbsolutePosition(mesh);
  90843. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  90844. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  90845. }
  90846. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  90847. this.maxAngle = Math.PI;
  90848. if (options) {
  90849. if (options.targetMesh) {
  90850. this.targetMesh = options.targetMesh;
  90851. this.targetMesh.computeWorldMatrix(true);
  90852. }
  90853. if (options.poleTargetMesh) {
  90854. this.poleTargetMesh = options.poleTargetMesh;
  90855. this.poleTargetMesh.computeWorldMatrix(true);
  90856. }
  90857. else if (options.poleTargetBone) {
  90858. this.poleTargetBone = options.poleTargetBone;
  90859. }
  90860. else if (this._bone1.getParent()) {
  90861. this.poleTargetBone = this._bone1.getParent();
  90862. }
  90863. if (options.poleTargetLocalOffset) {
  90864. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  90865. }
  90866. if (options.poleAngle) {
  90867. this.poleAngle = options.poleAngle;
  90868. }
  90869. if (options.bendAxis) {
  90870. this._bendAxis.copyFrom(options.bendAxis);
  90871. }
  90872. if (options.maxAngle) {
  90873. this.maxAngle = options.maxAngle;
  90874. }
  90875. if (options.slerpAmount) {
  90876. this.slerpAmount = options.slerpAmount;
  90877. }
  90878. }
  90879. }
  90880. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  90881. /**
  90882. * Gets or sets maximum allowed angle
  90883. */
  90884. get: function () {
  90885. return this._maxAngle;
  90886. },
  90887. set: function (value) {
  90888. this._setMaxAngle(value);
  90889. },
  90890. enumerable: true,
  90891. configurable: true
  90892. });
  90893. BoneIKController.prototype._setMaxAngle = function (ang) {
  90894. if (ang < 0) {
  90895. ang = 0;
  90896. }
  90897. if (ang > Math.PI || ang == undefined) {
  90898. ang = Math.PI;
  90899. }
  90900. this._maxAngle = ang;
  90901. var a = this._bone1Length;
  90902. var b = this._bone2Length;
  90903. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  90904. };
  90905. /**
  90906. * Force the controller to update the bones
  90907. */
  90908. BoneIKController.prototype.update = function () {
  90909. var bone1 = this._bone1;
  90910. if (!bone1) {
  90911. return;
  90912. }
  90913. var target = this.targetPosition;
  90914. var poleTarget = this.poleTargetPosition;
  90915. var mat1 = BoneIKController._tmpMats[0];
  90916. var mat2 = BoneIKController._tmpMats[1];
  90917. if (this.targetMesh) {
  90918. target.copyFrom(this.targetMesh.getAbsolutePosition());
  90919. }
  90920. if (this.poleTargetBone) {
  90921. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  90922. }
  90923. else if (this.poleTargetMesh) {
  90924. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  90925. }
  90926. var bonePos = BoneIKController._tmpVecs[0];
  90927. var zaxis = BoneIKController._tmpVecs[1];
  90928. var xaxis = BoneIKController._tmpVecs[2];
  90929. var yaxis = BoneIKController._tmpVecs[3];
  90930. var upAxis = BoneIKController._tmpVecs[4];
  90931. var _tmpQuat = BoneIKController._tmpQuat;
  90932. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  90933. poleTarget.subtractToRef(bonePos, upAxis);
  90934. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  90935. upAxis.y = 1;
  90936. }
  90937. else {
  90938. upAxis.normalize();
  90939. }
  90940. target.subtractToRef(bonePos, yaxis);
  90941. yaxis.normalize();
  90942. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  90943. zaxis.normalize();
  90944. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  90945. xaxis.normalize();
  90946. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  90947. var a = this._bone1Length;
  90948. var b = this._bone2Length;
  90949. var c = BABYLON.Vector3.Distance(bonePos, target);
  90950. if (this._maxReach > 0) {
  90951. c = Math.min(this._maxReach, c);
  90952. }
  90953. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  90954. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  90955. if (acosa > 1) {
  90956. acosa = 1;
  90957. }
  90958. if (acosb > 1) {
  90959. acosb = 1;
  90960. }
  90961. if (acosa < -1) {
  90962. acosa = -1;
  90963. }
  90964. if (acosb < -1) {
  90965. acosb = -1;
  90966. }
  90967. var angA = Math.acos(acosa);
  90968. var angB = Math.acos(acosb);
  90969. var angC = -angA - angB;
  90970. if (this._rightHandedSystem) {
  90971. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  90972. mat2.multiplyToRef(mat1, mat1);
  90973. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  90974. mat2.multiplyToRef(mat1, mat1);
  90975. }
  90976. else {
  90977. var _tmpVec = BoneIKController._tmpVecs[5];
  90978. _tmpVec.copyFrom(this._bendAxis);
  90979. _tmpVec.x *= -1;
  90980. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  90981. mat2.multiplyToRef(mat1, mat1);
  90982. }
  90983. if (this.poleAngle) {
  90984. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  90985. mat1.multiplyToRef(mat2, mat1);
  90986. }
  90987. if (this._bone1) {
  90988. if (this.slerpAmount < 1) {
  90989. if (!this._slerping) {
  90990. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  90991. }
  90992. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  90993. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  90994. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  90995. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  90996. this._slerping = true;
  90997. }
  90998. else {
  90999. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  91000. this._bone1Mat.copyFrom(mat1);
  91001. this._slerping = false;
  91002. }
  91003. }
  91004. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  91005. this._bone2Ang = angC;
  91006. };
  91007. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  91008. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  91009. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  91010. return BoneIKController;
  91011. }());
  91012. BABYLON.BoneIKController = BoneIKController;
  91013. })(BABYLON || (BABYLON = {}));
  91014. //# sourceMappingURL=babylon.boneIKController.js.map
  91015. var BABYLON;
  91016. (function (BABYLON) {
  91017. /**
  91018. * Class used to make a bone look toward a point in space
  91019. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  91020. */
  91021. var BoneLookController = /** @class */ (function () {
  91022. /**
  91023. * Create a BoneLookController
  91024. * @param mesh the mesh that the bone belongs to
  91025. * @param bone the bone that will be looking to the target
  91026. * @param target the target Vector3 to look at
  91027. * @param settings optional settings:
  91028. * * maxYaw: the maximum angle the bone will yaw to
  91029. * * minYaw: the minimum angle the bone will yaw to
  91030. * * maxPitch: the maximum angle the bone will pitch to
  91031. * * minPitch: the minimum angle the bone will yaw to
  91032. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  91033. * * upAxis: the up axis of the coordinate system
  91034. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  91035. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  91036. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  91037. * * adjustYaw: used to make an adjustment to the yaw of the bone
  91038. * * adjustPitch: used to make an adjustment to the pitch of the bone
  91039. * * adjustRoll: used to make an adjustment to the roll of the bone
  91040. **/
  91041. function BoneLookController(mesh, bone, target, options) {
  91042. /**
  91043. * The up axis of the coordinate system that is used when the bone is rotated
  91044. */
  91045. this.upAxis = BABYLON.Vector3.Up();
  91046. /**
  91047. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  91048. */
  91049. this.upAxisSpace = BABYLON.Space.LOCAL;
  91050. /**
  91051. * Used to make an adjustment to the yaw of the bone
  91052. */
  91053. this.adjustYaw = 0;
  91054. /**
  91055. * Used to make an adjustment to the pitch of the bone
  91056. */
  91057. this.adjustPitch = 0;
  91058. /**
  91059. * Used to make an adjustment to the roll of the bone
  91060. */
  91061. this.adjustRoll = 0;
  91062. /**
  91063. * 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)
  91064. */
  91065. this.slerpAmount = 1;
  91066. this._boneQuat = BABYLON.Quaternion.Identity();
  91067. this._slerping = false;
  91068. this._firstFrameSkipped = false;
  91069. this._fowardAxis = BABYLON.Vector3.Forward();
  91070. this.mesh = mesh;
  91071. this.bone = bone;
  91072. this.target = target;
  91073. if (options) {
  91074. if (options.adjustYaw) {
  91075. this.adjustYaw = options.adjustYaw;
  91076. }
  91077. if (options.adjustPitch) {
  91078. this.adjustPitch = options.adjustPitch;
  91079. }
  91080. if (options.adjustRoll) {
  91081. this.adjustRoll = options.adjustRoll;
  91082. }
  91083. if (options.maxYaw != null) {
  91084. this.maxYaw = options.maxYaw;
  91085. }
  91086. else {
  91087. this.maxYaw = Math.PI;
  91088. }
  91089. if (options.minYaw != null) {
  91090. this.minYaw = options.minYaw;
  91091. }
  91092. else {
  91093. this.minYaw = -Math.PI;
  91094. }
  91095. if (options.maxPitch != null) {
  91096. this.maxPitch = options.maxPitch;
  91097. }
  91098. else {
  91099. this.maxPitch = Math.PI;
  91100. }
  91101. if (options.minPitch != null) {
  91102. this.minPitch = options.minPitch;
  91103. }
  91104. else {
  91105. this.minPitch = -Math.PI;
  91106. }
  91107. if (options.slerpAmount != null) {
  91108. this.slerpAmount = options.slerpAmount;
  91109. }
  91110. if (options.upAxis != null) {
  91111. this.upAxis = options.upAxis;
  91112. }
  91113. if (options.upAxisSpace != null) {
  91114. this.upAxisSpace = options.upAxisSpace;
  91115. }
  91116. if (options.yawAxis != null || options.pitchAxis != null) {
  91117. var newYawAxis = BABYLON.Axis.Y;
  91118. var newPitchAxis = BABYLON.Axis.X;
  91119. if (options.yawAxis != null) {
  91120. newYawAxis = options.yawAxis.clone();
  91121. newYawAxis.normalize();
  91122. }
  91123. if (options.pitchAxis != null) {
  91124. newPitchAxis = options.pitchAxis.clone();
  91125. newPitchAxis.normalize();
  91126. }
  91127. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  91128. this._transformYawPitch = BABYLON.Matrix.Identity();
  91129. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  91130. this._transformYawPitchInv = this._transformYawPitch.clone();
  91131. this._transformYawPitch.invert();
  91132. }
  91133. }
  91134. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  91135. this.upAxisSpace = BABYLON.Space.LOCAL;
  91136. }
  91137. }
  91138. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  91139. /**
  91140. * Gets or sets the minimum yaw angle that the bone can look to
  91141. */
  91142. get: function () {
  91143. return this._minYaw;
  91144. },
  91145. set: function (value) {
  91146. this._minYaw = value;
  91147. this._minYawSin = Math.sin(value);
  91148. this._minYawCos = Math.cos(value);
  91149. if (this._maxYaw != null) {
  91150. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  91151. this._yawRange = this._maxYaw - this._minYaw;
  91152. }
  91153. },
  91154. enumerable: true,
  91155. configurable: true
  91156. });
  91157. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  91158. /**
  91159. * Gets or sets the maximum yaw angle that the bone can look to
  91160. */
  91161. get: function () {
  91162. return this._maxYaw;
  91163. },
  91164. set: function (value) {
  91165. this._maxYaw = value;
  91166. this._maxYawSin = Math.sin(value);
  91167. this._maxYawCos = Math.cos(value);
  91168. if (this._minYaw != null) {
  91169. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  91170. this._yawRange = this._maxYaw - this._minYaw;
  91171. }
  91172. },
  91173. enumerable: true,
  91174. configurable: true
  91175. });
  91176. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  91177. /**
  91178. * Gets or sets the minimum pitch angle that the bone can look to
  91179. */
  91180. get: function () {
  91181. return this._minPitch;
  91182. },
  91183. set: function (value) {
  91184. this._minPitch = value;
  91185. this._minPitchTan = Math.tan(value);
  91186. },
  91187. enumerable: true,
  91188. configurable: true
  91189. });
  91190. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  91191. /**
  91192. * Gets or sets the maximum pitch angle that the bone can look to
  91193. */
  91194. get: function () {
  91195. return this._maxPitch;
  91196. },
  91197. set: function (value) {
  91198. this._maxPitch = value;
  91199. this._maxPitchTan = Math.tan(value);
  91200. },
  91201. enumerable: true,
  91202. configurable: true
  91203. });
  91204. /**
  91205. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  91206. */
  91207. BoneLookController.prototype.update = function () {
  91208. //skip the first frame when slerping so that the mesh rotation is correct
  91209. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  91210. this._firstFrameSkipped = true;
  91211. return;
  91212. }
  91213. var bone = this.bone;
  91214. var bonePos = BoneLookController._tmpVecs[0];
  91215. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  91216. var target = this.target;
  91217. var _tmpMat1 = BoneLookController._tmpMats[0];
  91218. var _tmpMat2 = BoneLookController._tmpMats[1];
  91219. var mesh = this.mesh;
  91220. var parentBone = bone.getParent();
  91221. var upAxis = BoneLookController._tmpVecs[1];
  91222. upAxis.copyFrom(this.upAxis);
  91223. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  91224. if (this._transformYawPitch) {
  91225. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  91226. }
  91227. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  91228. }
  91229. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  91230. mesh.getDirectionToRef(upAxis, upAxis);
  91231. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  91232. upAxis.normalize();
  91233. }
  91234. }
  91235. var checkYaw = false;
  91236. var checkPitch = false;
  91237. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  91238. checkYaw = true;
  91239. }
  91240. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  91241. checkPitch = true;
  91242. }
  91243. if (checkYaw || checkPitch) {
  91244. var spaceMat = BoneLookController._tmpMats[2];
  91245. var spaceMatInv = BoneLookController._tmpMats[3];
  91246. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  91247. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  91248. }
  91249. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  91250. spaceMat.copyFrom(mesh.getWorldMatrix());
  91251. }
  91252. else {
  91253. var forwardAxis = BoneLookController._tmpVecs[2];
  91254. forwardAxis.copyFrom(this._fowardAxis);
  91255. if (this._transformYawPitch) {
  91256. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  91257. }
  91258. if (parentBone) {
  91259. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  91260. }
  91261. else {
  91262. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  91263. }
  91264. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  91265. rightAxis.normalize();
  91266. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  91267. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  91268. }
  91269. spaceMat.invertToRef(spaceMatInv);
  91270. var xzlen = null;
  91271. if (checkPitch) {
  91272. var localTarget = BoneLookController._tmpVecs[3];
  91273. target.subtractToRef(bonePos, localTarget);
  91274. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  91275. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  91276. var pitch = Math.atan2(localTarget.y, xzlen);
  91277. var newPitch = pitch;
  91278. if (pitch > this._maxPitch) {
  91279. localTarget.y = this._maxPitchTan * xzlen;
  91280. newPitch = this._maxPitch;
  91281. }
  91282. else if (pitch < this._minPitch) {
  91283. localTarget.y = this._minPitchTan * xzlen;
  91284. newPitch = this._minPitch;
  91285. }
  91286. if (pitch != newPitch) {
  91287. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  91288. localTarget.addInPlace(bonePos);
  91289. target = localTarget;
  91290. }
  91291. }
  91292. if (checkYaw) {
  91293. var localTarget = BoneLookController._tmpVecs[4];
  91294. target.subtractToRef(bonePos, localTarget);
  91295. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  91296. var yaw = Math.atan2(localTarget.x, localTarget.z);
  91297. var newYaw = yaw;
  91298. if (yaw > this._maxYaw || yaw < this._minYaw) {
  91299. if (xzlen == null) {
  91300. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  91301. }
  91302. if (this._yawRange > Math.PI) {
  91303. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  91304. localTarget.z = this._maxYawCos * xzlen;
  91305. localTarget.x = this._maxYawSin * xzlen;
  91306. newYaw = this._maxYaw;
  91307. }
  91308. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  91309. localTarget.z = this._minYawCos * xzlen;
  91310. localTarget.x = this._minYawSin * xzlen;
  91311. newYaw = this._minYaw;
  91312. }
  91313. }
  91314. else {
  91315. if (yaw > this._maxYaw) {
  91316. localTarget.z = this._maxYawCos * xzlen;
  91317. localTarget.x = this._maxYawSin * xzlen;
  91318. newYaw = this._maxYaw;
  91319. }
  91320. else if (yaw < this._minYaw) {
  91321. localTarget.z = this._minYawCos * xzlen;
  91322. localTarget.x = this._minYawSin * xzlen;
  91323. newYaw = this._minYaw;
  91324. }
  91325. }
  91326. }
  91327. if (this._slerping && this._yawRange > Math.PI) {
  91328. //are we going to be crossing into the min/max region?
  91329. var boneFwd = BoneLookController._tmpVecs[8];
  91330. boneFwd.copyFrom(BABYLON.Axis.Z);
  91331. if (this._transformYawPitch) {
  91332. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  91333. }
  91334. var boneRotMat = BoneLookController._tmpMats[4];
  91335. this._boneQuat.toRotationMatrix(boneRotMat);
  91336. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  91337. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  91338. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  91339. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  91340. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  91341. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  91342. if (angBtwTar > angBtwMidYaw) {
  91343. if (xzlen == null) {
  91344. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  91345. }
  91346. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  91347. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  91348. if (angBtwMin < angBtwMax) {
  91349. newYaw = boneYaw + Math.PI * .75;
  91350. localTarget.z = Math.cos(newYaw) * xzlen;
  91351. localTarget.x = Math.sin(newYaw) * xzlen;
  91352. }
  91353. else {
  91354. newYaw = boneYaw - Math.PI * .75;
  91355. localTarget.z = Math.cos(newYaw) * xzlen;
  91356. localTarget.x = Math.sin(newYaw) * xzlen;
  91357. }
  91358. }
  91359. }
  91360. if (yaw != newYaw) {
  91361. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  91362. localTarget.addInPlace(bonePos);
  91363. target = localTarget;
  91364. }
  91365. }
  91366. }
  91367. var zaxis = BoneLookController._tmpVecs[5];
  91368. var xaxis = BoneLookController._tmpVecs[6];
  91369. var yaxis = BoneLookController._tmpVecs[7];
  91370. var _tmpQuat = BoneLookController._tmpQuat;
  91371. target.subtractToRef(bonePos, zaxis);
  91372. zaxis.normalize();
  91373. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  91374. xaxis.normalize();
  91375. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  91376. yaxis.normalize();
  91377. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  91378. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  91379. return;
  91380. }
  91381. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  91382. return;
  91383. }
  91384. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  91385. return;
  91386. }
  91387. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  91388. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  91389. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  91390. }
  91391. if (this.slerpAmount < 1) {
  91392. if (!this._slerping) {
  91393. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  91394. }
  91395. if (this._transformYawPitch) {
  91396. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  91397. }
  91398. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  91399. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  91400. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  91401. this._slerping = true;
  91402. }
  91403. else {
  91404. if (this._transformYawPitch) {
  91405. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  91406. }
  91407. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  91408. this._slerping = false;
  91409. }
  91410. };
  91411. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  91412. var angDiff = ang2 - ang1;
  91413. angDiff %= Math.PI * 2;
  91414. if (angDiff > Math.PI) {
  91415. angDiff -= Math.PI * 2;
  91416. }
  91417. else if (angDiff < -Math.PI) {
  91418. angDiff += Math.PI * 2;
  91419. }
  91420. return angDiff;
  91421. };
  91422. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  91423. ang1 %= (2 * Math.PI);
  91424. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  91425. ang2 %= (2 * Math.PI);
  91426. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  91427. var ab = 0;
  91428. if (ang1 < ang2) {
  91429. ab = ang2 - ang1;
  91430. }
  91431. else {
  91432. ab = ang1 - ang2;
  91433. }
  91434. if (ab > Math.PI) {
  91435. ab = Math.PI * 2 - ab;
  91436. }
  91437. return ab;
  91438. };
  91439. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  91440. ang %= (2 * Math.PI);
  91441. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  91442. ang1 %= (2 * Math.PI);
  91443. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  91444. ang2 %= (2 * Math.PI);
  91445. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  91446. if (ang1 < ang2) {
  91447. if (ang > ang1 && ang < ang2) {
  91448. return true;
  91449. }
  91450. }
  91451. else {
  91452. if (ang > ang2 && ang < ang1) {
  91453. return true;
  91454. }
  91455. }
  91456. return false;
  91457. };
  91458. 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()];
  91459. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  91460. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  91461. return BoneLookController;
  91462. }());
  91463. BABYLON.BoneLookController = BoneLookController;
  91464. })(BABYLON || (BABYLON = {}));
  91465. //# sourceMappingURL=babylon.boneLookController.js.map
  91466. var BABYLON;
  91467. (function (BABYLON) {
  91468. /**
  91469. * Class used to handle skinning animations
  91470. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  91471. */
  91472. var Skeleton = /** @class */ (function () {
  91473. /**
  91474. * Creates a new skeleton
  91475. * @param name defines the skeleton name
  91476. * @param id defines the skeleton Id
  91477. * @param scene defines the hosting scene
  91478. */
  91479. function Skeleton(
  91480. /** defines the skeleton name */
  91481. name,
  91482. /** defines the skeleton Id */
  91483. id, scene) {
  91484. this.name = name;
  91485. this.id = id;
  91486. /**
  91487. * Gets the list of child bones
  91488. */
  91489. this.bones = new Array();
  91490. /**
  91491. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  91492. */
  91493. this.needInitialSkinMatrix = false;
  91494. this._isDirty = true;
  91495. this._meshesWithPoseMatrix = new Array();
  91496. this._identity = BABYLON.Matrix.Identity();
  91497. this._ranges = {};
  91498. this._lastAbsoluteTransformsUpdateId = -1;
  91499. /**
  91500. * Specifies if the skeleton should be serialized
  91501. */
  91502. this.doNotSerialize = false;
  91503. this._animationPropertiesOverride = null;
  91504. // Events
  91505. /**
  91506. * An observable triggered before computing the skeleton's matrices
  91507. */
  91508. this.onBeforeComputeObservable = new BABYLON.Observable();
  91509. this.bones = [];
  91510. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  91511. scene.skeletons.push(this);
  91512. //make sure it will recalculate the matrix next time prepare is called.
  91513. this._isDirty = true;
  91514. }
  91515. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  91516. /**
  91517. * Gets or sets the animation properties override
  91518. */
  91519. get: function () {
  91520. if (!this._animationPropertiesOverride) {
  91521. return this._scene.animationPropertiesOverride;
  91522. }
  91523. return this._animationPropertiesOverride;
  91524. },
  91525. set: function (value) {
  91526. this._animationPropertiesOverride = value;
  91527. },
  91528. enumerable: true,
  91529. configurable: true
  91530. });
  91531. // Members
  91532. /**
  91533. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  91534. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  91535. * @returns a Float32Array containing matrices data
  91536. */
  91537. Skeleton.prototype.getTransformMatrices = function (mesh) {
  91538. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  91539. return mesh._bonesTransformMatrices;
  91540. }
  91541. if (!this._transformMatrices) {
  91542. this.prepare();
  91543. }
  91544. return this._transformMatrices;
  91545. };
  91546. /**
  91547. * Gets the current hosting scene
  91548. * @returns a scene object
  91549. */
  91550. Skeleton.prototype.getScene = function () {
  91551. return this._scene;
  91552. };
  91553. // Methods
  91554. /**
  91555. * Gets a string representing the current skeleton data
  91556. * @param fullDetails defines a boolean indicating if we want a verbose version
  91557. * @returns a string representing the current skeleton data
  91558. */
  91559. Skeleton.prototype.toString = function (fullDetails) {
  91560. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  91561. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  91562. if (fullDetails) {
  91563. ret += ", Ranges: {";
  91564. var first = true;
  91565. for (var name_1 in this._ranges) {
  91566. if (first) {
  91567. ret += ", ";
  91568. first = false;
  91569. }
  91570. ret += name_1;
  91571. }
  91572. ret += "}";
  91573. }
  91574. return ret;
  91575. };
  91576. /**
  91577. * Get bone's index searching by name
  91578. * @param name defines bone's name to search for
  91579. * @return the indice of the bone. Returns -1 if not found
  91580. */
  91581. Skeleton.prototype.getBoneIndexByName = function (name) {
  91582. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  91583. if (this.bones[boneIndex].name === name) {
  91584. return boneIndex;
  91585. }
  91586. }
  91587. return -1;
  91588. };
  91589. /**
  91590. * Creater a new animation range
  91591. * @param name defines the name of the range
  91592. * @param from defines the start key
  91593. * @param to defines the end key
  91594. */
  91595. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  91596. // check name not already in use
  91597. if (!this._ranges[name]) {
  91598. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  91599. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  91600. if (this.bones[i].animations[0]) {
  91601. this.bones[i].animations[0].createRange(name, from, to);
  91602. }
  91603. }
  91604. }
  91605. };
  91606. /**
  91607. * Delete a specific animation range
  91608. * @param name defines the name of the range
  91609. * @param deleteFrames defines if frames must be removed as well
  91610. */
  91611. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  91612. if (deleteFrames === void 0) { deleteFrames = true; }
  91613. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  91614. if (this.bones[i].animations[0]) {
  91615. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  91616. }
  91617. }
  91618. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  91619. };
  91620. /**
  91621. * Gets a specific animation range
  91622. * @param name defines the name of the range to look for
  91623. * @returns the requested animation range or null if not found
  91624. */
  91625. Skeleton.prototype.getAnimationRange = function (name) {
  91626. return this._ranges[name];
  91627. };
  91628. /**
  91629. * Gets the list of all animation ranges defined on this skeleton
  91630. * @returns an array
  91631. */
  91632. Skeleton.prototype.getAnimationRanges = function () {
  91633. var animationRanges = [];
  91634. var name;
  91635. var i = 0;
  91636. for (name in this._ranges) {
  91637. animationRanges[i] = this._ranges[name];
  91638. i++;
  91639. }
  91640. return animationRanges;
  91641. };
  91642. /**
  91643. * Copy animation range from a source skeleton.
  91644. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  91645. * @param source defines the source skeleton
  91646. * @param name defines the name of the range to copy
  91647. * @param rescaleAsRequired defines if rescaling must be applied if required
  91648. * @returns true if operation was successful
  91649. */
  91650. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  91651. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  91652. if (this._ranges[name] || !source.getAnimationRange(name)) {
  91653. return false;
  91654. }
  91655. var ret = true;
  91656. var frameOffset = this._getHighestAnimationFrame() + 1;
  91657. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  91658. var boneDict = {};
  91659. var sourceBones = source.bones;
  91660. var nBones;
  91661. var i;
  91662. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  91663. boneDict[sourceBones[i].name] = sourceBones[i];
  91664. }
  91665. if (this.bones.length !== sourceBones.length) {
  91666. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  91667. ret = false;
  91668. }
  91669. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  91670. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  91671. var boneName = this.bones[i].name;
  91672. var sourceBone = boneDict[boneName];
  91673. if (sourceBone) {
  91674. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  91675. }
  91676. else {
  91677. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  91678. ret = false;
  91679. }
  91680. }
  91681. // do not call createAnimationRange(), since it also is done to bones, which was already done
  91682. var range = source.getAnimationRange(name);
  91683. if (range) {
  91684. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  91685. }
  91686. return ret;
  91687. };
  91688. /**
  91689. * Forces the skeleton to go to rest pose
  91690. */
  91691. Skeleton.prototype.returnToRest = function () {
  91692. for (var index = 0; index < this.bones.length; index++) {
  91693. this.bones[index].returnToRest();
  91694. }
  91695. };
  91696. Skeleton.prototype._getHighestAnimationFrame = function () {
  91697. var ret = 0;
  91698. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  91699. if (this.bones[i].animations[0]) {
  91700. var highest = this.bones[i].animations[0].getHighestFrame();
  91701. if (ret < highest) {
  91702. ret = highest;
  91703. }
  91704. }
  91705. }
  91706. return ret;
  91707. };
  91708. /**
  91709. * Begin a specific animation range
  91710. * @param name defines the name of the range to start
  91711. * @param loop defines if looping must be turned on (false by default)
  91712. * @param speedRatio defines the speed ratio to apply (1 by default)
  91713. * @param onAnimationEnd defines a callback which will be called when animation will end
  91714. * @returns a new animatable
  91715. */
  91716. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  91717. var range = this.getAnimationRange(name);
  91718. if (!range) {
  91719. return null;
  91720. }
  91721. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  91722. };
  91723. /** @hidden */
  91724. Skeleton.prototype._markAsDirty = function () {
  91725. this._isDirty = true;
  91726. };
  91727. /** @hidden */
  91728. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  91729. this._meshesWithPoseMatrix.push(mesh);
  91730. };
  91731. /** @hidden */
  91732. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  91733. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  91734. if (index > -1) {
  91735. this._meshesWithPoseMatrix.splice(index, 1);
  91736. }
  91737. };
  91738. /** @hidden */
  91739. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  91740. this.onBeforeComputeObservable.notifyObservers(this);
  91741. for (var index = 0; index < this.bones.length; index++) {
  91742. var bone = this.bones[index];
  91743. var parentBone = bone.getParent();
  91744. if (parentBone) {
  91745. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  91746. }
  91747. else {
  91748. if (initialSkinMatrix) {
  91749. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  91750. }
  91751. else {
  91752. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  91753. }
  91754. }
  91755. if (bone._index !== -1) {
  91756. var mappedIndex = bone._index === null ? index : bone._index;
  91757. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  91758. }
  91759. }
  91760. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  91761. };
  91762. /**
  91763. * Build all resources required to render a skeleton
  91764. */
  91765. Skeleton.prototype.prepare = function () {
  91766. if (!this._isDirty) {
  91767. return;
  91768. }
  91769. if (this.needInitialSkinMatrix) {
  91770. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  91771. var mesh = this._meshesWithPoseMatrix[index];
  91772. var poseMatrix = mesh.getPoseMatrix();
  91773. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  91774. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  91775. }
  91776. if (this._synchronizedWithMesh !== mesh) {
  91777. this._synchronizedWithMesh = mesh;
  91778. // Prepare bones
  91779. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  91780. var bone = this.bones[boneIndex];
  91781. if (!bone.getParent()) {
  91782. var matrix = bone.getBaseMatrix();
  91783. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  91784. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  91785. }
  91786. }
  91787. }
  91788. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  91789. }
  91790. }
  91791. else {
  91792. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  91793. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  91794. }
  91795. this._computeTransformMatrices(this._transformMatrices, null);
  91796. }
  91797. this._isDirty = false;
  91798. this._scene._activeBones.addCount(this.bones.length, false);
  91799. };
  91800. /**
  91801. * Gets the list of animatables currently running for this skeleton
  91802. * @returns an array of animatables
  91803. */
  91804. Skeleton.prototype.getAnimatables = function () {
  91805. if (!this._animatables || this._animatables.length !== this.bones.length) {
  91806. this._animatables = [];
  91807. for (var index = 0; index < this.bones.length; index++) {
  91808. this._animatables.push(this.bones[index]);
  91809. }
  91810. }
  91811. return this._animatables;
  91812. };
  91813. /**
  91814. * Clone the current skeleton
  91815. * @param name defines the name of the new skeleton
  91816. * @param id defines the id of the enw skeleton
  91817. * @returns the new skeleton
  91818. */
  91819. Skeleton.prototype.clone = function (name, id) {
  91820. var result = new Skeleton(name, id || name, this._scene);
  91821. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  91822. for (var index = 0; index < this.bones.length; index++) {
  91823. var source = this.bones[index];
  91824. var parentBone = null;
  91825. var parent_1 = source.getParent();
  91826. if (parent_1) {
  91827. var parentIndex = this.bones.indexOf(parent_1);
  91828. parentBone = result.bones[parentIndex];
  91829. }
  91830. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  91831. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  91832. }
  91833. if (this._ranges) {
  91834. result._ranges = {};
  91835. for (var rangeName in this._ranges) {
  91836. var range = this._ranges[rangeName];
  91837. if (range) {
  91838. result._ranges[rangeName] = range.clone();
  91839. }
  91840. }
  91841. }
  91842. this._isDirty = true;
  91843. return result;
  91844. };
  91845. /**
  91846. * Enable animation blending for this skeleton
  91847. * @param blendingSpeed defines the blending speed to apply
  91848. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  91849. */
  91850. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  91851. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  91852. this.bones.forEach(function (bone) {
  91853. bone.animations.forEach(function (animation) {
  91854. animation.enableBlending = true;
  91855. animation.blendingSpeed = blendingSpeed;
  91856. });
  91857. });
  91858. };
  91859. /**
  91860. * Releases all resources associated with the current skeleton
  91861. */
  91862. Skeleton.prototype.dispose = function () {
  91863. this._meshesWithPoseMatrix = [];
  91864. // Animations
  91865. this.getScene().stopAnimation(this);
  91866. // Remove from scene
  91867. this.getScene().removeSkeleton(this);
  91868. };
  91869. /**
  91870. * Serialize the skeleton in a JSON object
  91871. * @returns a JSON object
  91872. */
  91873. Skeleton.prototype.serialize = function () {
  91874. var serializationObject = {};
  91875. serializationObject.name = this.name;
  91876. serializationObject.id = this.id;
  91877. if (this.dimensionsAtRest) {
  91878. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  91879. }
  91880. serializationObject.bones = [];
  91881. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  91882. for (var index = 0; index < this.bones.length; index++) {
  91883. var bone = this.bones[index];
  91884. var parent_2 = bone.getParent();
  91885. var serializedBone = {
  91886. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  91887. name: bone.name,
  91888. matrix: bone.getBaseMatrix().toArray(),
  91889. rest: bone.getRestPose().toArray()
  91890. };
  91891. serializationObject.bones.push(serializedBone);
  91892. if (bone.length) {
  91893. serializedBone.length = bone.length;
  91894. }
  91895. if (bone.metadata) {
  91896. serializedBone.metadata = bone.metadata;
  91897. }
  91898. if (bone.animations && bone.animations.length > 0) {
  91899. serializedBone.animation = bone.animations[0].serialize();
  91900. }
  91901. serializationObject.ranges = [];
  91902. for (var name in this._ranges) {
  91903. var source = this._ranges[name];
  91904. if (!source) {
  91905. continue;
  91906. }
  91907. var range = {};
  91908. range.name = name;
  91909. range.from = source.from;
  91910. range.to = source.to;
  91911. serializationObject.ranges.push(range);
  91912. }
  91913. }
  91914. return serializationObject;
  91915. };
  91916. /**
  91917. * Creates a new skeleton from serialized data
  91918. * @param parsedSkeleton defines the serialized data
  91919. * @param scene defines the hosting scene
  91920. * @returns a new skeleton
  91921. */
  91922. Skeleton.Parse = function (parsedSkeleton, scene) {
  91923. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  91924. if (parsedSkeleton.dimensionsAtRest) {
  91925. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  91926. }
  91927. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  91928. var index;
  91929. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  91930. var parsedBone = parsedSkeleton.bones[index];
  91931. var parentBone = null;
  91932. if (parsedBone.parentBoneIndex > -1) {
  91933. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  91934. }
  91935. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  91936. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  91937. if (parsedBone.id !== undefined && parsedBone.id !== null) {
  91938. bone.id = parsedBone.id;
  91939. }
  91940. if (parsedBone.length) {
  91941. bone.length = parsedBone.length;
  91942. }
  91943. if (parsedBone.metadata) {
  91944. bone.metadata = parsedBone.metadata;
  91945. }
  91946. if (parsedBone.animation) {
  91947. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  91948. }
  91949. }
  91950. // placed after bones, so createAnimationRange can cascade down
  91951. if (parsedSkeleton.ranges) {
  91952. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  91953. var data = parsedSkeleton.ranges[index];
  91954. skeleton.createAnimationRange(data.name, data.from, data.to);
  91955. }
  91956. }
  91957. return skeleton;
  91958. };
  91959. /**
  91960. * Compute all node absolute transforms
  91961. * @param forceUpdate defines if computation must be done even if cache is up to date
  91962. */
  91963. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  91964. if (forceUpdate === void 0) { forceUpdate = false; }
  91965. var renderId = this._scene.getRenderId();
  91966. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  91967. this.bones[0].computeAbsoluteTransforms();
  91968. this._lastAbsoluteTransformsUpdateId = renderId;
  91969. }
  91970. };
  91971. /**
  91972. * Gets the root pose matrix
  91973. * @returns a matrix
  91974. */
  91975. Skeleton.prototype.getPoseMatrix = function () {
  91976. var poseMatrix = null;
  91977. if (this._meshesWithPoseMatrix.length > 0) {
  91978. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  91979. }
  91980. return poseMatrix;
  91981. };
  91982. /**
  91983. * Sorts bones per internal index
  91984. */
  91985. Skeleton.prototype.sortBones = function () {
  91986. var bones = new Array();
  91987. var visited = new Array(this.bones.length);
  91988. for (var index = 0; index < this.bones.length; index++) {
  91989. this._sortBones(index, bones, visited);
  91990. }
  91991. this.bones = bones;
  91992. };
  91993. Skeleton.prototype._sortBones = function (index, bones, visited) {
  91994. if (visited[index]) {
  91995. return;
  91996. }
  91997. visited[index] = true;
  91998. var bone = this.bones[index];
  91999. if (bone._index === undefined) {
  92000. bone._index = index;
  92001. }
  92002. var parentBone = bone.getParent();
  92003. if (parentBone) {
  92004. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  92005. }
  92006. bones.push(bone);
  92007. };
  92008. return Skeleton;
  92009. }());
  92010. BABYLON.Skeleton = Skeleton;
  92011. })(BABYLON || (BABYLON = {}));
  92012. //# sourceMappingURL=babylon.skeleton.js.map
  92013. var BABYLON;
  92014. (function (BABYLON) {
  92015. ;
  92016. /**
  92017. * This groups tools to convert HDR texture to native colors array.
  92018. */
  92019. var HDRTools = /** @class */ (function () {
  92020. function HDRTools() {
  92021. }
  92022. HDRTools.Ldexp = function (mantissa, exponent) {
  92023. if (exponent > 1023) {
  92024. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  92025. }
  92026. if (exponent < -1074) {
  92027. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  92028. }
  92029. return mantissa * Math.pow(2, exponent);
  92030. };
  92031. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  92032. if (exponent > 0) { /*nonzero pixel*/
  92033. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  92034. float32array[index + 0] = red * exponent;
  92035. float32array[index + 1] = green * exponent;
  92036. float32array[index + 2] = blue * exponent;
  92037. }
  92038. else {
  92039. float32array[index + 0] = 0;
  92040. float32array[index + 1] = 0;
  92041. float32array[index + 2] = 0;
  92042. }
  92043. };
  92044. HDRTools.readStringLine = function (uint8array, startIndex) {
  92045. var line = "";
  92046. var character = "";
  92047. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  92048. character = String.fromCharCode(uint8array[i]);
  92049. if (character == "\n") {
  92050. break;
  92051. }
  92052. line += character;
  92053. }
  92054. return line;
  92055. };
  92056. /**
  92057. * Reads header information from an RGBE texture stored in a native array.
  92058. * More information on this format are available here:
  92059. * https://en.wikipedia.org/wiki/RGBE_image_format
  92060. *
  92061. * @param uint8array The binary file stored in native array.
  92062. * @return The header information.
  92063. */
  92064. HDRTools.RGBE_ReadHeader = function (uint8array) {
  92065. var height = 0;
  92066. var width = 0;
  92067. var line = this.readStringLine(uint8array, 0);
  92068. if (line[0] != '#' || line[1] != '?') {
  92069. throw "Bad HDR Format.";
  92070. }
  92071. var endOfHeader = false;
  92072. var findFormat = false;
  92073. var lineIndex = 0;
  92074. do {
  92075. lineIndex += (line.length + 1);
  92076. line = this.readStringLine(uint8array, lineIndex);
  92077. if (line == "FORMAT=32-bit_rle_rgbe") {
  92078. findFormat = true;
  92079. }
  92080. else if (line.length == 0) {
  92081. endOfHeader = true;
  92082. }
  92083. } while (!endOfHeader);
  92084. if (!findFormat) {
  92085. throw "HDR Bad header format, unsupported FORMAT";
  92086. }
  92087. lineIndex += (line.length + 1);
  92088. line = this.readStringLine(uint8array, lineIndex);
  92089. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  92090. var match = sizeRegexp.exec(line);
  92091. // TODO. Support +Y and -X if needed.
  92092. if (!match || match.length < 3) {
  92093. throw "HDR Bad header format, no size";
  92094. }
  92095. width = parseInt(match[2]);
  92096. height = parseInt(match[1]);
  92097. if (width < 8 || width > 0x7fff) {
  92098. throw "HDR Bad header format, unsupported size";
  92099. }
  92100. lineIndex += (line.length + 1);
  92101. return {
  92102. height: height,
  92103. width: width,
  92104. dataPosition: lineIndex
  92105. };
  92106. };
  92107. /**
  92108. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  92109. * This RGBE texture needs to store the information as a panorama.
  92110. *
  92111. * More information on this format are available here:
  92112. * https://en.wikipedia.org/wiki/RGBE_image_format
  92113. *
  92114. * @param buffer The binary file stored in an array buffer.
  92115. * @param size The expected size of the extracted cubemap.
  92116. * @return The Cube Map information.
  92117. */
  92118. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  92119. var uint8array = new Uint8Array(buffer);
  92120. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  92121. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  92122. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  92123. return cubeMapData;
  92124. };
  92125. /**
  92126. * Returns the pixels data extracted from an RGBE texture.
  92127. * This pixels will be stored left to right up to down in the R G B order in one array.
  92128. *
  92129. * More information on this format are available here:
  92130. * https://en.wikipedia.org/wiki/RGBE_image_format
  92131. *
  92132. * @param uint8array The binary file stored in an array buffer.
  92133. * @param hdrInfo The header information of the file.
  92134. * @return The pixels data in RGB right to left up to down order.
  92135. */
  92136. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  92137. // Keep for multi format supports.
  92138. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  92139. };
  92140. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  92141. var num_scanlines = hdrInfo.height;
  92142. var scanline_width = hdrInfo.width;
  92143. var a, b, c, d, count;
  92144. var dataIndex = hdrInfo.dataPosition;
  92145. var index = 0, endIndex = 0, i = 0;
  92146. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  92147. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  92148. // 3 channels of 4 bytes per pixel in float.
  92149. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  92150. var resultArray = new Float32Array(resultBuffer);
  92151. // read in each successive scanline
  92152. while (num_scanlines > 0) {
  92153. a = uint8array[dataIndex++];
  92154. b = uint8array[dataIndex++];
  92155. c = uint8array[dataIndex++];
  92156. d = uint8array[dataIndex++];
  92157. if (a != 2 || b != 2 || (c & 0x80)) {
  92158. // this file is not run length encoded
  92159. throw "HDR Bad header format, not RLE";
  92160. }
  92161. if (((c << 8) | d) != scanline_width) {
  92162. throw "HDR Bad header format, wrong scan line width";
  92163. }
  92164. index = 0;
  92165. // read each of the four channels for the scanline into the buffer
  92166. for (i = 0; i < 4; i++) {
  92167. endIndex = (i + 1) * scanline_width;
  92168. while (index < endIndex) {
  92169. a = uint8array[dataIndex++];
  92170. b = uint8array[dataIndex++];
  92171. if (a > 128) {
  92172. // a run of the same value
  92173. count = a - 128;
  92174. if ((count == 0) || (count > endIndex - index)) {
  92175. throw "HDR Bad Format, bad scanline data (run)";
  92176. }
  92177. while (count-- > 0) {
  92178. scanLineArray[index++] = b;
  92179. }
  92180. }
  92181. else {
  92182. // a non-run
  92183. count = a;
  92184. if ((count == 0) || (count > endIndex - index)) {
  92185. throw "HDR Bad Format, bad scanline data (non-run)";
  92186. }
  92187. scanLineArray[index++] = b;
  92188. if (--count > 0) {
  92189. for (var j = 0; j < count; j++) {
  92190. scanLineArray[index++] = uint8array[dataIndex++];
  92191. }
  92192. }
  92193. }
  92194. }
  92195. }
  92196. // now convert data from buffer into floats
  92197. for (i = 0; i < scanline_width; i++) {
  92198. a = scanLineArray[i];
  92199. b = scanLineArray[i + scanline_width];
  92200. c = scanLineArray[i + 2 * scanline_width];
  92201. d = scanLineArray[i + 3 * scanline_width];
  92202. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  92203. }
  92204. num_scanlines--;
  92205. }
  92206. return resultArray;
  92207. };
  92208. return HDRTools;
  92209. }());
  92210. BABYLON.HDRTools = HDRTools;
  92211. })(BABYLON || (BABYLON = {}));
  92212. //# sourceMappingURL=babylon.hdr.js.map
  92213. var BABYLON;
  92214. (function (BABYLON) {
  92215. /**
  92216. * This represents a texture coming from an HDR input.
  92217. *
  92218. * The only supported format is currently panorama picture stored in RGBE format.
  92219. * Example of such files can be found on HDRLib: http://hdrlib.com/
  92220. */
  92221. var HDRCubeTexture = /** @class */ (function (_super) {
  92222. __extends(HDRCubeTexture, _super);
  92223. /**
  92224. * Instantiates an HDRTexture from the following parameters.
  92225. *
  92226. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  92227. * @param scene The scene the texture will be used in
  92228. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  92229. * @param noMipmap Forces to not generate the mipmap if true
  92230. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  92231. * @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)
  92232. * @param reserved Reserved flag for internal use.
  92233. */
  92234. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  92235. if (noMipmap === void 0) { noMipmap = false; }
  92236. if (generateHarmonics === void 0) { generateHarmonics = true; }
  92237. if (gammaSpace === void 0) { gammaSpace = false; }
  92238. if (reserved === void 0) { reserved = false; }
  92239. if (onLoad === void 0) { onLoad = null; }
  92240. if (onError === void 0) { onError = null; }
  92241. var _this = _super.call(this, scene) || this;
  92242. _this._generateHarmonics = true;
  92243. _this._onLoad = null;
  92244. _this._onError = null;
  92245. /**
  92246. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  92247. */
  92248. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  92249. _this._isBlocking = true;
  92250. _this._rotationY = 0;
  92251. /**
  92252. * Gets or sets the center of the bounding box associated with the cube texture
  92253. * It must define where the camera used to render the texture was set
  92254. */
  92255. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  92256. if (!url) {
  92257. return _this;
  92258. }
  92259. _this.name = url;
  92260. _this.url = url;
  92261. _this.hasAlpha = false;
  92262. _this.isCube = true;
  92263. _this._textureMatrix = BABYLON.Matrix.Identity();
  92264. _this._onLoad = onLoad;
  92265. _this._onError = onError;
  92266. _this.gammaSpace = gammaSpace;
  92267. _this._noMipmap = noMipmap;
  92268. _this._size = size;
  92269. _this._texture = _this._getFromCache(url, _this._noMipmap);
  92270. if (!_this._texture) {
  92271. if (!scene.useDelayedTextureLoading) {
  92272. _this.loadTexture();
  92273. }
  92274. else {
  92275. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  92276. }
  92277. }
  92278. return _this;
  92279. }
  92280. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  92281. /**
  92282. * Gets wether or not the texture is blocking during loading.
  92283. */
  92284. get: function () {
  92285. return this._isBlocking;
  92286. },
  92287. /**
  92288. * Sets wether or not the texture is blocking during loading.
  92289. */
  92290. set: function (value) {
  92291. this._isBlocking = value;
  92292. },
  92293. enumerable: true,
  92294. configurable: true
  92295. });
  92296. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  92297. /**
  92298. * Gets texture matrix rotation angle around Y axis radians.
  92299. */
  92300. get: function () {
  92301. return this._rotationY;
  92302. },
  92303. /**
  92304. * Sets texture matrix rotation angle around Y axis in radians.
  92305. */
  92306. set: function (value) {
  92307. this._rotationY = value;
  92308. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  92309. },
  92310. enumerable: true,
  92311. configurable: true
  92312. });
  92313. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  92314. get: function () {
  92315. return this._boundingBoxSize;
  92316. },
  92317. /**
  92318. * Gets or sets the size of the bounding box associated with the cube texture
  92319. * When defined, the cubemap will switch to local mode
  92320. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  92321. * @example https://www.babylonjs-playground.com/#RNASML
  92322. */
  92323. set: function (value) {
  92324. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  92325. return;
  92326. }
  92327. this._boundingBoxSize = value;
  92328. var scene = this.getScene();
  92329. if (scene) {
  92330. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  92331. }
  92332. },
  92333. enumerable: true,
  92334. configurable: true
  92335. });
  92336. /**
  92337. * Occurs when the file is raw .hdr file.
  92338. */
  92339. HDRCubeTexture.prototype.loadTexture = function () {
  92340. var _this = this;
  92341. var callback = function (buffer) {
  92342. _this.lodGenerationOffset = 0.0;
  92343. _this.lodGenerationScale = 0.8;
  92344. var scene = _this.getScene();
  92345. if (!scene) {
  92346. return null;
  92347. }
  92348. // Extract the raw linear data.
  92349. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  92350. // Generate harmonics if needed.
  92351. if (_this._generateHarmonics) {
  92352. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  92353. _this.sphericalPolynomial = sphericalPolynomial;
  92354. }
  92355. var results = [];
  92356. var byteArray = null;
  92357. // Push each faces.
  92358. for (var j = 0; j < 6; j++) {
  92359. // Create uintarray fallback.
  92360. if (!scene.getEngine().getCaps().textureFloat) {
  92361. // 3 channels of 1 bytes per pixel in bytes.
  92362. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  92363. byteArray = new Uint8Array(byteBuffer);
  92364. }
  92365. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  92366. // If special cases.
  92367. if (_this.gammaSpace || byteArray) {
  92368. for (var i = 0; i < _this._size * _this._size; i++) {
  92369. // Put in gamma space if requested.
  92370. if (_this.gammaSpace) {
  92371. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  92372. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  92373. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  92374. }
  92375. // Convert to int texture for fallback.
  92376. if (byteArray) {
  92377. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  92378. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  92379. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  92380. // May use luminance instead if the result is not accurate.
  92381. var max = Math.max(Math.max(r, g), b);
  92382. if (max > 255) {
  92383. var scale = 255 / max;
  92384. r *= scale;
  92385. g *= scale;
  92386. b *= scale;
  92387. }
  92388. byteArray[(i * 3) + 0] = r;
  92389. byteArray[(i * 3) + 1] = g;
  92390. byteArray[(i * 3) + 2] = b;
  92391. }
  92392. }
  92393. }
  92394. if (byteArray) {
  92395. results.push(byteArray);
  92396. }
  92397. else {
  92398. results.push(dataFace);
  92399. }
  92400. }
  92401. return results;
  92402. };
  92403. var scene = this.getScene();
  92404. if (scene) {
  92405. 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);
  92406. }
  92407. };
  92408. HDRCubeTexture.prototype.clone = function () {
  92409. var scene = this.getScene();
  92410. if (!scene) {
  92411. return this;
  92412. }
  92413. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  92414. // Base texture
  92415. newTexture.level = this.level;
  92416. newTexture.wrapU = this.wrapU;
  92417. newTexture.wrapV = this.wrapV;
  92418. newTexture.coordinatesIndex = this.coordinatesIndex;
  92419. newTexture.coordinatesMode = this.coordinatesMode;
  92420. return newTexture;
  92421. };
  92422. // Methods
  92423. HDRCubeTexture.prototype.delayLoad = function () {
  92424. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  92425. return;
  92426. }
  92427. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  92428. this._texture = this._getFromCache(this.url, this._noMipmap);
  92429. if (!this._texture) {
  92430. this.loadTexture();
  92431. }
  92432. };
  92433. /**
  92434. * Get the texture reflection matrix used to rotate/transform the reflection.
  92435. * @returns the reflection matrix
  92436. */
  92437. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  92438. return this._textureMatrix;
  92439. };
  92440. /**
  92441. * Set the texture reflection matrix used to rotate/transform the reflection.
  92442. * @param value Define the reflection matrix to set
  92443. */
  92444. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  92445. this._textureMatrix = value;
  92446. };
  92447. /**
  92448. * Parses a JSON representation of an HDR Texture in order to create the texture
  92449. * @param parsedTexture Define the JSON representation
  92450. * @param scene Define the scene the texture should be created in
  92451. * @param rootUrl Define the root url in case we need to load relative dependencies
  92452. * @returns the newly created texture after parsing
  92453. */
  92454. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  92455. var texture = null;
  92456. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  92457. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  92458. texture.name = parsedTexture.name;
  92459. texture.hasAlpha = parsedTexture.hasAlpha;
  92460. texture.level = parsedTexture.level;
  92461. texture.coordinatesMode = parsedTexture.coordinatesMode;
  92462. texture.isBlocking = parsedTexture.isBlocking;
  92463. }
  92464. if (texture) {
  92465. if (parsedTexture.boundingBoxPosition) {
  92466. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  92467. }
  92468. if (parsedTexture.boundingBoxSize) {
  92469. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  92470. }
  92471. if (parsedTexture.rotationY) {
  92472. texture.rotationY = parsedTexture.rotationY;
  92473. }
  92474. }
  92475. return texture;
  92476. };
  92477. HDRCubeTexture.prototype.serialize = function () {
  92478. if (!this.name) {
  92479. return null;
  92480. }
  92481. var serializationObject = {};
  92482. serializationObject.name = this.name;
  92483. serializationObject.hasAlpha = this.hasAlpha;
  92484. serializationObject.isCube = true;
  92485. serializationObject.level = this.level;
  92486. serializationObject.size = this._size;
  92487. serializationObject.coordinatesMode = this.coordinatesMode;
  92488. serializationObject.useInGammaSpace = this.gammaSpace;
  92489. serializationObject.generateHarmonics = this._generateHarmonics;
  92490. serializationObject.customType = "BABYLON.HDRCubeTexture";
  92491. serializationObject.noMipmap = this._noMipmap;
  92492. serializationObject.isBlocking = this._isBlocking;
  92493. serializationObject.rotationY = this._rotationY;
  92494. return serializationObject;
  92495. };
  92496. HDRCubeTexture._facesMapping = [
  92497. "right",
  92498. "left",
  92499. "up",
  92500. "down",
  92501. "front",
  92502. "back"
  92503. ];
  92504. return HDRCubeTexture;
  92505. }(BABYLON.BaseTexture));
  92506. BABYLON.HDRCubeTexture = HDRCubeTexture;
  92507. })(BABYLON || (BABYLON = {}));
  92508. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  92509. var BABYLON;
  92510. (function (BABYLON) {
  92511. /**
  92512. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  92513. */
  92514. var PanoramaToCubeMapTools = /** @class */ (function () {
  92515. function PanoramaToCubeMapTools() {
  92516. }
  92517. /**
  92518. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  92519. *
  92520. * @param float32Array The source data.
  92521. * @param inputWidth The width of the input panorama.
  92522. * @param inputHeight The height of the input panorama.
  92523. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  92524. * @return The cubemap data
  92525. */
  92526. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  92527. if (!float32Array) {
  92528. throw "ConvertPanoramaToCubemap: input cannot be null";
  92529. }
  92530. if (float32Array.length != inputWidth * inputHeight * 3) {
  92531. throw "ConvertPanoramaToCubemap: input size is wrong";
  92532. }
  92533. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  92534. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  92535. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  92536. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  92537. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  92538. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  92539. return {
  92540. front: textureFront,
  92541. back: textureBack,
  92542. left: textureLeft,
  92543. right: textureRight,
  92544. up: textureUp,
  92545. down: textureDown,
  92546. size: size,
  92547. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  92548. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  92549. gammaSpace: false,
  92550. };
  92551. };
  92552. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  92553. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  92554. var textureArray = new Float32Array(buffer);
  92555. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  92556. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  92557. var dy = 1 / texSize;
  92558. var fy = 0;
  92559. for (var y = 0; y < texSize; y++) {
  92560. var xv1 = faceData[0];
  92561. var xv2 = faceData[2];
  92562. for (var x = 0; x < texSize; x++) {
  92563. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  92564. v.normalize();
  92565. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  92566. // 3 channels per pixels
  92567. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  92568. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  92569. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  92570. xv1 = xv1.add(rotDX1);
  92571. xv2 = xv2.add(rotDX2);
  92572. }
  92573. fy += dy;
  92574. }
  92575. return textureArray;
  92576. };
  92577. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  92578. var theta = Math.atan2(vDir.z, vDir.x);
  92579. var phi = Math.acos(vDir.y);
  92580. while (theta < -Math.PI)
  92581. theta += 2 * Math.PI;
  92582. while (theta > Math.PI)
  92583. theta -= 2 * Math.PI;
  92584. var dx = theta / Math.PI;
  92585. var dy = phi / Math.PI;
  92586. // recenter.
  92587. dx = dx * 0.5 + 0.5;
  92588. var px = Math.round(dx * inputWidth);
  92589. if (px < 0)
  92590. px = 0;
  92591. else if (px >= inputWidth)
  92592. px = inputWidth - 1;
  92593. var py = Math.round(dy * inputHeight);
  92594. if (py < 0)
  92595. py = 0;
  92596. else if (py >= inputHeight)
  92597. py = inputHeight - 1;
  92598. var inputY = (inputHeight - py - 1);
  92599. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  92600. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  92601. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  92602. return {
  92603. r: r,
  92604. g: g,
  92605. b: b
  92606. };
  92607. };
  92608. PanoramaToCubeMapTools.FACE_FRONT = [
  92609. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  92610. new BABYLON.Vector3(1.0, -1.0, -1.0),
  92611. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  92612. new BABYLON.Vector3(1.0, 1.0, -1.0)
  92613. ];
  92614. PanoramaToCubeMapTools.FACE_BACK = [
  92615. new BABYLON.Vector3(1.0, -1.0, 1.0),
  92616. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  92617. new BABYLON.Vector3(1.0, 1.0, 1.0),
  92618. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  92619. ];
  92620. PanoramaToCubeMapTools.FACE_RIGHT = [
  92621. new BABYLON.Vector3(1.0, -1.0, -1.0),
  92622. new BABYLON.Vector3(1.0, -1.0, 1.0),
  92623. new BABYLON.Vector3(1.0, 1.0, -1.0),
  92624. new BABYLON.Vector3(1.0, 1.0, 1.0)
  92625. ];
  92626. PanoramaToCubeMapTools.FACE_LEFT = [
  92627. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  92628. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  92629. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  92630. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  92631. ];
  92632. PanoramaToCubeMapTools.FACE_DOWN = [
  92633. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  92634. new BABYLON.Vector3(1.0, 1.0, -1.0),
  92635. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  92636. new BABYLON.Vector3(1.0, 1.0, 1.0)
  92637. ];
  92638. PanoramaToCubeMapTools.FACE_UP = [
  92639. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  92640. new BABYLON.Vector3(1.0, -1.0, 1.0),
  92641. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  92642. new BABYLON.Vector3(1.0, -1.0, -1.0)
  92643. ];
  92644. return PanoramaToCubeMapTools;
  92645. }());
  92646. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  92647. })(BABYLON || (BABYLON = {}));
  92648. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  92649. var BABYLON;
  92650. (function (BABYLON) {
  92651. /**
  92652. * Vector2 wth index property
  92653. */
  92654. var IndexedVector2 = /** @class */ (function (_super) {
  92655. __extends(IndexedVector2, _super);
  92656. function IndexedVector2(original,
  92657. /** Index of the vector2 */
  92658. index) {
  92659. var _this = _super.call(this, original.x, original.y) || this;
  92660. _this.index = index;
  92661. return _this;
  92662. }
  92663. return IndexedVector2;
  92664. }(BABYLON.Vector2));
  92665. /**
  92666. * Defines points to create a polygon
  92667. */
  92668. var PolygonPoints = /** @class */ (function () {
  92669. function PolygonPoints() {
  92670. this.elements = new Array();
  92671. }
  92672. PolygonPoints.prototype.add = function (originalPoints) {
  92673. var _this = this;
  92674. var result = new Array();
  92675. originalPoints.forEach(function (point) {
  92676. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  92677. var newPoint = new IndexedVector2(point, _this.elements.length);
  92678. result.push(newPoint);
  92679. _this.elements.push(newPoint);
  92680. }
  92681. });
  92682. return result;
  92683. };
  92684. PolygonPoints.prototype.computeBounds = function () {
  92685. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  92686. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  92687. this.elements.forEach(function (point) {
  92688. // x
  92689. if (point.x < lmin.x) {
  92690. lmin.x = point.x;
  92691. }
  92692. else if (point.x > lmax.x) {
  92693. lmax.x = point.x;
  92694. }
  92695. // y
  92696. if (point.y < lmin.y) {
  92697. lmin.y = point.y;
  92698. }
  92699. else if (point.y > lmax.y) {
  92700. lmax.y = point.y;
  92701. }
  92702. });
  92703. return {
  92704. min: lmin,
  92705. max: lmax,
  92706. width: lmax.x - lmin.x,
  92707. height: lmax.y - lmin.y
  92708. };
  92709. };
  92710. return PolygonPoints;
  92711. }());
  92712. /**
  92713. * Polygon
  92714. * @see https://doc.babylonjs.com/how_to/parametric_shapes#non-regular-polygon
  92715. */
  92716. var Polygon = /** @class */ (function () {
  92717. function Polygon() {
  92718. }
  92719. /**
  92720. * Creates a rectangle
  92721. * @param xmin bottom X coord
  92722. * @param ymin bottom Y coord
  92723. * @param xmax top X coord
  92724. * @param ymax top Y coord
  92725. * @returns points that make the resulting rectation
  92726. */
  92727. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  92728. return [
  92729. new BABYLON.Vector2(xmin, ymin),
  92730. new BABYLON.Vector2(xmax, ymin),
  92731. new BABYLON.Vector2(xmax, ymax),
  92732. new BABYLON.Vector2(xmin, ymax)
  92733. ];
  92734. };
  92735. /**
  92736. * Creates a circle
  92737. * @param radius radius of circle
  92738. * @param cx scale in x
  92739. * @param cy scale in y
  92740. * @param numberOfSides number of sides that make up the circle
  92741. * @returns points that make the resulting circle
  92742. */
  92743. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  92744. if (cx === void 0) { cx = 0; }
  92745. if (cy === void 0) { cy = 0; }
  92746. if (numberOfSides === void 0) { numberOfSides = 32; }
  92747. var result = new Array();
  92748. var angle = 0;
  92749. var increment = (Math.PI * 2) / numberOfSides;
  92750. for (var i = 0; i < numberOfSides; i++) {
  92751. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  92752. angle -= increment;
  92753. }
  92754. return result;
  92755. };
  92756. /**
  92757. * Creates a polygon from input string
  92758. * @param input Input polygon data
  92759. * @returns the parsed points
  92760. */
  92761. Polygon.Parse = function (input) {
  92762. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  92763. var i, result = [];
  92764. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  92765. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  92766. }
  92767. return result;
  92768. };
  92769. /**
  92770. * Starts building a polygon from x and y coordinates
  92771. * @param x x coordinate
  92772. * @param y y coordinate
  92773. * @returns the started path2
  92774. */
  92775. Polygon.StartingAt = function (x, y) {
  92776. return BABYLON.Path2.StartingAt(x, y);
  92777. };
  92778. return Polygon;
  92779. }());
  92780. BABYLON.Polygon = Polygon;
  92781. /**
  92782. * Builds a polygon
  92783. * @see https://doc.babylonjs.com/how_to/polygonmeshbuilder
  92784. */
  92785. var PolygonMeshBuilder = /** @class */ (function () {
  92786. /**
  92787. * Creates a PolygonMeshBuilder
  92788. * @param name name of the builder
  92789. * @param contours Path of the polygon
  92790. * @param scene scene to add to
  92791. */
  92792. function PolygonMeshBuilder(name, contours, scene) {
  92793. this._points = new PolygonPoints();
  92794. this._outlinepoints = new PolygonPoints();
  92795. this._holes = new Array();
  92796. this._epoints = new Array();
  92797. this._eholes = new Array();
  92798. this._name = name;
  92799. this._scene = scene;
  92800. var points;
  92801. if (contours instanceof BABYLON.Path2) {
  92802. points = contours.getPoints();
  92803. }
  92804. else {
  92805. points = contours;
  92806. }
  92807. this._addToepoint(points);
  92808. this._points.add(points);
  92809. this._outlinepoints.add(points);
  92810. if (typeof earcut === 'undefined') {
  92811. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  92812. }
  92813. }
  92814. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  92815. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  92816. var p = points_1[_i];
  92817. this._epoints.push(p.x, p.y);
  92818. }
  92819. };
  92820. /**
  92821. * Adds a whole within the polygon
  92822. * @param hole Array of points defining the hole
  92823. * @returns this
  92824. */
  92825. PolygonMeshBuilder.prototype.addHole = function (hole) {
  92826. this._points.add(hole);
  92827. var holepoints = new PolygonPoints();
  92828. holepoints.add(hole);
  92829. this._holes.push(holepoints);
  92830. this._eholes.push(this._epoints.length / 2);
  92831. this._addToepoint(hole);
  92832. return this;
  92833. };
  92834. /**
  92835. * Creates the polygon
  92836. * @param updatable If the mesh should be updatable
  92837. * @param depth The depth of the mesh created
  92838. * @returns the created mesh
  92839. */
  92840. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  92841. var _this = this;
  92842. if (updatable === void 0) { updatable = false; }
  92843. if (depth === void 0) { depth = 0; }
  92844. var result = new BABYLON.Mesh(this._name, this._scene);
  92845. var normals = new Array();
  92846. var positions = new Array();
  92847. var uvs = new Array();
  92848. var bounds = this._points.computeBounds();
  92849. this._points.elements.forEach(function (p) {
  92850. normals.push(0, 1.0, 0);
  92851. positions.push(p.x, 0, p.y);
  92852. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  92853. });
  92854. var indices = new Array();
  92855. var res = earcut(this._epoints, this._eholes, 2);
  92856. for (var i = 0; i < res.length; i++) {
  92857. indices.push(res[i]);
  92858. }
  92859. if (depth > 0) {
  92860. var positionscount = (positions.length / 3); //get the current pointcount
  92861. this._points.elements.forEach(function (p) {
  92862. normals.push(0, -1.0, 0);
  92863. positions.push(p.x, -depth, p.y);
  92864. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  92865. });
  92866. var totalCount = indices.length;
  92867. for (var i = 0; i < totalCount; i += 3) {
  92868. var i0 = indices[i + 0];
  92869. var i1 = indices[i + 1];
  92870. var i2 = indices[i + 2];
  92871. indices.push(i2 + positionscount);
  92872. indices.push(i1 + positionscount);
  92873. indices.push(i0 + positionscount);
  92874. }
  92875. //Add the sides
  92876. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  92877. this._holes.forEach(function (hole) {
  92878. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  92879. });
  92880. }
  92881. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  92882. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  92883. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  92884. result.setIndices(indices);
  92885. return result;
  92886. };
  92887. /**
  92888. * Adds a side to the polygon
  92889. * @param positions points that make the polygon
  92890. * @param normals normals of the polygon
  92891. * @param uvs uvs of the polygon
  92892. * @param indices indices of the polygon
  92893. * @param bounds bounds of the polygon
  92894. * @param points points of the polygon
  92895. * @param depth depth of the polygon
  92896. * @param flip flip of the polygon
  92897. */
  92898. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  92899. var StartIndex = positions.length / 3;
  92900. var ulength = 0;
  92901. for (var i = 0; i < points.elements.length; i++) {
  92902. var p = points.elements[i];
  92903. var p1;
  92904. if ((i + 1) > points.elements.length - 1) {
  92905. p1 = points.elements[0];
  92906. }
  92907. else {
  92908. p1 = points.elements[i + 1];
  92909. }
  92910. positions.push(p.x, 0, p.y);
  92911. positions.push(p.x, -depth, p.y);
  92912. positions.push(p1.x, 0, p1.y);
  92913. positions.push(p1.x, -depth, p1.y);
  92914. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  92915. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  92916. var v3 = v2.subtract(v1);
  92917. var v4 = new BABYLON.Vector3(0, 1, 0);
  92918. var vn = BABYLON.Vector3.Cross(v3, v4);
  92919. vn = vn.normalize();
  92920. uvs.push(ulength / bounds.width, 0);
  92921. uvs.push(ulength / bounds.width, 1);
  92922. ulength += v3.length();
  92923. uvs.push((ulength / bounds.width), 0);
  92924. uvs.push((ulength / bounds.width), 1);
  92925. if (!flip) {
  92926. normals.push(-vn.x, -vn.y, -vn.z);
  92927. normals.push(-vn.x, -vn.y, -vn.z);
  92928. normals.push(-vn.x, -vn.y, -vn.z);
  92929. normals.push(-vn.x, -vn.y, -vn.z);
  92930. indices.push(StartIndex);
  92931. indices.push(StartIndex + 1);
  92932. indices.push(StartIndex + 2);
  92933. indices.push(StartIndex + 1);
  92934. indices.push(StartIndex + 3);
  92935. indices.push(StartIndex + 2);
  92936. }
  92937. else {
  92938. normals.push(vn.x, vn.y, vn.z);
  92939. normals.push(vn.x, vn.y, vn.z);
  92940. normals.push(vn.x, vn.y, vn.z);
  92941. normals.push(vn.x, vn.y, vn.z);
  92942. indices.push(StartIndex);
  92943. indices.push(StartIndex + 2);
  92944. indices.push(StartIndex + 1);
  92945. indices.push(StartIndex + 1);
  92946. indices.push(StartIndex + 2);
  92947. indices.push(StartIndex + 3);
  92948. }
  92949. StartIndex += 4;
  92950. }
  92951. ;
  92952. };
  92953. return PolygonMeshBuilder;
  92954. }());
  92955. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  92956. })(BABYLON || (BABYLON = {}));
  92957. //# sourceMappingURL=babylon.polygonMesh.js.map
  92958. var BABYLON;
  92959. (function (BABYLON) {
  92960. /**
  92961. * Unique ID when we import meshes from Babylon to CSG
  92962. */
  92963. var currentCSGMeshId = 0;
  92964. /**
  92965. * Represents a vertex of a polygon. Use your own vertex class instead of this
  92966. * one to provide additional features like texture coordinates and vertex
  92967. * colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  92968. * `flip()`, and `interpolate()` methods that behave analogous to the ones
  92969. * defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  92970. * functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  92971. * is not used anywhere else.
  92972. * Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  92973. */
  92974. var Vertex = /** @class */ (function () {
  92975. /**
  92976. * Initializes the vertex
  92977. * @param pos The position of the vertex
  92978. * @param normal The normal of the vertex
  92979. * @param uv The texture coordinate of the vertex
  92980. */
  92981. function Vertex(
  92982. /**
  92983. * The position of the vertex
  92984. */
  92985. pos,
  92986. /**
  92987. * The normal of the vertex
  92988. */
  92989. normal,
  92990. /**
  92991. * The texture coordinate of the vertex
  92992. */
  92993. uv) {
  92994. this.pos = pos;
  92995. this.normal = normal;
  92996. this.uv = uv;
  92997. }
  92998. /**
  92999. * Make a clone, or deep copy, of the vertex
  93000. * @returns A new Vertex
  93001. */
  93002. Vertex.prototype.clone = function () {
  93003. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  93004. };
  93005. /**
  93006. * Invert all orientation-specific data (e.g. vertex normal). Called when the
  93007. * orientation of a polygon is flipped.
  93008. */
  93009. Vertex.prototype.flip = function () {
  93010. this.normal = this.normal.scale(-1);
  93011. };
  93012. /**
  93013. * Create a new vertex between this vertex and `other` by linearly
  93014. * interpolating all properties using a parameter of `t`. Subclasses should
  93015. * override this to interpolate additional properties.
  93016. * @param other the vertex to interpolate against
  93017. * @param t The factor used to linearly interpolate between the vertices
  93018. */
  93019. Vertex.prototype.interpolate = function (other, t) {
  93020. 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));
  93021. };
  93022. return Vertex;
  93023. }());
  93024. /**
  93025. * Represents a plane in 3D space.
  93026. */
  93027. var Plane = /** @class */ (function () {
  93028. /**
  93029. * Initializes the plane
  93030. * @param normal The normal for the plane
  93031. * @param w
  93032. */
  93033. function Plane(normal, w) {
  93034. this.normal = normal;
  93035. this.w = w;
  93036. }
  93037. /**
  93038. * Construct a plane from three points
  93039. * @param a Point a
  93040. * @param b Point b
  93041. * @param c Point c
  93042. */
  93043. Plane.FromPoints = function (a, b, c) {
  93044. var v0 = c.subtract(a);
  93045. var v1 = b.subtract(a);
  93046. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  93047. return null;
  93048. }
  93049. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  93050. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  93051. };
  93052. /**
  93053. * Clone, or make a deep copy of the plane
  93054. * @returns a new Plane
  93055. */
  93056. Plane.prototype.clone = function () {
  93057. return new Plane(this.normal.clone(), this.w);
  93058. };
  93059. /**
  93060. * Flip the face of the plane
  93061. */
  93062. Plane.prototype.flip = function () {
  93063. this.normal.scaleInPlace(-1);
  93064. this.w = -this.w;
  93065. };
  93066. /**
  93067. * Split `polygon` by this plane if needed, then put the polygon or polygon
  93068. * fragments in the appropriate lists. Coplanar polygons go into either
  93069. `* coplanarFront` or `coplanarBack` depending on their orientation with
  93070. * respect to this plane. Polygons in front or in back of this plane go into
  93071. * either `front` or `back`
  93072. * @param polygon The polygon to be split
  93073. * @param coplanarFront Will contain polygons coplanar with the plane that are oriented to the front of the plane
  93074. * @param coplanarBack Will contain polygons coplanar with the plane that are oriented to the back of the plane
  93075. * @param front Will contain the polygons in front of the plane
  93076. * @param back Will contain the polygons begind the plane
  93077. */
  93078. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  93079. var COPLANAR = 0;
  93080. var FRONT = 1;
  93081. var BACK = 2;
  93082. var SPANNING = 3;
  93083. // Classify each point as well as the entire polygon into one of the above
  93084. // four classes.
  93085. var polygonType = 0;
  93086. var types = [];
  93087. var i;
  93088. var t;
  93089. for (i = 0; i < polygon.vertices.length; i++) {
  93090. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  93091. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  93092. polygonType |= type;
  93093. types.push(type);
  93094. }
  93095. // Put the polygon in the correct list, splitting it when necessary
  93096. switch (polygonType) {
  93097. case COPLANAR:
  93098. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  93099. break;
  93100. case FRONT:
  93101. front.push(polygon);
  93102. break;
  93103. case BACK:
  93104. back.push(polygon);
  93105. break;
  93106. case SPANNING:
  93107. var f = [], b = [];
  93108. for (i = 0; i < polygon.vertices.length; i++) {
  93109. var j = (i + 1) % polygon.vertices.length;
  93110. var ti = types[i], tj = types[j];
  93111. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  93112. if (ti !== BACK)
  93113. f.push(vi);
  93114. if (ti !== FRONT)
  93115. b.push(ti !== BACK ? vi.clone() : vi);
  93116. if ((ti | tj) === SPANNING) {
  93117. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  93118. var v = vi.interpolate(vj, t);
  93119. f.push(v);
  93120. b.push(v.clone());
  93121. }
  93122. }
  93123. var poly;
  93124. if (f.length >= 3) {
  93125. poly = new Polygon(f, polygon.shared);
  93126. if (poly.plane)
  93127. front.push(poly);
  93128. }
  93129. if (b.length >= 3) {
  93130. poly = new Polygon(b, polygon.shared);
  93131. if (poly.plane)
  93132. back.push(poly);
  93133. }
  93134. break;
  93135. }
  93136. };
  93137. /**
  93138. * `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  93139. * point is on the plane
  93140. */
  93141. Plane.EPSILON = 1e-5;
  93142. return Plane;
  93143. }());
  93144. /**
  93145. * Represents a convex polygon. The vertices used to initialize a polygon must
  93146. * be coplanar and form a convex loop.
  93147. *
  93148. * Each convex polygon has a `shared` property, which is shared between all
  93149. * polygons that are clones of each other or were split from the same polygon.
  93150. * This can be used to define per-polygon properties (such as surface color)
  93151. */
  93152. var Polygon = /** @class */ (function () {
  93153. /**
  93154. * Initializes the polygon
  93155. * @param vertices The vertices of the polygon
  93156. * @param shared The properties shared across all polygons
  93157. */
  93158. function Polygon(vertices, shared) {
  93159. this.vertices = vertices;
  93160. this.shared = shared;
  93161. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  93162. }
  93163. /**
  93164. * Clones, or makes a deep copy, or the polygon
  93165. */
  93166. Polygon.prototype.clone = function () {
  93167. var vertices = this.vertices.map(function (v) { return v.clone(); });
  93168. return new Polygon(vertices, this.shared);
  93169. };
  93170. /**
  93171. * Flips the faces of the polygon
  93172. */
  93173. Polygon.prototype.flip = function () {
  93174. this.vertices.reverse().map(function (v) { v.flip(); });
  93175. this.plane.flip();
  93176. };
  93177. return Polygon;
  93178. }());
  93179. /**
  93180. * Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  93181. * by picking a polygon to split along. That polygon (and all other coplanar
  93182. * polygons) are added directly to that node and the other polygons are added to
  93183. * the front and/or back subtrees. This is not a leafy BSP tree since there is
  93184. * no distinction between internal and leaf nodes
  93185. */
  93186. var Node = /** @class */ (function () {
  93187. /**
  93188. * Initializes the node
  93189. * @param polygons A collection of polygons held in the node
  93190. */
  93191. function Node(polygons) {
  93192. this.plane = null;
  93193. this.front = null;
  93194. this.back = null;
  93195. this.polygons = new Array();
  93196. if (polygons) {
  93197. this.build(polygons);
  93198. }
  93199. }
  93200. /**
  93201. * Clones, or makes a deep copy, of the node
  93202. * @returns The cloned node
  93203. */
  93204. Node.prototype.clone = function () {
  93205. var node = new Node();
  93206. node.plane = this.plane && this.plane.clone();
  93207. node.front = this.front && this.front.clone();
  93208. node.back = this.back && this.back.clone();
  93209. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  93210. return node;
  93211. };
  93212. /**
  93213. * Convert solid space to empty space and empty space to solid space
  93214. */
  93215. Node.prototype.invert = function () {
  93216. for (var i = 0; i < this.polygons.length; i++) {
  93217. this.polygons[i].flip();
  93218. }
  93219. if (this.plane) {
  93220. this.plane.flip();
  93221. }
  93222. if (this.front) {
  93223. this.front.invert();
  93224. }
  93225. if (this.back) {
  93226. this.back.invert();
  93227. }
  93228. var temp = this.front;
  93229. this.front = this.back;
  93230. this.back = temp;
  93231. };
  93232. /**
  93233. * Recursively remove all polygons in `polygons` that are inside this BSP
  93234. * tree.
  93235. * @param polygons Polygons to remove from the BSP
  93236. * @returns Polygons clipped from the BSP
  93237. */
  93238. Node.prototype.clipPolygons = function (polygons) {
  93239. if (!this.plane)
  93240. return polygons.slice();
  93241. var front = new Array(), back = new Array();
  93242. for (var i = 0; i < polygons.length; i++) {
  93243. this.plane.splitPolygon(polygons[i], front, back, front, back);
  93244. }
  93245. if (this.front) {
  93246. front = this.front.clipPolygons(front);
  93247. }
  93248. if (this.back) {
  93249. back = this.back.clipPolygons(back);
  93250. }
  93251. else {
  93252. back = [];
  93253. }
  93254. return front.concat(back);
  93255. };
  93256. /**
  93257. * Remove all polygons in this BSP tree that are inside the other BSP tree
  93258. * `bsp`.
  93259. * @param bsp BSP containing polygons to remove from this BSP
  93260. */
  93261. Node.prototype.clipTo = function (bsp) {
  93262. this.polygons = bsp.clipPolygons(this.polygons);
  93263. if (this.front)
  93264. this.front.clipTo(bsp);
  93265. if (this.back)
  93266. this.back.clipTo(bsp);
  93267. };
  93268. /**
  93269. * Return a list of all polygons in this BSP tree
  93270. * @returns List of all polygons in this BSP tree
  93271. */
  93272. Node.prototype.allPolygons = function () {
  93273. var polygons = this.polygons.slice();
  93274. if (this.front)
  93275. polygons = polygons.concat(this.front.allPolygons());
  93276. if (this.back)
  93277. polygons = polygons.concat(this.back.allPolygons());
  93278. return polygons;
  93279. };
  93280. /**
  93281. * Build a BSP tree out of `polygons`. When called on an existing tree, the
  93282. * new polygons are filtered down to the bottom of the tree and become new
  93283. * nodes there. Each set of polygons is partitioned using the first polygon
  93284. * (no heuristic is used to pick a good split)
  93285. * @param polygons Polygons used to construct the BSP tree
  93286. */
  93287. Node.prototype.build = function (polygons) {
  93288. if (!polygons.length)
  93289. return;
  93290. if (!this.plane)
  93291. this.plane = polygons[0].plane.clone();
  93292. var front = new Array(), back = new Array();
  93293. for (var i = 0; i < polygons.length; i++) {
  93294. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  93295. }
  93296. if (front.length) {
  93297. if (!this.front)
  93298. this.front = new Node();
  93299. this.front.build(front);
  93300. }
  93301. if (back.length) {
  93302. if (!this.back)
  93303. this.back = new Node();
  93304. this.back.build(back);
  93305. }
  93306. };
  93307. return Node;
  93308. }());
  93309. /**
  93310. * Class for building Constructive Solid Geometry
  93311. */
  93312. var CSG = /** @class */ (function () {
  93313. function CSG() {
  93314. this.polygons = new Array();
  93315. }
  93316. /**
  93317. * Convert the BABYLON.Mesh to BABYLON.CSG
  93318. * @param mesh The BABYLON.Mesh to convert to BABYLON.CSG
  93319. * @returns A new BABYLON.CSG from the BABYLON.Mesh
  93320. */
  93321. CSG.FromMesh = function (mesh) {
  93322. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  93323. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  93324. if (mesh instanceof BABYLON.Mesh) {
  93325. mesh.computeWorldMatrix(true);
  93326. matrix = mesh.getWorldMatrix();
  93327. meshPosition = mesh.position.clone();
  93328. meshRotation = mesh.rotation.clone();
  93329. if (mesh.rotationQuaternion) {
  93330. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  93331. }
  93332. meshScaling = mesh.scaling.clone();
  93333. }
  93334. else {
  93335. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  93336. }
  93337. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  93338. var subMeshes = mesh.subMeshes;
  93339. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  93340. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  93341. vertices = [];
  93342. for (var j = 0; j < 3; j++) {
  93343. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  93344. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  93345. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  93346. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  93347. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  93348. vertex = new Vertex(position, normal, uv);
  93349. vertices.push(vertex);
  93350. }
  93351. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  93352. // To handle the case of degenerated triangle
  93353. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  93354. if (polygon.plane)
  93355. polygons.push(polygon);
  93356. }
  93357. }
  93358. var csg = CSG.FromPolygons(polygons);
  93359. csg.matrix = matrix;
  93360. csg.position = meshPosition;
  93361. csg.rotation = meshRotation;
  93362. csg.scaling = meshScaling;
  93363. csg.rotationQuaternion = meshRotationQuaternion;
  93364. currentCSGMeshId++;
  93365. return csg;
  93366. };
  93367. /**
  93368. * Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  93369. * @param polygons Polygons used to construct a BABYLON.CSG solid
  93370. */
  93371. CSG.FromPolygons = function (polygons) {
  93372. var csg = new CSG();
  93373. csg.polygons = polygons;
  93374. return csg;
  93375. };
  93376. /**
  93377. * Clones, or makes a deep copy, of the BABYLON.CSG
  93378. * @returns A new BABYLON.CSG
  93379. */
  93380. CSG.prototype.clone = function () {
  93381. var csg = new CSG();
  93382. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  93383. csg.copyTransformAttributes(this);
  93384. return csg;
  93385. };
  93386. /**
  93387. * Unions this CSG with another CSG
  93388. * @param csg The CSG to union against this CSG
  93389. * @returns The unioned CSG
  93390. */
  93391. CSG.prototype.union = function (csg) {
  93392. var a = new Node(this.clone().polygons);
  93393. var b = new Node(csg.clone().polygons);
  93394. a.clipTo(b);
  93395. b.clipTo(a);
  93396. b.invert();
  93397. b.clipTo(a);
  93398. b.invert();
  93399. a.build(b.allPolygons());
  93400. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  93401. };
  93402. /**
  93403. * Unions this CSG with another CSG in place
  93404. * @param csg The CSG to union against this CSG
  93405. */
  93406. CSG.prototype.unionInPlace = function (csg) {
  93407. var a = new Node(this.polygons);
  93408. var b = new Node(csg.polygons);
  93409. a.clipTo(b);
  93410. b.clipTo(a);
  93411. b.invert();
  93412. b.clipTo(a);
  93413. b.invert();
  93414. a.build(b.allPolygons());
  93415. this.polygons = a.allPolygons();
  93416. };
  93417. /**
  93418. * Subtracts this CSG with another CSG
  93419. * @param csg The CSG to subtract against this CSG
  93420. * @returns A new BABYLON.CSG
  93421. */
  93422. CSG.prototype.subtract = function (csg) {
  93423. var a = new Node(this.clone().polygons);
  93424. var b = new Node(csg.clone().polygons);
  93425. a.invert();
  93426. a.clipTo(b);
  93427. b.clipTo(a);
  93428. b.invert();
  93429. b.clipTo(a);
  93430. b.invert();
  93431. a.build(b.allPolygons());
  93432. a.invert();
  93433. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  93434. };
  93435. /**
  93436. * Subtracts this CSG with another CSG in place
  93437. * @param csg The CSG to subtact against this CSG
  93438. */
  93439. CSG.prototype.subtractInPlace = function (csg) {
  93440. var a = new Node(this.polygons);
  93441. var b = new Node(csg.polygons);
  93442. a.invert();
  93443. a.clipTo(b);
  93444. b.clipTo(a);
  93445. b.invert();
  93446. b.clipTo(a);
  93447. b.invert();
  93448. a.build(b.allPolygons());
  93449. a.invert();
  93450. this.polygons = a.allPolygons();
  93451. };
  93452. /**
  93453. * Intersect this CSG with another CSG
  93454. * @param csg The CSG to intersect against this CSG
  93455. * @returns A new BABYLON.CSG
  93456. */
  93457. CSG.prototype.intersect = function (csg) {
  93458. var a = new Node(this.clone().polygons);
  93459. var b = new Node(csg.clone().polygons);
  93460. a.invert();
  93461. b.clipTo(a);
  93462. b.invert();
  93463. a.clipTo(b);
  93464. b.clipTo(a);
  93465. a.build(b.allPolygons());
  93466. a.invert();
  93467. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  93468. };
  93469. /**
  93470. * Intersects this CSG with another CSG in place
  93471. * @param csg The CSG to intersect against this CSG
  93472. */
  93473. CSG.prototype.intersectInPlace = function (csg) {
  93474. var a = new Node(this.polygons);
  93475. var b = new Node(csg.polygons);
  93476. a.invert();
  93477. b.clipTo(a);
  93478. b.invert();
  93479. a.clipTo(b);
  93480. b.clipTo(a);
  93481. a.build(b.allPolygons());
  93482. a.invert();
  93483. this.polygons = a.allPolygons();
  93484. };
  93485. /**
  93486. * Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  93487. * not modified.
  93488. * @returns A new BABYLON.CSG solid with solid and empty space switched
  93489. */
  93490. CSG.prototype.inverse = function () {
  93491. var csg = this.clone();
  93492. csg.inverseInPlace();
  93493. return csg;
  93494. };
  93495. /**
  93496. * Inverses the BABYLON.CSG in place
  93497. */
  93498. CSG.prototype.inverseInPlace = function () {
  93499. this.polygons.map(function (p) { p.flip(); });
  93500. };
  93501. /**
  93502. * This is used to keep meshes transformations so they can be restored
  93503. * when we build back a Babylon Mesh
  93504. * NB : All CSG operations are performed in world coordinates
  93505. * @param csg The BABYLON.CSG to copy the transform attributes from
  93506. * @returns This BABYLON.CSG
  93507. */
  93508. CSG.prototype.copyTransformAttributes = function (csg) {
  93509. this.matrix = csg.matrix;
  93510. this.position = csg.position;
  93511. this.rotation = csg.rotation;
  93512. this.scaling = csg.scaling;
  93513. this.rotationQuaternion = csg.rotationQuaternion;
  93514. return this;
  93515. };
  93516. /**
  93517. * Build Raw mesh from CSG
  93518. * Coordinates here are in world space
  93519. * @param name The name of the mesh geometry
  93520. * @param scene The BABYLON.Scene
  93521. * @param keepSubMeshes Specifies if the submeshes should be kept
  93522. * @returns A new BABYLON.Mesh
  93523. */
  93524. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  93525. var matrix = this.matrix.clone();
  93526. matrix.invert();
  93527. 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;
  93528. if (keepSubMeshes) {
  93529. // Sort Polygons, since subMeshes are indices range
  93530. polygons.sort(function (a, b) {
  93531. if (a.shared.meshId === b.shared.meshId) {
  93532. return a.shared.subMeshId - b.shared.subMeshId;
  93533. }
  93534. else {
  93535. return a.shared.meshId - b.shared.meshId;
  93536. }
  93537. });
  93538. }
  93539. for (var i = 0, il = polygons.length; i < il; i++) {
  93540. polygon = polygons[i];
  93541. // Building SubMeshes
  93542. if (!subMesh_dict[polygon.shared.meshId]) {
  93543. subMesh_dict[polygon.shared.meshId] = {};
  93544. }
  93545. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  93546. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  93547. indexStart: +Infinity,
  93548. indexEnd: -Infinity,
  93549. materialIndex: polygon.shared.materialIndex
  93550. };
  93551. }
  93552. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  93553. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  93554. polygonIndices[0] = 0;
  93555. polygonIndices[1] = j - 1;
  93556. polygonIndices[2] = j;
  93557. for (var k = 0; k < 3; k++) {
  93558. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  93559. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  93560. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  93561. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  93562. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  93563. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  93564. // Check if 2 points can be merged
  93565. if (!(typeof vertex_idx !== 'undefined' &&
  93566. normals[vertex_idx * 3] === localNormal.x &&
  93567. normals[vertex_idx * 3 + 1] === localNormal.y &&
  93568. normals[vertex_idx * 3 + 2] === localNormal.z &&
  93569. uvs[vertex_idx * 2] === uv.x &&
  93570. uvs[vertex_idx * 2 + 1] === uv.y)) {
  93571. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  93572. uvs.push(uv.x, uv.y);
  93573. normals.push(normal.x, normal.y, normal.z);
  93574. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  93575. }
  93576. indices.push(vertex_idx);
  93577. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  93578. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  93579. currentIndex++;
  93580. }
  93581. }
  93582. }
  93583. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  93584. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  93585. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  93586. mesh.setIndices(indices, null);
  93587. if (keepSubMeshes) {
  93588. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  93589. var materialIndexOffset = 0, materialMaxIndex;
  93590. mesh.subMeshes = new Array();
  93591. for (var m in subMesh_dict) {
  93592. materialMaxIndex = -1;
  93593. for (var sm in subMesh_dict[m]) {
  93594. subMesh_obj = subMesh_dict[m][sm];
  93595. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  93596. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  93597. }
  93598. materialIndexOffset += ++materialMaxIndex;
  93599. }
  93600. }
  93601. return mesh;
  93602. };
  93603. /**
  93604. * Build Mesh from CSG taking material and transforms into account
  93605. * @param name The name of the BABYLON.Mesh
  93606. * @param material The material of the BABYLON.Mesh
  93607. * @param scene The BABYLON.Scene
  93608. * @param keepSubMeshes Specifies if submeshes should be kept
  93609. * @returns The new BABYLON.Mesh
  93610. */
  93611. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  93612. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  93613. mesh.material = material;
  93614. mesh.position.copyFrom(this.position);
  93615. mesh.rotation.copyFrom(this.rotation);
  93616. if (this.rotationQuaternion) {
  93617. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  93618. }
  93619. mesh.scaling.copyFrom(this.scaling);
  93620. mesh.computeWorldMatrix(true);
  93621. return mesh;
  93622. };
  93623. return CSG;
  93624. }());
  93625. BABYLON.CSG = CSG;
  93626. })(BABYLON || (BABYLON = {}));
  93627. //# sourceMappingURL=babylon.csg.js.map
  93628. var BABYLON;
  93629. (function (BABYLON) {
  93630. /**
  93631. * This represents one of the lens effect in a `BABYLON.lensFlareSystem`.
  93632. * It controls one of the indiviual texture used in the effect.
  93633. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  93634. */
  93635. var LensFlare = /** @class */ (function () {
  93636. /**
  93637. * Instantiates a new Lens Flare.
  93638. * This represents one of the lens effect in a `BABYLON.lensFlareSystem`.
  93639. * It controls one of the indiviual texture used in the effect.
  93640. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  93641. * @param size Define the size of the lens flare in the system (a floating value between 0 and 1)
  93642. * @param position Define the position of the lens flare in the system. (a floating value between -1 and 1). A value of 0 is located on the emitter. A value greater than 0 is beyond the emitter and a value lesser than 0 is behind.
  93643. * @param color Define the lens color
  93644. * @param imgUrl Define the lens texture url
  93645. * @param system Define the `lensFlareSystem` this flare is part of
  93646. */
  93647. function LensFlare(
  93648. /**
  93649. * Define the size of the lens flare in the system (a floating value between 0 and 1)
  93650. */
  93651. size,
  93652. /**
  93653. * Define the position of the lens flare in the system. (a floating value between -1 and 1). A value of 0 is located on the emitter. A value greater than 0 is beyond the emitter and a value lesser than 0 is behind.
  93654. */
  93655. position, color, imgUrl, system) {
  93656. this.size = size;
  93657. this.position = position;
  93658. /**
  93659. * Define the alpha mode to render this particular lens.
  93660. */
  93661. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  93662. this.color = color || new BABYLON.Color3(1, 1, 1);
  93663. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  93664. this._system = system;
  93665. system.lensFlares.push(this);
  93666. }
  93667. /**
  93668. * Creates a new Lens Flare.
  93669. * This represents one of the lens effect in a `BABYLON.lensFlareSystem`.
  93670. * It controls one of the indiviual texture used in the effect.
  93671. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  93672. * @param size Define the size of the lens flare (a floating value between 0 and 1)
  93673. * @param position Define the position of the lens flare in the system. (a floating value between -1 and 1). A value of 0 is located on the emitter. A value greater than 0 is beyond the emitter and a value lesser than 0 is behind.
  93674. * @param color Define the lens color
  93675. * @param imgUrl Define the lens texture url
  93676. * @param system Define the `lensFlareSystem` this flare is part of
  93677. * @returns The newly created Lens Flare
  93678. */
  93679. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  93680. return new LensFlare(size, position, color, imgUrl, system);
  93681. };
  93682. /**
  93683. * Dispose and release the lens flare with its associated resources.
  93684. */
  93685. LensFlare.prototype.dispose = function () {
  93686. if (this.texture) {
  93687. this.texture.dispose();
  93688. }
  93689. // Remove from scene
  93690. var index = this._system.lensFlares.indexOf(this);
  93691. this._system.lensFlares.splice(index, 1);
  93692. };
  93693. ;
  93694. return LensFlare;
  93695. }());
  93696. BABYLON.LensFlare = LensFlare;
  93697. })(BABYLON || (BABYLON = {}));
  93698. //# sourceMappingURL=babylon.lensFlare.js.map
  93699. var BABYLON;
  93700. (function (BABYLON) {
  93701. // Adds the parser to the scene parsers.
  93702. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM, function (parsedData, scene, container, rootUrl) {
  93703. // Lens flares
  93704. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  93705. if (!container.lensFlareSystems) {
  93706. container.lensFlareSystems = new Array();
  93707. }
  93708. for (var index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  93709. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  93710. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  93711. container.lensFlareSystems.push(lf);
  93712. }
  93713. }
  93714. });
  93715. BABYLON.AbstractScene.prototype.getLensFlareSystemByName = function (name) {
  93716. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  93717. if (this.lensFlareSystems[index].name === name) {
  93718. return this.lensFlareSystems[index];
  93719. }
  93720. }
  93721. return null;
  93722. };
  93723. BABYLON.AbstractScene.prototype.getLensFlareSystemByID = function (id) {
  93724. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  93725. if (this.lensFlareSystems[index].id === id) {
  93726. return this.lensFlareSystems[index];
  93727. }
  93728. }
  93729. return null;
  93730. };
  93731. BABYLON.AbstractScene.prototype.removeLensFlareSystem = function (toRemove) {
  93732. var index = this.lensFlareSystems.indexOf(toRemove);
  93733. if (index !== -1) {
  93734. this.lensFlareSystems.splice(index, 1);
  93735. }
  93736. return index;
  93737. };
  93738. BABYLON.AbstractScene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  93739. this.lensFlareSystems.push(newLensFlareSystem);
  93740. };
  93741. /**
  93742. * Defines the lens flare scene component responsible to manage any lens flares
  93743. * in a given scene.
  93744. */
  93745. var LensFlareSystemSceneComponent = /** @class */ (function () {
  93746. /**
  93747. * Creates a new instance of the component for the given scene
  93748. * @param scene Defines the scene to register the component in
  93749. */
  93750. function LensFlareSystemSceneComponent(scene) {
  93751. /**
  93752. * The component name helpfull to identify the component in the list of scene components.
  93753. */
  93754. this.name = BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM;
  93755. this.scene = scene;
  93756. scene.lensFlareSystems = new Array();
  93757. }
  93758. /**
  93759. * Registers the component in a given scene
  93760. */
  93761. LensFlareSystemSceneComponent.prototype.register = function () {
  93762. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM, this, this._draw);
  93763. };
  93764. /**
  93765. * Rebuilds the elements related to this component in case of
  93766. * context lost for instance.
  93767. */
  93768. LensFlareSystemSceneComponent.prototype.rebuild = function () {
  93769. // Nothing to do for lens flare
  93770. };
  93771. /**
  93772. * Adds all the element from the container to the scene
  93773. * @param container the container holding the elements
  93774. */
  93775. LensFlareSystemSceneComponent.prototype.addFromContainer = function (container) {
  93776. var _this = this;
  93777. if (!container.lensFlareSystems) {
  93778. return;
  93779. }
  93780. container.lensFlareSystems.forEach(function (o) {
  93781. _this.scene.addLensFlareSystem(o);
  93782. });
  93783. };
  93784. /**
  93785. * Removes all the elements in the container from the scene
  93786. * @param container contains the elements to remove
  93787. */
  93788. LensFlareSystemSceneComponent.prototype.removeFromContainer = function (container) {
  93789. var _this = this;
  93790. if (!container.lensFlareSystems) {
  93791. return;
  93792. }
  93793. container.lensFlareSystems.forEach(function (o) {
  93794. _this.scene.removeLensFlareSystem(o);
  93795. });
  93796. };
  93797. /**
  93798. * Serializes the component data to the specified json object
  93799. * @param serializationObject The object to serialize to
  93800. */
  93801. LensFlareSystemSceneComponent.prototype.serialize = function (serializationObject) {
  93802. // Lens flares
  93803. serializationObject.lensFlareSystems = [];
  93804. var lensFlareSystems = this.scene.lensFlareSystems;
  93805. for (var _i = 0, lensFlareSystems_1 = lensFlareSystems; _i < lensFlareSystems_1.length; _i++) {
  93806. var lensFlareSystem = lensFlareSystems_1[_i];
  93807. serializationObject.lensFlareSystems.push(lensFlareSystem.serialize());
  93808. }
  93809. };
  93810. /**
  93811. * Disposes the component and the associated ressources.
  93812. */
  93813. LensFlareSystemSceneComponent.prototype.dispose = function () {
  93814. var lensFlareSystems = this.scene.lensFlareSystems;
  93815. while (lensFlareSystems.length) {
  93816. lensFlareSystems[0].dispose();
  93817. }
  93818. };
  93819. LensFlareSystemSceneComponent.prototype._draw = function (camera) {
  93820. // Lens flares
  93821. if (this.scene.lensFlaresEnabled) {
  93822. var lensFlareSystems = this.scene.lensFlareSystems;
  93823. BABYLON.Tools.StartPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  93824. for (var _i = 0, lensFlareSystems_2 = lensFlareSystems; _i < lensFlareSystems_2.length; _i++) {
  93825. var lensFlareSystem = lensFlareSystems_2[_i];
  93826. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  93827. lensFlareSystem.render();
  93828. }
  93829. }
  93830. BABYLON.Tools.EndPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  93831. }
  93832. };
  93833. return LensFlareSystemSceneComponent;
  93834. }());
  93835. BABYLON.LensFlareSystemSceneComponent = LensFlareSystemSceneComponent;
  93836. })(BABYLON || (BABYLON = {}));
  93837. //# sourceMappingURL=babylon.lensFlareSystemSceneComponent.js.map
  93838. var BABYLON;
  93839. (function (BABYLON) {
  93840. /**
  93841. * This represents a Lens Flare System or the shiny effect created by the light reflection on the camera lenses.
  93842. * It is usually composed of several `BABYLON.lensFlare`.
  93843. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  93844. */
  93845. var LensFlareSystem = /** @class */ (function () {
  93846. /**
  93847. * Instantiates a lens flare system.
  93848. * This represents a Lens Flare System or the shiny effect created by the light reflection on the camera lenses.
  93849. * It is usually composed of several `BABYLON.lensFlare`.
  93850. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  93851. * @param name Define the name of the lens flare system in the scene
  93852. * @param emitter Define the source (the emitter) of the lens flares (it can be a camera, a light or a mesh).
  93853. * @param scene Define the scene the lens flare system belongs to
  93854. */
  93855. function LensFlareSystem(
  93856. /**
  93857. * Define the name of the lens flare system
  93858. */
  93859. name, emitter, scene) {
  93860. this.name = name;
  93861. /**
  93862. * List of lens flares used in this system.
  93863. */
  93864. this.lensFlares = new Array();
  93865. /**
  93866. * Define a limit from the border the lens flare can be visible.
  93867. */
  93868. this.borderLimit = 300;
  93869. /**
  93870. * Define a viewport border we do not want to see the lens flare in.
  93871. */
  93872. this.viewportBorder = 0;
  93873. /**
  93874. * Restricts the rendering of the effect to only the camera rendering this layer mask.
  93875. */
  93876. this.layerMask = 0x0FFFFFFF;
  93877. this._vertexBuffers = {};
  93878. this._isEnabled = true;
  93879. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  93880. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM);
  93881. if (!component) {
  93882. component = new BABYLON.LensFlareSystemSceneComponent(this._scene);
  93883. scene._addComponent(component);
  93884. }
  93885. this._emitter = emitter;
  93886. this.id = name;
  93887. scene.lensFlareSystems.push(this);
  93888. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  93889. var engine = scene.getEngine();
  93890. // VBO
  93891. var vertices = [];
  93892. vertices.push(1, 1);
  93893. vertices.push(-1, 1);
  93894. vertices.push(-1, -1);
  93895. vertices.push(1, -1);
  93896. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  93897. // Indices
  93898. var indices = [];
  93899. indices.push(0);
  93900. indices.push(1);
  93901. indices.push(2);
  93902. indices.push(0);
  93903. indices.push(2);
  93904. indices.push(3);
  93905. this._indexBuffer = engine.createIndexBuffer(indices);
  93906. // Effects
  93907. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  93908. }
  93909. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  93910. /**
  93911. * Define if the lens flare system is enabled.
  93912. */
  93913. get: function () {
  93914. return this._isEnabled;
  93915. },
  93916. set: function (value) {
  93917. this._isEnabled = value;
  93918. },
  93919. enumerable: true,
  93920. configurable: true
  93921. });
  93922. /**
  93923. * Get the scene the effects belongs to.
  93924. * @returns the scene holding the lens flare system
  93925. */
  93926. LensFlareSystem.prototype.getScene = function () {
  93927. return this._scene;
  93928. };
  93929. /**
  93930. * Get the emitter of the lens flare system.
  93931. * It defines the source of the lens flares (it can be a camera, a light or a mesh).
  93932. * @returns the emitter of the lens flare system
  93933. */
  93934. LensFlareSystem.prototype.getEmitter = function () {
  93935. return this._emitter;
  93936. };
  93937. /**
  93938. * Set the emitter of the lens flare system.
  93939. * It defines the source of the lens flares (it can be a camera, a light or a mesh).
  93940. * @param newEmitter Define the new emitter of the system
  93941. */
  93942. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  93943. this._emitter = newEmitter;
  93944. };
  93945. /**
  93946. * Get the lens flare system emitter position.
  93947. * The emitter defines the source of the lens flares (it can be a camera, a light or a mesh).
  93948. * @returns the position
  93949. */
  93950. LensFlareSystem.prototype.getEmitterPosition = function () {
  93951. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  93952. };
  93953. /**
  93954. * @hidden
  93955. */
  93956. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  93957. var position = this.getEmitterPosition();
  93958. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  93959. this._positionX = position.x;
  93960. this._positionY = position.y;
  93961. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  93962. if (this.viewportBorder > 0) {
  93963. globalViewport.x -= this.viewportBorder;
  93964. globalViewport.y -= this.viewportBorder;
  93965. globalViewport.width += this.viewportBorder * 2;
  93966. globalViewport.height += this.viewportBorder * 2;
  93967. position.x += this.viewportBorder;
  93968. position.y += this.viewportBorder;
  93969. this._positionX += this.viewportBorder;
  93970. this._positionY += this.viewportBorder;
  93971. }
  93972. if (position.z > 0) {
  93973. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  93974. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  93975. return true;
  93976. }
  93977. return true;
  93978. }
  93979. return false;
  93980. };
  93981. /** @hidden */
  93982. LensFlareSystem.prototype._isVisible = function () {
  93983. if (!this._isEnabled || !this._scene.activeCamera) {
  93984. return false;
  93985. }
  93986. var emitterPosition = this.getEmitterPosition();
  93987. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  93988. var distance = direction.length();
  93989. direction.normalize();
  93990. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  93991. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  93992. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  93993. };
  93994. /**
  93995. * @hidden
  93996. */
  93997. LensFlareSystem.prototype.render = function () {
  93998. if (!this._effect.isReady() || !this._scene.activeCamera)
  93999. return false;
  94000. var engine = this._scene.getEngine();
  94001. var viewport = this._scene.activeCamera.viewport;
  94002. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  94003. // Position
  94004. if (!this.computeEffectivePosition(globalViewport)) {
  94005. return false;
  94006. }
  94007. // Visibility
  94008. if (!this._isVisible()) {
  94009. return false;
  94010. }
  94011. // Intensity
  94012. var awayX;
  94013. var awayY;
  94014. if (this._positionX < this.borderLimit + globalViewport.x) {
  94015. awayX = this.borderLimit + globalViewport.x - this._positionX;
  94016. }
  94017. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  94018. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  94019. }
  94020. else {
  94021. awayX = 0;
  94022. }
  94023. if (this._positionY < this.borderLimit + globalViewport.y) {
  94024. awayY = this.borderLimit + globalViewport.y - this._positionY;
  94025. }
  94026. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  94027. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  94028. }
  94029. else {
  94030. awayY = 0;
  94031. }
  94032. var away = (awayX > awayY) ? awayX : awayY;
  94033. away -= this.viewportBorder;
  94034. if (away > this.borderLimit) {
  94035. away = this.borderLimit;
  94036. }
  94037. var intensity = 1.0 - (away / this.borderLimit);
  94038. if (intensity < 0) {
  94039. return false;
  94040. }
  94041. if (intensity > 1.0) {
  94042. intensity = 1.0;
  94043. }
  94044. if (this.viewportBorder > 0) {
  94045. globalViewport.x += this.viewportBorder;
  94046. globalViewport.y += this.viewportBorder;
  94047. globalViewport.width -= this.viewportBorder * 2;
  94048. globalViewport.height -= this.viewportBorder * 2;
  94049. this._positionX -= this.viewportBorder;
  94050. this._positionY -= this.viewportBorder;
  94051. }
  94052. // Position
  94053. var centerX = globalViewport.x + globalViewport.width / 2;
  94054. var centerY = globalViewport.y + globalViewport.height / 2;
  94055. var distX = centerX - this._positionX;
  94056. var distY = centerY - this._positionY;
  94057. // Effects
  94058. engine.enableEffect(this._effect);
  94059. engine.setState(false);
  94060. engine.setDepthBuffer(false);
  94061. // VBOs
  94062. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  94063. // Flares
  94064. for (var index = 0; index < this.lensFlares.length; index++) {
  94065. var flare = this.lensFlares[index];
  94066. engine.setAlphaMode(flare.alphaMode);
  94067. var x = centerX - (distX * flare.position);
  94068. var y = centerY - (distY * flare.position);
  94069. var cw = flare.size;
  94070. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  94071. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  94072. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  94073. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  94074. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  94075. // Texture
  94076. this._effect.setTexture("textureSampler", flare.texture);
  94077. // Color
  94078. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  94079. // Draw order
  94080. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  94081. }
  94082. engine.setDepthBuffer(true);
  94083. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  94084. return true;
  94085. };
  94086. /**
  94087. * Dispose and release the lens flare with its associated resources.
  94088. */
  94089. LensFlareSystem.prototype.dispose = function () {
  94090. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  94091. if (vertexBuffer) {
  94092. vertexBuffer.dispose();
  94093. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  94094. }
  94095. if (this._indexBuffer) {
  94096. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  94097. this._indexBuffer = null;
  94098. }
  94099. while (this.lensFlares.length) {
  94100. this.lensFlares[0].dispose();
  94101. }
  94102. // Remove from scene
  94103. var index = this._scene.lensFlareSystems.indexOf(this);
  94104. this._scene.lensFlareSystems.splice(index, 1);
  94105. };
  94106. /**
  94107. * Parse a lens flare system from a JSON repressentation
  94108. * @param parsedLensFlareSystem Define the JSON to parse
  94109. * @param scene Define the scene the parsed system should be instantiated in
  94110. * @param rootUrl Define the rootUrl of the load sequence to easily find a load relative dependencies such as textures
  94111. * @returns the parsed system
  94112. */
  94113. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  94114. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  94115. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  94116. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  94117. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  94118. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  94119. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  94120. var parsedFlare = parsedLensFlareSystem.flares[index];
  94121. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  94122. }
  94123. return lensFlareSystem;
  94124. };
  94125. /**
  94126. * Serialize the current Lens Flare System into a JSON representation.
  94127. * @returns the serialized JSON
  94128. */
  94129. LensFlareSystem.prototype.serialize = function () {
  94130. var serializationObject = {};
  94131. serializationObject.id = this.id;
  94132. serializationObject.name = this.name;
  94133. serializationObject.emitterId = this.getEmitter().id;
  94134. serializationObject.borderLimit = this.borderLimit;
  94135. serializationObject.flares = [];
  94136. for (var index = 0; index < this.lensFlares.length; index++) {
  94137. var flare = this.lensFlares[index];
  94138. serializationObject.flares.push({
  94139. size: flare.size,
  94140. position: flare.position,
  94141. color: flare.color.asArray(),
  94142. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  94143. });
  94144. }
  94145. return serializationObject;
  94146. };
  94147. return LensFlareSystem;
  94148. }());
  94149. BABYLON.LensFlareSystem = LensFlareSystem;
  94150. })(BABYLON || (BABYLON = {}));
  94151. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  94152. var BABYLON;
  94153. (function (BABYLON) {
  94154. /**
  94155. * This is a holder class for the physics joint created by the physics plugin
  94156. * It holds a set of functions to control the underlying joint
  94157. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  94158. */
  94159. var PhysicsJoint = /** @class */ (function () {
  94160. /**
  94161. * Initializes the physics joint
  94162. * @param type The type of the physics joint
  94163. * @param jointData The data for the physics joint
  94164. */
  94165. function PhysicsJoint(
  94166. /**
  94167. * The type of the physics joint
  94168. */
  94169. type,
  94170. /**
  94171. * The data for the physics joint
  94172. */
  94173. jointData) {
  94174. this.type = type;
  94175. this.jointData = jointData;
  94176. jointData.nativeParams = jointData.nativeParams || {};
  94177. }
  94178. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  94179. /**
  94180. * Gets the physics joint
  94181. */
  94182. get: function () {
  94183. return this._physicsJoint;
  94184. },
  94185. /**
  94186. * Sets the physics joint
  94187. */
  94188. set: function (newJoint) {
  94189. if (this._physicsJoint) {
  94190. //remove from the wolrd
  94191. }
  94192. this._physicsJoint = newJoint;
  94193. },
  94194. enumerable: true,
  94195. configurable: true
  94196. });
  94197. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  94198. /**
  94199. * Sets the physics plugin
  94200. */
  94201. set: function (physicsPlugin) {
  94202. this._physicsPlugin = physicsPlugin;
  94203. },
  94204. enumerable: true,
  94205. configurable: true
  94206. });
  94207. /**
  94208. * Execute a function that is physics-plugin specific.
  94209. * @param {Function} func the function that will be executed.
  94210. * It accepts two parameters: the physics world and the physics joint
  94211. */
  94212. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  94213. func(this._physicsPlugin.world, this._physicsJoint);
  94214. };
  94215. //TODO check if the native joints are the same
  94216. //Joint Types
  94217. /**
  94218. * Distance-Joint type
  94219. */
  94220. PhysicsJoint.DistanceJoint = 0;
  94221. /**
  94222. * Hinge-Joint type
  94223. */
  94224. PhysicsJoint.HingeJoint = 1;
  94225. /**
  94226. * Ball-and-Socket joint type
  94227. */
  94228. PhysicsJoint.BallAndSocketJoint = 2;
  94229. /**
  94230. * Wheel-Joint type
  94231. */
  94232. PhysicsJoint.WheelJoint = 3;
  94233. /**
  94234. * Slider-Joint type
  94235. */
  94236. PhysicsJoint.SliderJoint = 4;
  94237. //OIMO
  94238. /**
  94239. * Prismatic-Joint type
  94240. */
  94241. PhysicsJoint.PrismaticJoint = 5;
  94242. //
  94243. /**
  94244. * Universal-Joint type
  94245. * ENERGY FTW! (compare with this - @see http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  94246. */
  94247. PhysicsJoint.UniversalJoint = 6;
  94248. /**
  94249. * Hinge-Joint 2 type
  94250. */
  94251. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  94252. //Cannon
  94253. /**
  94254. * Point to Point Joint type. Similar to a Ball-Joint. Different in parameters
  94255. */
  94256. PhysicsJoint.PointToPointJoint = 8;
  94257. //Cannon only at the moment
  94258. /**
  94259. * Spring-Joint type
  94260. */
  94261. PhysicsJoint.SpringJoint = 9;
  94262. /**
  94263. * Lock-Joint type
  94264. */
  94265. PhysicsJoint.LockJoint = 10;
  94266. return PhysicsJoint;
  94267. }());
  94268. BABYLON.PhysicsJoint = PhysicsJoint;
  94269. /**
  94270. * A class representing a physics distance joint
  94271. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  94272. */
  94273. var DistanceJoint = /** @class */ (function (_super) {
  94274. __extends(DistanceJoint, _super);
  94275. /**
  94276. *
  94277. * @param jointData The data for the Distance-Joint
  94278. */
  94279. function DistanceJoint(jointData) {
  94280. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  94281. }
  94282. /**
  94283. * Update the predefined distance.
  94284. * @param maxDistance The maximum preferred distance
  94285. * @param minDistance The minimum preferred distance
  94286. */
  94287. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  94288. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  94289. };
  94290. return DistanceJoint;
  94291. }(PhysicsJoint));
  94292. BABYLON.DistanceJoint = DistanceJoint;
  94293. /**
  94294. * Represents a Motor-Enabled Joint
  94295. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  94296. */
  94297. var MotorEnabledJoint = /** @class */ (function (_super) {
  94298. __extends(MotorEnabledJoint, _super);
  94299. /**
  94300. * Initializes the Motor-Enabled Joint
  94301. * @param type The type of the joint
  94302. * @param jointData The physica joint data for the joint
  94303. */
  94304. function MotorEnabledJoint(type, jointData) {
  94305. return _super.call(this, type, jointData) || this;
  94306. }
  94307. /**
  94308. * Set the motor values.
  94309. * Attention, this function is plugin specific. Engines won't react 100% the same.
  94310. * @param force the force to apply
  94311. * @param maxForce max force for this motor.
  94312. */
  94313. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  94314. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  94315. };
  94316. /**
  94317. * Set the motor's limits.
  94318. * Attention, this function is plugin specific. Engines won't react 100% the same.
  94319. * @param upperLimit The upper limit of the motor
  94320. * @param lowerLimit The lower limit of the motor
  94321. */
  94322. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  94323. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  94324. };
  94325. return MotorEnabledJoint;
  94326. }(PhysicsJoint));
  94327. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  94328. /**
  94329. * This class represents a single physics Hinge-Joint
  94330. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  94331. */
  94332. var HingeJoint = /** @class */ (function (_super) {
  94333. __extends(HingeJoint, _super);
  94334. /**
  94335. * Initializes the Hinge-Joint
  94336. * @param jointData The joint data for the Hinge-Joint
  94337. */
  94338. function HingeJoint(jointData) {
  94339. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  94340. }
  94341. /**
  94342. * Set the motor values.
  94343. * Attention, this function is plugin specific. Engines won't react 100% the same.
  94344. * @param {number} force the force to apply
  94345. * @param {number} maxForce max force for this motor.
  94346. */
  94347. HingeJoint.prototype.setMotor = function (force, maxForce) {
  94348. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  94349. };
  94350. /**
  94351. * Set the motor's limits.
  94352. * Attention, this function is plugin specific. Engines won't react 100% the same.
  94353. * @param upperLimit The upper limit of the motor
  94354. * @param lowerLimit The lower limit of the motor
  94355. */
  94356. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  94357. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  94358. };
  94359. return HingeJoint;
  94360. }(MotorEnabledJoint));
  94361. BABYLON.HingeJoint = HingeJoint;
  94362. /**
  94363. * This class represents a dual hinge physics joint (same as wheel joint)
  94364. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  94365. */
  94366. var Hinge2Joint = /** @class */ (function (_super) {
  94367. __extends(Hinge2Joint, _super);
  94368. /**
  94369. * Initializes the Hinge2-Joint
  94370. * @param jointData The joint data for the Hinge2-Joint
  94371. */
  94372. function Hinge2Joint(jointData) {
  94373. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  94374. }
  94375. /**
  94376. * Set the motor values.
  94377. * Attention, this function is plugin specific. Engines won't react 100% the same.
  94378. * @param {number} force the force to apply
  94379. * @param {number} maxForce max force for this motor.
  94380. * @param {motorIndex} the motor's index, 0 or 1.
  94381. */
  94382. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  94383. if (motorIndex === void 0) { motorIndex = 0; }
  94384. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  94385. };
  94386. /**
  94387. * Set the motor limits.
  94388. * Attention, this function is plugin specific. Engines won't react 100% the same.
  94389. * @param {number} upperLimit the upper limit
  94390. * @param {number} lowerLimit lower limit
  94391. * @param {motorIndex} the motor's index, 0 or 1.
  94392. */
  94393. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  94394. if (motorIndex === void 0) { motorIndex = 0; }
  94395. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  94396. };
  94397. return Hinge2Joint;
  94398. }(MotorEnabledJoint));
  94399. BABYLON.Hinge2Joint = Hinge2Joint;
  94400. })(BABYLON || (BABYLON = {}));
  94401. //# sourceMappingURL=babylon.physicsJoint.js.map
  94402. var BABYLON;
  94403. (function (BABYLON) {
  94404. /**
  94405. * Represents a physics imposter
  94406. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  94407. */
  94408. var PhysicsImpostor = /** @class */ (function () {
  94409. /**
  94410. * Initializes the physics imposter
  94411. * @param object The physics-enabled object used as the physics imposter
  94412. * @param type The type of the physics imposter
  94413. * @param _options The options for the physics imposter
  94414. * @param _scene The Babylon scene
  94415. */
  94416. function PhysicsImpostor(
  94417. /**
  94418. * The physics-enabled object used as the physics imposter
  94419. */
  94420. object,
  94421. /**
  94422. * The type of the physics imposter
  94423. */
  94424. type, _options, _scene) {
  94425. if (_options === void 0) { _options = { mass: 0 }; }
  94426. var _this = this;
  94427. this.object = object;
  94428. this.type = type;
  94429. this._options = _options;
  94430. this._scene = _scene;
  94431. this._bodyUpdateRequired = false;
  94432. this._onBeforePhysicsStepCallbacks = new Array();
  94433. this._onAfterPhysicsStepCallbacks = new Array();
  94434. this._onPhysicsCollideCallbacks = [];
  94435. this._deltaPosition = BABYLON.Vector3.Zero();
  94436. this._isDisposed = false;
  94437. //temp variables for parent rotation calculations
  94438. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  94439. this._tmpQuat = new BABYLON.Quaternion();
  94440. this._tmpQuat2 = new BABYLON.Quaternion();
  94441. /**
  94442. * this function is executed by the physics engine.
  94443. */
  94444. this.beforeStep = function () {
  94445. if (!_this._physicsEngine) {
  94446. return;
  94447. }
  94448. _this.object.translate(_this._deltaPosition, -1);
  94449. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  94450. _this.object.computeWorldMatrix(false);
  94451. if (_this.object.parent && _this.object.rotationQuaternion) {
  94452. _this.getParentsRotation();
  94453. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  94454. }
  94455. else {
  94456. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  94457. }
  94458. if (!_this._options.disableBidirectionalTransformation) {
  94459. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  94460. }
  94461. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  94462. func(_this);
  94463. });
  94464. };
  94465. /**
  94466. * this function is executed by the physics engine
  94467. */
  94468. this.afterStep = function () {
  94469. if (!_this._physicsEngine) {
  94470. return;
  94471. }
  94472. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  94473. func(_this);
  94474. });
  94475. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  94476. // object has now its world rotation. needs to be converted to local.
  94477. if (_this.object.parent && _this.object.rotationQuaternion) {
  94478. _this.getParentsRotation();
  94479. _this._tmpQuat.conjugateInPlace();
  94480. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  94481. }
  94482. // take the position set and make it the absolute position of this object.
  94483. _this.object.setAbsolutePosition(_this.object.position);
  94484. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  94485. _this.object.translate(_this._deltaPosition, 1);
  94486. };
  94487. /**
  94488. * Legacy collision detection event support
  94489. */
  94490. this.onCollideEvent = null;
  94491. /**
  94492. * event and body object due to cannon's event-based architecture.
  94493. */
  94494. this.onCollide = function (e) {
  94495. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  94496. return;
  94497. }
  94498. if (!_this._physicsEngine) {
  94499. return;
  94500. }
  94501. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  94502. if (otherImpostor) {
  94503. // Legacy collision detection event support
  94504. if (_this.onCollideEvent) {
  94505. _this.onCollideEvent(_this, otherImpostor);
  94506. }
  94507. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  94508. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  94509. }).forEach(function (obj) {
  94510. obj.callback(_this, otherImpostor);
  94511. });
  94512. }
  94513. };
  94514. //sanity check!
  94515. if (!this.object) {
  94516. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  94517. return;
  94518. }
  94519. //legacy support for old syntax.
  94520. if (!this._scene && object.getScene) {
  94521. this._scene = object.getScene();
  94522. }
  94523. if (!this._scene) {
  94524. return;
  94525. }
  94526. this._physicsEngine = this._scene.getPhysicsEngine();
  94527. if (!this._physicsEngine) {
  94528. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  94529. }
  94530. else {
  94531. //set the object's quaternion, if not set
  94532. if (!this.object.rotationQuaternion) {
  94533. if (this.object.rotation) {
  94534. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  94535. }
  94536. else {
  94537. this.object.rotationQuaternion = new BABYLON.Quaternion();
  94538. }
  94539. }
  94540. //default options params
  94541. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  94542. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  94543. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  94544. this._joints = [];
  94545. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  94546. if (!this.object.parent || this._options.ignoreParent) {
  94547. this._init();
  94548. }
  94549. else if (this.object.parent.physicsImpostor) {
  94550. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  94551. }
  94552. }
  94553. }
  94554. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  94555. /**
  94556. * Specifies if the physics imposter is disposed
  94557. */
  94558. get: function () {
  94559. return this._isDisposed;
  94560. },
  94561. enumerable: true,
  94562. configurable: true
  94563. });
  94564. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  94565. /**
  94566. * Gets the mass of the physics imposter
  94567. */
  94568. get: function () {
  94569. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  94570. },
  94571. set: function (value) {
  94572. this.setMass(value);
  94573. },
  94574. enumerable: true,
  94575. configurable: true
  94576. });
  94577. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  94578. /**
  94579. * Gets the coefficient of friction
  94580. */
  94581. get: function () {
  94582. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  94583. },
  94584. /**
  94585. * Sets the coefficient of friction
  94586. */
  94587. set: function (value) {
  94588. if (!this._physicsEngine) {
  94589. return;
  94590. }
  94591. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  94592. },
  94593. enumerable: true,
  94594. configurable: true
  94595. });
  94596. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  94597. /**
  94598. * Gets the coefficient of restitution
  94599. */
  94600. get: function () {
  94601. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  94602. },
  94603. /**
  94604. * Sets the coefficient of restitution
  94605. */
  94606. set: function (value) {
  94607. if (!this._physicsEngine) {
  94608. return;
  94609. }
  94610. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  94611. },
  94612. enumerable: true,
  94613. configurable: true
  94614. });
  94615. /**
  94616. * This function will completly initialize this impostor.
  94617. * It will create a new body - but only if this mesh has no parent.
  94618. * If it has, this impostor will not be used other than to define the impostor
  94619. * of the child mesh.
  94620. * @hidden
  94621. */
  94622. PhysicsImpostor.prototype._init = function () {
  94623. if (!this._physicsEngine) {
  94624. return;
  94625. }
  94626. this._physicsEngine.removeImpostor(this);
  94627. this.physicsBody = null;
  94628. this._parent = this._parent || this._getPhysicsParent();
  94629. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  94630. this._physicsEngine.addImpostor(this);
  94631. }
  94632. };
  94633. PhysicsImpostor.prototype._getPhysicsParent = function () {
  94634. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  94635. var parentMesh = this.object.parent;
  94636. return parentMesh.physicsImpostor;
  94637. }
  94638. return null;
  94639. };
  94640. /**
  94641. * Should a new body be generated.
  94642. * @returns boolean specifying if body initialization is required
  94643. */
  94644. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  94645. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  94646. };
  94647. /**
  94648. * Sets the updated scaling
  94649. * @param updated Specifies if the scaling is updated
  94650. */
  94651. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  94652. this.forceUpdate();
  94653. };
  94654. /**
  94655. * Force a regeneration of this or the parent's impostor's body.
  94656. * Use under cautious - This will remove all joints already implemented.
  94657. */
  94658. PhysicsImpostor.prototype.forceUpdate = function () {
  94659. this._init();
  94660. if (this.parent && !this._options.ignoreParent) {
  94661. this.parent.forceUpdate();
  94662. }
  94663. };
  94664. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  94665. /*public get mesh(): AbstractMesh {
  94666. return this._mesh;
  94667. }*/
  94668. /**
  94669. * Gets the body that holds this impostor. Either its own, or its parent.
  94670. */
  94671. get: function () {
  94672. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  94673. },
  94674. /**
  94675. * Set the physics body. Used mainly by the physics engine/plugin
  94676. */
  94677. set: function (physicsBody) {
  94678. if (this._physicsBody && this._physicsEngine) {
  94679. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  94680. }
  94681. this._physicsBody = physicsBody;
  94682. this.resetUpdateFlags();
  94683. },
  94684. enumerable: true,
  94685. configurable: true
  94686. });
  94687. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  94688. /**
  94689. * Get the parent of the physics imposter
  94690. * @returns Physics imposter or null
  94691. */
  94692. get: function () {
  94693. return !this._options.ignoreParent && this._parent ? this._parent : null;
  94694. },
  94695. /**
  94696. * Sets the parent of the physics imposter
  94697. */
  94698. set: function (value) {
  94699. this._parent = value;
  94700. },
  94701. enumerable: true,
  94702. configurable: true
  94703. });
  94704. /**
  94705. * Resets the update flags
  94706. */
  94707. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  94708. this._bodyUpdateRequired = false;
  94709. };
  94710. /**
  94711. * Gets the object extend size
  94712. * @returns the object extend size
  94713. */
  94714. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  94715. if (this.object.getBoundingInfo) {
  94716. var q = this.object.rotationQuaternion;
  94717. //reset rotation
  94718. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  94719. //calculate the world matrix with no rotation
  94720. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  94721. var boundingInfo = this.object.getBoundingInfo();
  94722. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  94723. //bring back the rotation
  94724. this.object.rotationQuaternion = q;
  94725. //calculate the world matrix with the new rotation
  94726. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  94727. return size;
  94728. }
  94729. else {
  94730. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  94731. }
  94732. };
  94733. /**
  94734. * Gets the object center
  94735. * @returns The object center
  94736. */
  94737. PhysicsImpostor.prototype.getObjectCenter = function () {
  94738. if (this.object.getBoundingInfo) {
  94739. var boundingInfo = this.object.getBoundingInfo();
  94740. return boundingInfo.boundingBox.centerWorld;
  94741. }
  94742. else {
  94743. return this.object.position;
  94744. }
  94745. };
  94746. /**
  94747. * Get a specific parametes from the options parameter
  94748. * @param paramName The object parameter name
  94749. * @returns The object parameter
  94750. */
  94751. PhysicsImpostor.prototype.getParam = function (paramName) {
  94752. return this._options[paramName];
  94753. };
  94754. /**
  94755. * Sets a specific parameter in the options given to the physics plugin
  94756. * @param paramName The parameter name
  94757. * @param value The value of the parameter
  94758. */
  94759. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  94760. this._options[paramName] = value;
  94761. this._bodyUpdateRequired = true;
  94762. };
  94763. /**
  94764. * Specifically change the body's mass option. Won't recreate the physics body object
  94765. * @param mass The mass of the physics imposter
  94766. */
  94767. PhysicsImpostor.prototype.setMass = function (mass) {
  94768. if (this.getParam("mass") !== mass) {
  94769. this.setParam("mass", mass);
  94770. }
  94771. if (this._physicsEngine) {
  94772. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  94773. }
  94774. };
  94775. /**
  94776. * Gets the linear velocity
  94777. * @returns linear velocity or null
  94778. */
  94779. PhysicsImpostor.prototype.getLinearVelocity = function () {
  94780. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  94781. };
  94782. /**
  94783. * Sets the linear velocity
  94784. * @param velocity linear velocity or null
  94785. */
  94786. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  94787. if (this._physicsEngine) {
  94788. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  94789. }
  94790. };
  94791. /**
  94792. * Gets the angular velocity
  94793. * @returns angular velocity or null
  94794. */
  94795. PhysicsImpostor.prototype.getAngularVelocity = function () {
  94796. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  94797. };
  94798. /**
  94799. * Sets the angular velocity
  94800. * @param velocity The velocity or null
  94801. */
  94802. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  94803. if (this._physicsEngine) {
  94804. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  94805. }
  94806. };
  94807. /**
  94808. * Execute a function with the physics plugin native code
  94809. * Provide a function the will have two variables - the world object and the physics body object
  94810. * @param func The function to execute with the physics plugin native code
  94811. */
  94812. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  94813. if (this._physicsEngine) {
  94814. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  94815. }
  94816. };
  94817. /**
  94818. * Register a function that will be executed before the physics world is stepping forward
  94819. * @param func The function to execute before the physics world is stepped forward
  94820. */
  94821. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  94822. this._onBeforePhysicsStepCallbacks.push(func);
  94823. };
  94824. /**
  94825. * Unregister a function that will be executed before the physics world is stepping forward
  94826. * @param func The function to execute before the physics world is stepped forward
  94827. */
  94828. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  94829. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  94830. if (index > -1) {
  94831. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  94832. }
  94833. else {
  94834. BABYLON.Tools.Warn("Function to remove was not found");
  94835. }
  94836. };
  94837. /**
  94838. * Register a function that will be executed after the physics step
  94839. * @param func The function to execute after physics step
  94840. */
  94841. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  94842. this._onAfterPhysicsStepCallbacks.push(func);
  94843. };
  94844. /**
  94845. * Unregisters a function that will be executed after the physics step
  94846. * @param func The function to execute after physics step
  94847. */
  94848. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  94849. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  94850. if (index > -1) {
  94851. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  94852. }
  94853. else {
  94854. BABYLON.Tools.Warn("Function to remove was not found");
  94855. }
  94856. };
  94857. /**
  94858. * register a function that will be executed when this impostor collides against a different body
  94859. * @param collideAgainst Physics imposter, or array of physics imposters to collide against
  94860. * @param func Callback that is executed on collision
  94861. */
  94862. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  94863. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  94864. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  94865. };
  94866. /**
  94867. * Unregisters the physics imposter on contact
  94868. * @param collideAgainst The physics object to collide against
  94869. * @param func Callback to execute on collision
  94870. */
  94871. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  94872. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  94873. var index = -1;
  94874. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  94875. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  94876. // chcek the arrays match
  94877. var sameList = cbDef.otherImpostors.every(function (impostor) {
  94878. return collidedAgainstList.indexOf(impostor) > -1;
  94879. });
  94880. if (sameList) {
  94881. index = idx;
  94882. }
  94883. return sameList;
  94884. }
  94885. return false;
  94886. });
  94887. if (found) {
  94888. this._onPhysicsCollideCallbacks.splice(index, 1);
  94889. }
  94890. else {
  94891. BABYLON.Tools.Warn("Function to remove was not found");
  94892. }
  94893. };
  94894. /**
  94895. * Get the parent rotation
  94896. * @returns The parent rotation
  94897. */
  94898. PhysicsImpostor.prototype.getParentsRotation = function () {
  94899. var parent = this.object.parent;
  94900. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  94901. while (parent) {
  94902. if (parent.rotationQuaternion) {
  94903. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  94904. }
  94905. else {
  94906. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  94907. }
  94908. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  94909. parent = parent.parent;
  94910. }
  94911. return this._tmpQuat;
  94912. };
  94913. /**
  94914. * Apply a force
  94915. * @param force The force to apply
  94916. * @param contactPoint The contact point for the force
  94917. * @returns The physics imposter
  94918. */
  94919. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  94920. if (this._physicsEngine) {
  94921. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  94922. }
  94923. return this;
  94924. };
  94925. /**
  94926. * Apply an impulse
  94927. * @param force The impulse force
  94928. * @param contactPoint The contact point for the impulse force
  94929. * @returns The physics imposter
  94930. */
  94931. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  94932. if (this._physicsEngine) {
  94933. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  94934. }
  94935. return this;
  94936. };
  94937. /**
  94938. * A help function to create a joint
  94939. * @param otherImpostor A physics imposter used to create a joint
  94940. * @param jointType The type of joint
  94941. * @param jointData The data for the joint
  94942. * @returns The physics imposter
  94943. */
  94944. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  94945. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  94946. this.addJoint(otherImpostor, joint);
  94947. return this;
  94948. };
  94949. /**
  94950. * Add a joint to this impostor with a different impostor
  94951. * @param otherImpostor A physics imposter used to add a joint
  94952. * @param joint The joint to add
  94953. * @returns The physics imposter
  94954. */
  94955. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  94956. this._joints.push({
  94957. otherImpostor: otherImpostor,
  94958. joint: joint
  94959. });
  94960. if (this._physicsEngine) {
  94961. this._physicsEngine.addJoint(this, otherImpostor, joint);
  94962. }
  94963. return this;
  94964. };
  94965. /**
  94966. * Will keep this body still, in a sleep mode.
  94967. * @returns the physics imposter
  94968. */
  94969. PhysicsImpostor.prototype.sleep = function () {
  94970. if (this._physicsEngine) {
  94971. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  94972. }
  94973. return this;
  94974. };
  94975. /**
  94976. * Wake the body up.
  94977. * @returns The physics imposter
  94978. */
  94979. PhysicsImpostor.prototype.wakeUp = function () {
  94980. if (this._physicsEngine) {
  94981. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  94982. }
  94983. return this;
  94984. };
  94985. /**
  94986. * Clones the physics imposter
  94987. * @param newObject The physics imposter clones to this physics-enabled object
  94988. * @returns A nullable physics imposter
  94989. */
  94990. PhysicsImpostor.prototype.clone = function (newObject) {
  94991. if (!newObject)
  94992. return null;
  94993. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  94994. };
  94995. /**
  94996. * Disposes the physics imposter
  94997. */
  94998. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  94999. var _this = this;
  95000. //no dispose if no physics engine is available.
  95001. if (!this._physicsEngine) {
  95002. return;
  95003. }
  95004. this._joints.forEach(function (j) {
  95005. if (_this._physicsEngine) {
  95006. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  95007. }
  95008. });
  95009. //dispose the physics body
  95010. this._physicsEngine.removeImpostor(this);
  95011. if (this.parent) {
  95012. this.parent.forceUpdate();
  95013. }
  95014. else {
  95015. /*this._object.getChildMeshes().forEach(function(mesh) {
  95016. if (mesh.physicsImpostor) {
  95017. if (disposeChildren) {
  95018. mesh.physicsImpostor.dispose();
  95019. mesh.physicsImpostor = null;
  95020. }
  95021. }
  95022. })*/
  95023. }
  95024. this._isDisposed = true;
  95025. };
  95026. /**
  95027. * Sets the delta position
  95028. * @param position The delta position amount
  95029. */
  95030. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  95031. this._deltaPosition.copyFrom(position);
  95032. };
  95033. /**
  95034. * Sets the delta rotation
  95035. * @param rotation The delta rotation amount
  95036. */
  95037. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  95038. if (!this._deltaRotation) {
  95039. this._deltaRotation = new BABYLON.Quaternion();
  95040. }
  95041. this._deltaRotation.copyFrom(rotation);
  95042. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  95043. };
  95044. /**
  95045. * Gets the box size of the physics imposter and stores the result in the input parameter
  95046. * @param result Stores the box size
  95047. * @returns The physics imposter
  95048. */
  95049. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  95050. if (this._physicsEngine) {
  95051. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  95052. }
  95053. return this;
  95054. };
  95055. /**
  95056. * Gets the radius of the physics imposter
  95057. * @returns Radius of the physics imposter
  95058. */
  95059. PhysicsImpostor.prototype.getRadius = function () {
  95060. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  95061. };
  95062. /**
  95063. * Sync a bone with this impostor
  95064. * @param bone The bone to sync to the impostor.
  95065. * @param boneMesh The mesh that the bone is influencing.
  95066. * @param jointPivot The pivot of the joint / bone in local space.
  95067. * @param distToJoint Optional distance from the impostor to the joint.
  95068. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  95069. */
  95070. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  95071. var tempVec = PhysicsImpostor._tmpVecs[0];
  95072. var mesh = this.object;
  95073. if (mesh.rotationQuaternion) {
  95074. if (adjustRotation) {
  95075. var tempQuat = PhysicsImpostor._tmpQuat;
  95076. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  95077. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  95078. }
  95079. else {
  95080. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  95081. }
  95082. }
  95083. tempVec.x = 0;
  95084. tempVec.y = 0;
  95085. tempVec.z = 0;
  95086. if (jointPivot) {
  95087. tempVec.x = jointPivot.x;
  95088. tempVec.y = jointPivot.y;
  95089. tempVec.z = jointPivot.z;
  95090. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  95091. if (distToJoint === undefined || distToJoint === null) {
  95092. distToJoint = jointPivot.length();
  95093. }
  95094. tempVec.x *= distToJoint;
  95095. tempVec.y *= distToJoint;
  95096. tempVec.z *= distToJoint;
  95097. }
  95098. if (bone.getParent()) {
  95099. tempVec.addInPlace(mesh.getAbsolutePosition());
  95100. bone.setAbsolutePosition(tempVec, boneMesh);
  95101. }
  95102. else {
  95103. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  95104. boneMesh.position.x -= tempVec.x;
  95105. boneMesh.position.y -= tempVec.y;
  95106. boneMesh.position.z -= tempVec.z;
  95107. }
  95108. };
  95109. /**
  95110. * Sync impostor to a bone
  95111. * @param bone The bone that the impostor will be synced to.
  95112. * @param boneMesh The mesh that the bone is influencing.
  95113. * @param jointPivot The pivot of the joint / bone in local space.
  95114. * @param distToJoint Optional distance from the impostor to the joint.
  95115. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  95116. * @param boneAxis Optional vector3 axis the bone is aligned with
  95117. */
  95118. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  95119. var mesh = this.object;
  95120. if (mesh.rotationQuaternion) {
  95121. if (adjustRotation) {
  95122. var tempQuat = PhysicsImpostor._tmpQuat;
  95123. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  95124. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  95125. }
  95126. else {
  95127. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  95128. }
  95129. }
  95130. var pos = PhysicsImpostor._tmpVecs[0];
  95131. var boneDir = PhysicsImpostor._tmpVecs[1];
  95132. if (!boneAxis) {
  95133. boneAxis = PhysicsImpostor._tmpVecs[2];
  95134. boneAxis.x = 0;
  95135. boneAxis.y = 1;
  95136. boneAxis.z = 0;
  95137. }
  95138. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  95139. bone.getAbsolutePositionToRef(boneMesh, pos);
  95140. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  95141. distToJoint = jointPivot.length();
  95142. }
  95143. if (distToJoint !== undefined && distToJoint !== null) {
  95144. pos.x += boneDir.x * distToJoint;
  95145. pos.y += boneDir.y * distToJoint;
  95146. pos.z += boneDir.z * distToJoint;
  95147. }
  95148. mesh.setAbsolutePosition(pos);
  95149. };
  95150. /**
  95151. * The default object size of the imposter
  95152. */
  95153. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  95154. /**
  95155. * The identity quaternion of the imposter
  95156. */
  95157. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  95158. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  95159. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  95160. //Impostor types
  95161. /**
  95162. * No-Imposter type
  95163. */
  95164. PhysicsImpostor.NoImpostor = 0;
  95165. /**
  95166. * Sphere-Imposter type
  95167. */
  95168. PhysicsImpostor.SphereImpostor = 1;
  95169. /**
  95170. * Box-Imposter type
  95171. */
  95172. PhysicsImpostor.BoxImpostor = 2;
  95173. /**
  95174. * Plane-Imposter type
  95175. */
  95176. PhysicsImpostor.PlaneImpostor = 3;
  95177. /**
  95178. * Mesh-imposter type
  95179. */
  95180. PhysicsImpostor.MeshImpostor = 4;
  95181. /**
  95182. * Cylinder-Imposter type
  95183. */
  95184. PhysicsImpostor.CylinderImpostor = 7;
  95185. /**
  95186. * Particle-Imposter type
  95187. */
  95188. PhysicsImpostor.ParticleImpostor = 8;
  95189. /**
  95190. * Heightmap-Imposter type
  95191. */
  95192. PhysicsImpostor.HeightmapImpostor = 9;
  95193. return PhysicsImpostor;
  95194. }());
  95195. BABYLON.PhysicsImpostor = PhysicsImpostor;
  95196. })(BABYLON || (BABYLON = {}));
  95197. //# sourceMappingURL=babylon.physicsImpostor.js.map
  95198. var BABYLON;
  95199. (function (BABYLON) {
  95200. /**
  95201. * Class used to control physics engine
  95202. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  95203. */
  95204. var PhysicsEngine = /** @class */ (function () {
  95205. /**
  95206. * Creates a new Physics Engine
  95207. * @param gravity defines the gravity vector used by the simulation
  95208. * @param _physicsPlugin defines the plugin to use (CannonJS by default)
  95209. */
  95210. function PhysicsEngine(gravity, _physicsPlugin) {
  95211. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  95212. this._physicsPlugin = _physicsPlugin;
  95213. this._impostors = [];
  95214. this._joints = [];
  95215. if (!this._physicsPlugin.isSupported()) {
  95216. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  95217. + "Please make sure it is included.");
  95218. }
  95219. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  95220. this.setGravity(gravity);
  95221. this.setTimeStep();
  95222. }
  95223. /**
  95224. * Sets the gravity vector used by the simulation
  95225. * @param gravity defines the gravity vector to use
  95226. */
  95227. PhysicsEngine.prototype.setGravity = function (gravity) {
  95228. this.gravity = gravity;
  95229. this._physicsPlugin.setGravity(this.gravity);
  95230. };
  95231. /**
  95232. * Set the time step of the physics engine.
  95233. * Default is 1/60.
  95234. * To slow it down, enter 1/600 for example.
  95235. * To speed it up, 1/30
  95236. * @param newTimeStep defines the new timestep to apply to this world.
  95237. */
  95238. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  95239. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  95240. this._physicsPlugin.setTimeStep(newTimeStep);
  95241. };
  95242. /**
  95243. * Get the time step of the physics engine.
  95244. * @returns the current time step
  95245. */
  95246. PhysicsEngine.prototype.getTimeStep = function () {
  95247. return this._physicsPlugin.getTimeStep();
  95248. };
  95249. /**
  95250. * Release all resources
  95251. */
  95252. PhysicsEngine.prototype.dispose = function () {
  95253. this._impostors.forEach(function (impostor) {
  95254. impostor.dispose();
  95255. });
  95256. this._physicsPlugin.dispose();
  95257. };
  95258. /**
  95259. * Gets the name of the current physics plugin
  95260. * @returns the name of the plugin
  95261. */
  95262. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  95263. return this._physicsPlugin.name;
  95264. };
  95265. /**
  95266. * Adding a new impostor for the impostor tracking.
  95267. * This will be done by the impostor itself.
  95268. * @param impostor the impostor to add
  95269. */
  95270. PhysicsEngine.prototype.addImpostor = function (impostor) {
  95271. impostor.uniqueId = this._impostors.push(impostor);
  95272. //if no parent, generate the body
  95273. if (!impostor.parent) {
  95274. this._physicsPlugin.generatePhysicsBody(impostor);
  95275. }
  95276. };
  95277. /**
  95278. * Remove an impostor from the engine.
  95279. * This impostor and its mesh will not longer be updated by the physics engine.
  95280. * @param impostor the impostor to remove
  95281. */
  95282. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  95283. var index = this._impostors.indexOf(impostor);
  95284. if (index > -1) {
  95285. var removed = this._impostors.splice(index, 1);
  95286. //Is it needed?
  95287. if (removed.length) {
  95288. //this will also remove it from the world.
  95289. removed[0].physicsBody = null;
  95290. }
  95291. }
  95292. };
  95293. /**
  95294. * Add a joint to the physics engine
  95295. * @param mainImpostor defines the main impostor to which the joint is added.
  95296. * @param connectedImpostor defines the impostor that is connected to the main impostor using this joint
  95297. * @param joint defines the joint that will connect both impostors.
  95298. */
  95299. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  95300. var impostorJoint = {
  95301. mainImpostor: mainImpostor,
  95302. connectedImpostor: connectedImpostor,
  95303. joint: joint
  95304. };
  95305. joint.physicsPlugin = this._physicsPlugin;
  95306. this._joints.push(impostorJoint);
  95307. this._physicsPlugin.generateJoint(impostorJoint);
  95308. };
  95309. /**
  95310. * Removes a joint from the simulation
  95311. * @param mainImpostor defines the impostor used with the joint
  95312. * @param connectedImpostor defines the other impostor connected to the main one by the joint
  95313. * @param joint defines the joint to remove
  95314. */
  95315. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  95316. var matchingJoints = this._joints.filter(function (impostorJoint) {
  95317. return (impostorJoint.connectedImpostor === connectedImpostor
  95318. && impostorJoint.joint === joint
  95319. && impostorJoint.mainImpostor === mainImpostor);
  95320. });
  95321. if (matchingJoints.length) {
  95322. this._physicsPlugin.removeJoint(matchingJoints[0]);
  95323. //TODO remove it from the list as well
  95324. }
  95325. };
  95326. /**
  95327. * Called by the scene. No need to call it.
  95328. * @param delta defines the timespam between frames
  95329. */
  95330. PhysicsEngine.prototype._step = function (delta) {
  95331. var _this = this;
  95332. //check if any mesh has no body / requires an update
  95333. this._impostors.forEach(function (impostor) {
  95334. if (impostor.isBodyInitRequired()) {
  95335. _this._physicsPlugin.generatePhysicsBody(impostor);
  95336. }
  95337. });
  95338. if (delta > 0.1) {
  95339. delta = 0.1;
  95340. }
  95341. else if (delta <= 0) {
  95342. delta = 1.0 / 60.0;
  95343. }
  95344. this._physicsPlugin.executeStep(delta, this._impostors);
  95345. };
  95346. /**
  95347. * Gets the current plugin used to run the simulation
  95348. * @returns current plugin
  95349. */
  95350. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  95351. return this._physicsPlugin;
  95352. };
  95353. /**
  95354. * Gets the list of physic impostors
  95355. * @returns an array of PhysicsImpostor
  95356. */
  95357. PhysicsEngine.prototype.getImpostors = function () {
  95358. return this._impostors;
  95359. };
  95360. /**
  95361. * Gets the impostor for a physics enabled object
  95362. * @param object defines the object impersonated by the impostor
  95363. * @returns the PhysicsImpostor or null if not found
  95364. */
  95365. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  95366. for (var i = 0; i < this._impostors.length; ++i) {
  95367. if (this._impostors[i].object === object) {
  95368. return this._impostors[i];
  95369. }
  95370. }
  95371. return null;
  95372. };
  95373. /**
  95374. * Gets the impostor for a physics body object
  95375. * @param body defines physics body used by the impostor
  95376. * @returns the PhysicsImpostor or null if not found
  95377. */
  95378. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  95379. for (var i = 0; i < this._impostors.length; ++i) {
  95380. if (this._impostors[i].physicsBody === body) {
  95381. return this._impostors[i];
  95382. }
  95383. }
  95384. return null;
  95385. };
  95386. /**
  95387. * Global value used to control the smallest number supported by the simulation
  95388. */
  95389. PhysicsEngine.Epsilon = 0.001;
  95390. return PhysicsEngine;
  95391. }());
  95392. BABYLON.PhysicsEngine = PhysicsEngine;
  95393. })(BABYLON || (BABYLON = {}));
  95394. //# sourceMappingURL=babylon.physicsEngine.js.map
  95395. var BABYLON;
  95396. (function (BABYLON) {
  95397. /**
  95398. * A helper for physics simulations
  95399. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  95400. */
  95401. var PhysicsHelper = /** @class */ (function () {
  95402. /**
  95403. * Initializes the Physics helper
  95404. * @param scene Babylon.js scene
  95405. */
  95406. function PhysicsHelper(scene) {
  95407. this._scene = scene;
  95408. this._physicsEngine = this._scene.getPhysicsEngine();
  95409. if (!this._physicsEngine) {
  95410. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  95411. }
  95412. }
  95413. /**
  95414. * Applies a radial explosion impulse
  95415. * @param origin the origin of the explosion
  95416. * @param radius the explosion radius
  95417. * @param strength the explosion strength
  95418. * @param falloff possible options: Constant & Linear. Defaults to Constant
  95419. * @returns A physics radial explosion event, or null
  95420. */
  95421. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  95422. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  95423. if (!this._physicsEngine) {
  95424. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  95425. return null;
  95426. }
  95427. var impostors = this._physicsEngine.getImpostors();
  95428. if (impostors.length === 0) {
  95429. return null;
  95430. }
  95431. var event = new PhysicsRadialExplosionEvent(this._scene);
  95432. impostors.forEach(function (impostor) {
  95433. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  95434. if (!impostorForceAndContactPoint) {
  95435. return;
  95436. }
  95437. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  95438. });
  95439. event.dispose(false);
  95440. return event;
  95441. };
  95442. /**
  95443. * Applies a radial explosion force
  95444. * @param origin the origin of the explosion
  95445. * @param radius the explosion radius
  95446. * @param strength the explosion strength
  95447. * @param falloff possible options: Constant & Linear. Defaults to Constant
  95448. * @returns A physics radial explosion event, or null
  95449. */
  95450. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  95451. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  95452. if (!this._physicsEngine) {
  95453. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  95454. return null;
  95455. }
  95456. var impostors = this._physicsEngine.getImpostors();
  95457. if (impostors.length === 0) {
  95458. return null;
  95459. }
  95460. var event = new PhysicsRadialExplosionEvent(this._scene);
  95461. impostors.forEach(function (impostor) {
  95462. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  95463. if (!impostorForceAndContactPoint) {
  95464. return;
  95465. }
  95466. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  95467. });
  95468. event.dispose(false);
  95469. return event;
  95470. };
  95471. /**
  95472. * Creates a gravitational field
  95473. * @param origin the origin of the explosion
  95474. * @param radius the explosion radius
  95475. * @param strength the explosion strength
  95476. * @param falloff possible options: Constant & Linear. Defaults to Constant
  95477. * @returns A physics gravitational field event, or null
  95478. */
  95479. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  95480. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  95481. if (!this._physicsEngine) {
  95482. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  95483. return null;
  95484. }
  95485. var impostors = this._physicsEngine.getImpostors();
  95486. if (impostors.length === 0) {
  95487. return null;
  95488. }
  95489. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  95490. event.dispose(false);
  95491. return event;
  95492. };
  95493. /**
  95494. * Creates a physics updraft event
  95495. * @param origin the origin of the updraft
  95496. * @param radius the radius of the updraft
  95497. * @param strength the strength of the updraft
  95498. * @param height the height of the updraft
  95499. * @param updraftMode possible options: Center & Perpendicular. Defaults to Center
  95500. * @returns A physics updraft event, or null
  95501. */
  95502. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  95503. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  95504. if (!this._physicsEngine) {
  95505. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  95506. return null;
  95507. }
  95508. if (this._physicsEngine.getImpostors().length === 0) {
  95509. return null;
  95510. }
  95511. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  95512. event.dispose(false);
  95513. return event;
  95514. };
  95515. /**
  95516. * Creates a physics vortex event
  95517. * @param origin the of the vortex
  95518. * @param radius the radius of the vortex
  95519. * @param strength the strength of the vortex
  95520. * @param height the height of the vortex
  95521. * @returns a Physics vortex event, or null
  95522. * A physics vortex event or null
  95523. */
  95524. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  95525. if (!this._physicsEngine) {
  95526. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  95527. return null;
  95528. }
  95529. if (this._physicsEngine.getImpostors().length === 0) {
  95530. return null;
  95531. }
  95532. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  95533. event.dispose(false);
  95534. return event;
  95535. };
  95536. return PhysicsHelper;
  95537. }());
  95538. BABYLON.PhysicsHelper = PhysicsHelper;
  95539. /**
  95540. * Represents a physics radial explosion event
  95541. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  95542. */
  95543. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  95544. /**
  95545. * Initializes a radial explosioin event
  95546. * @param scene BabylonJS scene
  95547. */
  95548. function PhysicsRadialExplosionEvent(scene) {
  95549. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  95550. this._rays = [];
  95551. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  95552. this._scene = scene;
  95553. }
  95554. /**
  95555. * Returns the data related to the radial explosion event (sphere & rays).
  95556. * @returns The radial explosion event data
  95557. */
  95558. PhysicsRadialExplosionEvent.prototype.getData = function () {
  95559. this._dataFetched = true;
  95560. return {
  95561. sphere: this._sphere,
  95562. rays: this._rays,
  95563. };
  95564. };
  95565. /**
  95566. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  95567. * @param impostor A physics imposter
  95568. * @param origin the origin of the explosion
  95569. * @param radius the explosion radius
  95570. * @param strength the explosion strength
  95571. * @param falloff possible options: Constant & Linear
  95572. * @returns {Nullable<PhysicsForceAndContactPoint>} A physics force and contact point, or null
  95573. */
  95574. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  95575. if (impostor.mass === 0) {
  95576. return null;
  95577. }
  95578. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  95579. return null;
  95580. }
  95581. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  95582. return null;
  95583. }
  95584. var impostorObjectCenter = impostor.getObjectCenter();
  95585. var direction = impostorObjectCenter.subtract(origin);
  95586. var ray = new BABYLON.Ray(origin, direction, radius);
  95587. this._rays.push(ray);
  95588. var hit = ray.intersectsMesh(impostor.object);
  95589. var contactPoint = hit.pickedPoint;
  95590. if (!contactPoint) {
  95591. return null;
  95592. }
  95593. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  95594. if (distanceFromOrigin > radius) {
  95595. return null;
  95596. }
  95597. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  95598. ? strength
  95599. : strength * (1 - (distanceFromOrigin / radius));
  95600. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  95601. return { force: force, contactPoint: contactPoint };
  95602. };
  95603. /**
  95604. * Disposes the sphere.
  95605. * @param force Specifies if the sphere should be disposed by force
  95606. */
  95607. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  95608. var _this = this;
  95609. if (force === void 0) { force = true; }
  95610. if (force) {
  95611. this._sphere.dispose();
  95612. }
  95613. else {
  95614. setTimeout(function () {
  95615. if (!_this._dataFetched) {
  95616. _this._sphere.dispose();
  95617. }
  95618. }, 0);
  95619. }
  95620. };
  95621. /*** Helpers ***/
  95622. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  95623. if (!this._sphere) {
  95624. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  95625. this._sphere.isVisible = false;
  95626. }
  95627. };
  95628. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  95629. var impostorObject = impostor.object;
  95630. this._prepareSphere();
  95631. this._sphere.position = origin;
  95632. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  95633. this._sphere._updateBoundingInfo();
  95634. this._sphere.computeWorldMatrix(true);
  95635. return this._sphere.intersectsMesh(impostorObject, true);
  95636. };
  95637. return PhysicsRadialExplosionEvent;
  95638. }());
  95639. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  95640. /**
  95641. * Represents a gravitational field event
  95642. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  95643. */
  95644. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  95645. /**
  95646. * Initializes the physics gravitational field event
  95647. * @param physicsHelper A physics helper
  95648. * @param scene BabylonJS scene
  95649. * @param origin The origin position of the gravitational field event
  95650. * @param radius The radius of the gravitational field event
  95651. * @param strength The strength of the gravitational field event
  95652. * @param falloff The falloff for the gravitational field event
  95653. */
  95654. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  95655. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  95656. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  95657. this._physicsHelper = physicsHelper;
  95658. this._scene = scene;
  95659. this._origin = origin;
  95660. this._radius = radius;
  95661. this._strength = strength;
  95662. this._falloff = falloff;
  95663. this._tickCallback = this._tick.bind(this);
  95664. }
  95665. /**
  95666. * Returns the data related to the gravitational field event (sphere).
  95667. * @returns A gravitational field event
  95668. */
  95669. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  95670. this._dataFetched = true;
  95671. return {
  95672. sphere: this._sphere,
  95673. };
  95674. };
  95675. /**
  95676. * Enables the gravitational field.
  95677. */
  95678. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  95679. this._tickCallback.call(this);
  95680. this._scene.registerBeforeRender(this._tickCallback);
  95681. };
  95682. /**
  95683. * Disables the gravitational field.
  95684. */
  95685. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  95686. this._scene.unregisterBeforeRender(this._tickCallback);
  95687. };
  95688. /**
  95689. * Disposes the sphere.
  95690. * @param force The force to dispose from the gravitational field event
  95691. */
  95692. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  95693. var _this = this;
  95694. if (force === void 0) { force = true; }
  95695. if (force) {
  95696. this._sphere.dispose();
  95697. }
  95698. else {
  95699. setTimeout(function () {
  95700. if (!_this._dataFetched) {
  95701. _this._sphere.dispose();
  95702. }
  95703. }, 0);
  95704. }
  95705. };
  95706. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  95707. // Since the params won't change, we fetch the event only once
  95708. if (this._sphere) {
  95709. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  95710. }
  95711. else {
  95712. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  95713. if (radialExplosionEvent) {
  95714. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  95715. }
  95716. }
  95717. };
  95718. return PhysicsGravitationalFieldEvent;
  95719. }());
  95720. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  95721. /**
  95722. * Represents a physics updraft event
  95723. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  95724. */
  95725. var PhysicsUpdraftEvent = /** @class */ (function () {
  95726. /**
  95727. * Initializes the physics updraft event
  95728. * @param _scene BabylonJS scene
  95729. * @param _origin The origin position of the updraft
  95730. * @param _radius The radius of the updraft
  95731. * @param _strength The strength of the updraft
  95732. * @param _height The height of the updraft
  95733. * @param _updraftMode The mode of the updraft
  95734. */
  95735. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  95736. this._scene = _scene;
  95737. this._origin = _origin;
  95738. this._radius = _radius;
  95739. this._strength = _strength;
  95740. this._height = _height;
  95741. this._updraftMode = _updraftMode;
  95742. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  95743. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  95744. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  95745. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  95746. this._physicsEngine = this._scene.getPhysicsEngine();
  95747. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  95748. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  95749. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  95750. this._originDirection = this._origin.subtract(this._originTop).normalize();
  95751. }
  95752. this._tickCallback = this._tick.bind(this);
  95753. }
  95754. /**
  95755. * Returns the data related to the updraft event (cylinder).
  95756. * @returns A physics updraft event
  95757. */
  95758. PhysicsUpdraftEvent.prototype.getData = function () {
  95759. this._dataFetched = true;
  95760. return {
  95761. cylinder: this._cylinder,
  95762. };
  95763. };
  95764. /**
  95765. * Enables the updraft.
  95766. */
  95767. PhysicsUpdraftEvent.prototype.enable = function () {
  95768. this._tickCallback.call(this);
  95769. this._scene.registerBeforeRender(this._tickCallback);
  95770. };
  95771. /**
  95772. * Disables the cortex.
  95773. */
  95774. PhysicsUpdraftEvent.prototype.disable = function () {
  95775. this._scene.unregisterBeforeRender(this._tickCallback);
  95776. };
  95777. /**
  95778. * Disposes the sphere.
  95779. * @param force Specifies if the updraft should be disposed by force
  95780. */
  95781. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  95782. var _this = this;
  95783. if (force === void 0) { force = true; }
  95784. if (force) {
  95785. this._cylinder.dispose();
  95786. }
  95787. else {
  95788. setTimeout(function () {
  95789. if (!_this._dataFetched) {
  95790. _this._cylinder.dispose();
  95791. }
  95792. }, 0);
  95793. }
  95794. };
  95795. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  95796. if (impostor.mass === 0) {
  95797. return null;
  95798. }
  95799. if (!this._intersectsWithCylinder(impostor)) {
  95800. return null;
  95801. }
  95802. var impostorObjectCenter = impostor.getObjectCenter();
  95803. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  95804. var direction = this._originDirection;
  95805. }
  95806. else {
  95807. var direction = impostorObjectCenter.subtract(this._originTop);
  95808. }
  95809. var multiplier = this._strength * -1;
  95810. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  95811. return { force: force, contactPoint: impostorObjectCenter };
  95812. };
  95813. PhysicsUpdraftEvent.prototype._tick = function () {
  95814. var _this = this;
  95815. this._physicsEngine.getImpostors().forEach(function (impostor) {
  95816. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  95817. if (!impostorForceAndContactPoint) {
  95818. return;
  95819. }
  95820. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  95821. });
  95822. };
  95823. /*** Helpers ***/
  95824. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  95825. if (!this._cylinder) {
  95826. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  95827. height: this._height,
  95828. diameter: this._radius * 2,
  95829. }, this._scene);
  95830. this._cylinder.isVisible = false;
  95831. }
  95832. };
  95833. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  95834. var impostorObject = impostor.object;
  95835. this._prepareCylinder();
  95836. this._cylinder.position = this._cylinderPosition;
  95837. return this._cylinder.intersectsMesh(impostorObject, true);
  95838. };
  95839. return PhysicsUpdraftEvent;
  95840. }());
  95841. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  95842. /**
  95843. * Represents a physics vortex event
  95844. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  95845. */
  95846. var PhysicsVortexEvent = /** @class */ (function () {
  95847. /**
  95848. * Initializes the physics vortex event
  95849. * @param _scene The BabylonJS scene
  95850. * @param _origin The origin position of the vortex
  95851. * @param _radius The radius of the vortex
  95852. * @param _strength The strength of the vortex
  95853. * @param _height The height of the vortex
  95854. */
  95855. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  95856. this._scene = _scene;
  95857. this._origin = _origin;
  95858. this._radius = _radius;
  95859. this._strength = _strength;
  95860. this._height = _height;
  95861. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  95862. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  95863. this._updraftMultiplier = 0.02;
  95864. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  95865. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  95866. this._physicsEngine = this._scene.getPhysicsEngine();
  95867. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  95868. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  95869. this._tickCallback = this._tick.bind(this);
  95870. }
  95871. /**
  95872. * Returns the data related to the vortex event (cylinder).
  95873. * @returns The physics vortex event data
  95874. */
  95875. PhysicsVortexEvent.prototype.getData = function () {
  95876. this._dataFetched = true;
  95877. return {
  95878. cylinder: this._cylinder,
  95879. };
  95880. };
  95881. /**
  95882. * Enables the vortex.
  95883. */
  95884. PhysicsVortexEvent.prototype.enable = function () {
  95885. this._tickCallback.call(this);
  95886. this._scene.registerBeforeRender(this._tickCallback);
  95887. };
  95888. /**
  95889. * Disables the cortex.
  95890. */
  95891. PhysicsVortexEvent.prototype.disable = function () {
  95892. this._scene.unregisterBeforeRender(this._tickCallback);
  95893. };
  95894. /**
  95895. * Disposes the sphere.
  95896. * @param force
  95897. */
  95898. PhysicsVortexEvent.prototype.dispose = function (force) {
  95899. var _this = this;
  95900. if (force === void 0) { force = true; }
  95901. if (force) {
  95902. this._cylinder.dispose();
  95903. }
  95904. else {
  95905. setTimeout(function () {
  95906. if (!_this._dataFetched) {
  95907. _this._cylinder.dispose();
  95908. }
  95909. }, 0);
  95910. }
  95911. };
  95912. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  95913. if (impostor.mass === 0) {
  95914. return null;
  95915. }
  95916. if (!this._intersectsWithCylinder(impostor)) {
  95917. return null;
  95918. }
  95919. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  95920. return null;
  95921. }
  95922. var impostorObjectCenter = impostor.getObjectCenter();
  95923. 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)
  95924. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  95925. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  95926. var hit = ray.intersectsMesh(impostor.object);
  95927. var contactPoint = hit.pickedPoint;
  95928. if (!contactPoint) {
  95929. return null;
  95930. }
  95931. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  95932. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  95933. var directionToOrigin = contactPoint.normalize();
  95934. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  95935. directionToOrigin = directionToOrigin.negate();
  95936. }
  95937. // TODO: find a more physically based solution
  95938. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  95939. var forceX = directionToOrigin.x * this._strength / 8;
  95940. var forceY = directionToOrigin.y * this._updraftMultiplier;
  95941. var forceZ = directionToOrigin.z * this._strength / 8;
  95942. }
  95943. else {
  95944. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  95945. var forceY = this._originTop.y * this._updraftMultiplier;
  95946. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  95947. }
  95948. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  95949. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  95950. return { force: force, contactPoint: impostorObjectCenter };
  95951. };
  95952. PhysicsVortexEvent.prototype._tick = function () {
  95953. var _this = this;
  95954. this._physicsEngine.getImpostors().forEach(function (impostor) {
  95955. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  95956. if (!impostorForceAndContactPoint) {
  95957. return;
  95958. }
  95959. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  95960. });
  95961. };
  95962. /*** Helpers ***/
  95963. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  95964. if (!this._cylinder) {
  95965. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  95966. height: this._height,
  95967. diameter: this._radius * 2,
  95968. }, this._scene);
  95969. this._cylinder.isVisible = false;
  95970. }
  95971. };
  95972. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  95973. var impostorObject = impostor.object;
  95974. this._prepareCylinder();
  95975. this._cylinder.position = this._cylinderPosition;
  95976. return this._cylinder.intersectsMesh(impostorObject, true);
  95977. };
  95978. return PhysicsVortexEvent;
  95979. }());
  95980. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  95981. /**
  95982. * The strenght of the force in correspondence to the distance of the affected object
  95983. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  95984. */
  95985. var PhysicsRadialImpulseFalloff;
  95986. (function (PhysicsRadialImpulseFalloff) {
  95987. /** Defines that impulse is constant in strength across it's whole radius */
  95988. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  95989. /** DEfines that impulse gets weaker if it's further from the origin */
  95990. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  95991. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  95992. /**
  95993. * The strength of the force in correspondence to the distance of the affected object
  95994. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  95995. */
  95996. var PhysicsUpdraftMode;
  95997. (function (PhysicsUpdraftMode) {
  95998. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  95999. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  96000. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  96001. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  96002. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  96003. })(BABYLON || (BABYLON = {}));
  96004. //# sourceMappingURL=babylon.physicsHelper.js.map
  96005. var BABYLON;
  96006. (function (BABYLON) {
  96007. /** @hidden */
  96008. var CannonJSPlugin = /** @class */ (function () {
  96009. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  96010. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  96011. if (iterations === void 0) { iterations = 10; }
  96012. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  96013. this.name = "CannonJSPlugin";
  96014. this._physicsMaterials = new Array();
  96015. this._fixedTimeStep = 1 / 60;
  96016. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  96017. this.BJSCANNON = CANNON;
  96018. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  96019. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  96020. this._tmpPosition = BABYLON.Vector3.Zero();
  96021. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  96022. this._tmpUnityRotation = new BABYLON.Quaternion();
  96023. if (!this.isSupported()) {
  96024. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  96025. return;
  96026. }
  96027. this._extendNamespace();
  96028. this.world = new this.BJSCANNON.World();
  96029. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  96030. this.world.solver.iterations = iterations;
  96031. }
  96032. CannonJSPlugin.prototype.setGravity = function (gravity) {
  96033. this.world.gravity.copy(gravity);
  96034. };
  96035. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  96036. this._fixedTimeStep = timeStep;
  96037. };
  96038. CannonJSPlugin.prototype.getTimeStep = function () {
  96039. return this._fixedTimeStep;
  96040. };
  96041. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  96042. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  96043. };
  96044. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  96045. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  96046. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  96047. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  96048. };
  96049. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  96050. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  96051. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  96052. impostor.physicsBody.applyForce(impulse, worldPoint);
  96053. };
  96054. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  96055. //parent-child relationship. Does this impostor has a parent impostor?
  96056. if (impostor.parent) {
  96057. if (impostor.physicsBody) {
  96058. this.removePhysicsBody(impostor);
  96059. //TODO is that needed?
  96060. impostor.forceUpdate();
  96061. }
  96062. return;
  96063. }
  96064. //should a new body be created for this impostor?
  96065. if (impostor.isBodyInitRequired()) {
  96066. var shape = this._createShape(impostor);
  96067. //unregister events, if body is being changed
  96068. var oldBody = impostor.physicsBody;
  96069. if (oldBody) {
  96070. this.removePhysicsBody(impostor);
  96071. }
  96072. //create the body and material
  96073. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  96074. var bodyCreationObject = {
  96075. mass: impostor.getParam("mass"),
  96076. material: material
  96077. };
  96078. // A simple extend, in case native options were used.
  96079. var nativeOptions = impostor.getParam("nativeOptions");
  96080. for (var key in nativeOptions) {
  96081. if (nativeOptions.hasOwnProperty(key)) {
  96082. bodyCreationObject[key] = nativeOptions[key];
  96083. }
  96084. }
  96085. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  96086. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  96087. this.world.addEventListener("preStep", impostor.beforeStep);
  96088. this.world.addEventListener("postStep", impostor.afterStep);
  96089. impostor.physicsBody.addShape(shape);
  96090. this.world.add(impostor.physicsBody);
  96091. //try to keep the body moving in the right direction by taking old properties.
  96092. //Should be tested!
  96093. if (oldBody) {
  96094. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  96095. impostor.physicsBody[param].copy(oldBody[param]);
  96096. });
  96097. }
  96098. this._processChildMeshes(impostor);
  96099. }
  96100. //now update the body's transformation
  96101. this._updatePhysicsBodyTransformation(impostor);
  96102. };
  96103. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  96104. var _this = this;
  96105. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  96106. var currentRotation = mainImpostor.object.rotationQuaternion;
  96107. if (meshChildren.length) {
  96108. var processMesh = function (localPosition, mesh) {
  96109. if (!currentRotation || !mesh.rotationQuaternion) {
  96110. return;
  96111. }
  96112. var childImpostor = mesh.getPhysicsImpostor();
  96113. if (childImpostor) {
  96114. var parent = childImpostor.parent;
  96115. if (parent !== mainImpostor) {
  96116. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  96117. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  96118. if (childImpostor.physicsBody) {
  96119. _this.removePhysicsBody(childImpostor);
  96120. childImpostor.physicsBody = null;
  96121. }
  96122. childImpostor.parent = mainImpostor;
  96123. childImpostor.resetUpdateFlags();
  96124. 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));
  96125. //Add the mass of the children.
  96126. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  96127. }
  96128. }
  96129. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  96130. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  96131. };
  96132. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  96133. }
  96134. };
  96135. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  96136. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  96137. this.world.removeEventListener("preStep", impostor.beforeStep);
  96138. this.world.removeEventListener("postStep", impostor.afterStep);
  96139. this.world.remove(impostor.physicsBody);
  96140. };
  96141. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  96142. var mainBody = impostorJoint.mainImpostor.physicsBody;
  96143. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  96144. if (!mainBody || !connectedBody) {
  96145. return;
  96146. }
  96147. var constraint;
  96148. var jointData = impostorJoint.joint.jointData;
  96149. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  96150. var constraintData = {
  96151. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  96152. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  96153. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  96154. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  96155. maxForce: jointData.nativeParams.maxForce,
  96156. collideConnected: !!jointData.collision
  96157. };
  96158. switch (impostorJoint.joint.type) {
  96159. case BABYLON.PhysicsJoint.HingeJoint:
  96160. case BABYLON.PhysicsJoint.Hinge2Joint:
  96161. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  96162. break;
  96163. case BABYLON.PhysicsJoint.DistanceJoint:
  96164. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  96165. break;
  96166. case BABYLON.PhysicsJoint.SpringJoint:
  96167. var springData = jointData;
  96168. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  96169. restLength: springData.length,
  96170. stiffness: springData.stiffness,
  96171. damping: springData.damping,
  96172. localAnchorA: constraintData.pivotA,
  96173. localAnchorB: constraintData.pivotB
  96174. });
  96175. break;
  96176. case BABYLON.PhysicsJoint.LockJoint:
  96177. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  96178. break;
  96179. case BABYLON.PhysicsJoint.PointToPointJoint:
  96180. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  96181. default:
  96182. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  96183. break;
  96184. }
  96185. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  96186. constraint.collideConnected = !!jointData.collision;
  96187. impostorJoint.joint.physicsJoint = constraint;
  96188. //don't add spring as constraint, as it is not one.
  96189. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  96190. this.world.addConstraint(constraint);
  96191. }
  96192. else {
  96193. impostorJoint.joint.jointData.forceApplicationCallback = impostorJoint.joint.jointData.forceApplicationCallback || function () {
  96194. constraint.applyForce();
  96195. };
  96196. impostorJoint.mainImpostor.registerAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);
  96197. }
  96198. };
  96199. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  96200. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  96201. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  96202. }
  96203. else {
  96204. impostorJoint.mainImpostor.unregisterAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);
  96205. }
  96206. };
  96207. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  96208. var index;
  96209. var mat;
  96210. for (index = 0; index < this._physicsMaterials.length; index++) {
  96211. mat = this._physicsMaterials[index];
  96212. if (mat.friction === friction && mat.restitution === restitution) {
  96213. return mat;
  96214. }
  96215. }
  96216. var currentMat = new this.BJSCANNON.Material(name);
  96217. currentMat.friction = friction;
  96218. currentMat.restitution = restitution;
  96219. this._physicsMaterials.push(currentMat);
  96220. return currentMat;
  96221. };
  96222. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  96223. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  96224. };
  96225. CannonJSPlugin.prototype._createShape = function (impostor) {
  96226. var object = impostor.object;
  96227. var returnValue;
  96228. var extendSize = impostor.getObjectExtendSize();
  96229. switch (impostor.type) {
  96230. case BABYLON.PhysicsImpostor.SphereImpostor:
  96231. var radiusX = extendSize.x;
  96232. var radiusY = extendSize.y;
  96233. var radiusZ = extendSize.z;
  96234. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  96235. break;
  96236. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  96237. case BABYLON.PhysicsImpostor.CylinderImpostor:
  96238. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  96239. break;
  96240. case BABYLON.PhysicsImpostor.BoxImpostor:
  96241. var box = extendSize.scale(0.5);
  96242. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  96243. break;
  96244. case BABYLON.PhysicsImpostor.PlaneImpostor:
  96245. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  96246. returnValue = new this.BJSCANNON.Plane();
  96247. break;
  96248. case BABYLON.PhysicsImpostor.MeshImpostor:
  96249. // should transform the vertex data to world coordinates!!
  96250. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  96251. var rawFaces = object.getIndices ? object.getIndices() : [];
  96252. if (!rawVerts)
  96253. return;
  96254. // get only scale! so the object could transform correctly.
  96255. var oldPosition = object.position.clone();
  96256. var oldRotation = object.rotation && object.rotation.clone();
  96257. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  96258. object.position.copyFromFloats(0, 0, 0);
  96259. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  96260. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  96261. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  96262. var transform = object.computeWorldMatrix(true);
  96263. // convert rawVerts to object space
  96264. var temp = new Array();
  96265. var index;
  96266. for (index = 0; index < rawVerts.length; index += 3) {
  96267. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  96268. }
  96269. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  96270. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  96271. //now set back the transformation!
  96272. object.position.copyFrom(oldPosition);
  96273. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  96274. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  96275. break;
  96276. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  96277. var oldPosition2 = object.position.clone();
  96278. var oldRotation2 = object.rotation && object.rotation.clone();
  96279. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  96280. object.position.copyFromFloats(0, 0, 0);
  96281. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  96282. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  96283. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  96284. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  96285. returnValue = this._createHeightmap(object);
  96286. object.position.copyFrom(oldPosition2);
  96287. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  96288. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  96289. object.computeWorldMatrix(true);
  96290. break;
  96291. case BABYLON.PhysicsImpostor.ParticleImpostor:
  96292. returnValue = new this.BJSCANNON.Particle();
  96293. break;
  96294. }
  96295. return returnValue;
  96296. };
  96297. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  96298. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  96299. var transform = object.computeWorldMatrix(true);
  96300. // convert rawVerts to object space
  96301. var temp = new Array();
  96302. var index;
  96303. for (index = 0; index < pos.length; index += 3) {
  96304. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  96305. }
  96306. pos = temp;
  96307. var matrix = new Array();
  96308. //For now pointDepth will not be used and will be automatically calculated.
  96309. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  96310. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  96311. var boundingInfo = object.getBoundingInfo();
  96312. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  96313. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  96314. var elementSize = dim * 2 / arraySize;
  96315. for (var i = 0; i < pos.length; i = i + 3) {
  96316. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  96317. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  96318. var y = -pos[i + 2] + minY;
  96319. if (!matrix[x]) {
  96320. matrix[x] = [];
  96321. }
  96322. if (!matrix[x][z]) {
  96323. matrix[x][z] = y;
  96324. }
  96325. matrix[x][z] = Math.max(y, matrix[x][z]);
  96326. }
  96327. for (var x = 0; x <= arraySize; ++x) {
  96328. if (!matrix[x]) {
  96329. var loc = 1;
  96330. while (!matrix[(x + loc) % arraySize]) {
  96331. loc++;
  96332. }
  96333. matrix[x] = matrix[(x + loc) % arraySize].slice();
  96334. //console.log("missing x", x);
  96335. }
  96336. for (var z = 0; z <= arraySize; ++z) {
  96337. if (!matrix[x][z]) {
  96338. var loc = 1;
  96339. var newValue;
  96340. while (newValue === undefined) {
  96341. newValue = matrix[x][(z + loc++) % arraySize];
  96342. }
  96343. matrix[x][z] = newValue;
  96344. }
  96345. }
  96346. }
  96347. var shape = new this.BJSCANNON.Heightfield(matrix, {
  96348. elementSize: elementSize
  96349. });
  96350. //For future reference, needed for body transformation
  96351. shape.minY = minY;
  96352. return shape;
  96353. };
  96354. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  96355. var object = impostor.object;
  96356. //make sure it is updated...
  96357. object.computeWorldMatrix && object.computeWorldMatrix(true);
  96358. // The delta between the mesh position and the mesh bounding box center
  96359. var bInfo = object.getBoundingInfo();
  96360. if (!bInfo)
  96361. return;
  96362. var center = impostor.getObjectCenter();
  96363. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  96364. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  96365. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  96366. this._tmpPosition.copyFrom(center);
  96367. var quaternion = object.rotationQuaternion;
  96368. if (!quaternion) {
  96369. return;
  96370. }
  96371. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  96372. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  96373. //-90 DEG in X, precalculated
  96374. quaternion = quaternion.multiply(this._minus90X);
  96375. //Invert! (Precalculated, 90 deg in X)
  96376. //No need to clone. this will never change.
  96377. impostor.setDeltaRotation(this._plus90X);
  96378. }
  96379. //If it is a heightfield, if should be centered.
  96380. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  96381. var mesh = object;
  96382. var boundingInfo = mesh.getBoundingInfo();
  96383. //calculate the correct body position:
  96384. var rotationQuaternion = mesh.rotationQuaternion;
  96385. mesh.rotationQuaternion = this._tmpUnityRotation;
  96386. mesh.computeWorldMatrix(true);
  96387. //get original center with no rotation
  96388. var c = center.clone();
  96389. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  96390. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  96391. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  96392. mesh.setPreTransformMatrix(p);
  96393. mesh.computeWorldMatrix(true);
  96394. //calculate the translation
  96395. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  96396. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  96397. //add it inverted to the delta
  96398. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  96399. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  96400. //rotation is back
  96401. mesh.rotationQuaternion = rotationQuaternion;
  96402. mesh.setPreTransformMatrix(oldPivot);
  96403. mesh.computeWorldMatrix(true);
  96404. }
  96405. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  96406. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  96407. //this._tmpPosition.copyFrom(object.position);
  96408. }
  96409. impostor.setDeltaPosition(this._tmpDeltaPosition);
  96410. //Now update the impostor object
  96411. impostor.physicsBody.position.copy(this._tmpPosition);
  96412. impostor.physicsBody.quaternion.copy(quaternion);
  96413. };
  96414. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  96415. impostor.object.position.copyFrom(impostor.physicsBody.position);
  96416. if (impostor.object.rotationQuaternion) {
  96417. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  96418. }
  96419. };
  96420. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  96421. impostor.physicsBody.position.copy(newPosition);
  96422. impostor.physicsBody.quaternion.copy(newRotation);
  96423. };
  96424. CannonJSPlugin.prototype.isSupported = function () {
  96425. return this.BJSCANNON !== undefined;
  96426. };
  96427. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  96428. impostor.physicsBody.velocity.copy(velocity);
  96429. };
  96430. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  96431. impostor.physicsBody.angularVelocity.copy(velocity);
  96432. };
  96433. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  96434. var v = impostor.physicsBody.velocity;
  96435. if (!v) {
  96436. return null;
  96437. }
  96438. return new BABYLON.Vector3(v.x, v.y, v.z);
  96439. };
  96440. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  96441. var v = impostor.physicsBody.angularVelocity;
  96442. if (!v) {
  96443. return null;
  96444. }
  96445. return new BABYLON.Vector3(v.x, v.y, v.z);
  96446. };
  96447. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  96448. impostor.physicsBody.mass = mass;
  96449. impostor.physicsBody.updateMassProperties();
  96450. };
  96451. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  96452. return impostor.physicsBody.mass;
  96453. };
  96454. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  96455. return impostor.physicsBody.material.friction;
  96456. };
  96457. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  96458. impostor.physicsBody.material.friction = friction;
  96459. };
  96460. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  96461. return impostor.physicsBody.material.restitution;
  96462. };
  96463. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  96464. impostor.physicsBody.material.restitution = restitution;
  96465. };
  96466. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  96467. impostor.physicsBody.sleep();
  96468. };
  96469. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  96470. impostor.physicsBody.wakeUp();
  96471. };
  96472. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  96473. joint.physicsJoint.distance = maxDistance;
  96474. };
  96475. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  96476. // if (!motorIndex) {
  96477. // joint.physicsJoint.enableMotor();
  96478. // }
  96479. // }
  96480. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  96481. // if (!motorIndex) {
  96482. // joint.physicsJoint.disableMotor();
  96483. // }
  96484. // }
  96485. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  96486. if (!motorIndex) {
  96487. joint.physicsJoint.enableMotor();
  96488. joint.physicsJoint.setMotorSpeed(speed);
  96489. if (maxForce) {
  96490. this.setLimit(joint, maxForce);
  96491. }
  96492. }
  96493. };
  96494. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  96495. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  96496. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  96497. };
  96498. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  96499. var body = impostor.physicsBody;
  96500. mesh.position.x = body.position.x;
  96501. mesh.position.y = body.position.y;
  96502. mesh.position.z = body.position.z;
  96503. if (mesh.rotationQuaternion) {
  96504. mesh.rotationQuaternion.x = body.quaternion.x;
  96505. mesh.rotationQuaternion.y = body.quaternion.y;
  96506. mesh.rotationQuaternion.z = body.quaternion.z;
  96507. mesh.rotationQuaternion.w = body.quaternion.w;
  96508. }
  96509. };
  96510. CannonJSPlugin.prototype.getRadius = function (impostor) {
  96511. var shape = impostor.physicsBody.shapes[0];
  96512. return shape.boundingSphereRadius;
  96513. };
  96514. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  96515. var shape = impostor.physicsBody.shapes[0];
  96516. result.x = shape.halfExtents.x * 2;
  96517. result.y = shape.halfExtents.y * 2;
  96518. result.z = shape.halfExtents.z * 2;
  96519. };
  96520. CannonJSPlugin.prototype.dispose = function () {
  96521. };
  96522. CannonJSPlugin.prototype._extendNamespace = function () {
  96523. //this will force cannon to execute at least one step when using interpolation
  96524. var step_tmp1 = new this.BJSCANNON.Vec3();
  96525. var Engine = this.BJSCANNON;
  96526. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  96527. maxSubSteps = maxSubSteps || 10;
  96528. timeSinceLastCalled = timeSinceLastCalled || 0;
  96529. if (timeSinceLastCalled === 0) {
  96530. this.internalStep(dt);
  96531. this.time += dt;
  96532. }
  96533. else {
  96534. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  96535. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  96536. var t0 = performance.now();
  96537. for (var i = 0; i !== internalSteps; i++) {
  96538. this.internalStep(dt);
  96539. if (performance.now() - t0 > dt * 1000) {
  96540. break;
  96541. }
  96542. }
  96543. this.time += timeSinceLastCalled;
  96544. var h = this.time % dt;
  96545. var h_div_dt = h / dt;
  96546. var interpvelo = step_tmp1;
  96547. var bodies = this.bodies;
  96548. for (var j = 0; j !== bodies.length; j++) {
  96549. var b = bodies[j];
  96550. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  96551. b.position.vsub(b.previousPosition, interpvelo);
  96552. interpvelo.scale(h_div_dt, interpvelo);
  96553. b.position.vadd(interpvelo, b.interpolatedPosition);
  96554. }
  96555. else {
  96556. b.interpolatedPosition.copy(b.position);
  96557. b.interpolatedQuaternion.copy(b.quaternion);
  96558. }
  96559. }
  96560. }
  96561. };
  96562. };
  96563. return CannonJSPlugin;
  96564. }());
  96565. BABYLON.CannonJSPlugin = CannonJSPlugin;
  96566. })(BABYLON || (BABYLON = {}));
  96567. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  96568. var BABYLON;
  96569. (function (BABYLON) {
  96570. /** @hidden */
  96571. var OimoJSPlugin = /** @class */ (function () {
  96572. function OimoJSPlugin(iterations) {
  96573. this.name = "OimoJSPlugin";
  96574. this._tmpImpostorsArray = [];
  96575. this._tmpPositionVector = BABYLON.Vector3.Zero();
  96576. this.BJSOIMO = OIMO;
  96577. this.world = new this.BJSOIMO.World({
  96578. iterations: iterations
  96579. });
  96580. this.world.clear();
  96581. }
  96582. OimoJSPlugin.prototype.setGravity = function (gravity) {
  96583. this.world.gravity.copy(gravity);
  96584. };
  96585. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  96586. this.world.timeStep = timeStep;
  96587. };
  96588. OimoJSPlugin.prototype.getTimeStep = function () {
  96589. return this.world.timeStep;
  96590. };
  96591. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  96592. var _this = this;
  96593. impostors.forEach(function (impostor) {
  96594. impostor.beforeStep();
  96595. });
  96596. this.world.step();
  96597. impostors.forEach(function (impostor) {
  96598. impostor.afterStep();
  96599. //update the ordered impostors array
  96600. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  96601. });
  96602. //check for collisions
  96603. var contact = this.world.contacts;
  96604. while (contact !== null) {
  96605. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  96606. contact = contact.next;
  96607. continue;
  96608. }
  96609. //is this body colliding with any other? get the impostor
  96610. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  96611. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  96612. if (!mainImpostor || !collidingImpostor) {
  96613. contact = contact.next;
  96614. continue;
  96615. }
  96616. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  96617. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  96618. contact = contact.next;
  96619. }
  96620. };
  96621. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  96622. var mass = impostor.physicsBody.mass;
  96623. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  96624. };
  96625. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  96626. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  96627. this.applyImpulse(impostor, force, contactPoint);
  96628. };
  96629. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  96630. var _this = this;
  96631. //parent-child relationship. Does this impostor has a parent impostor?
  96632. if (impostor.parent) {
  96633. if (impostor.physicsBody) {
  96634. this.removePhysicsBody(impostor);
  96635. //TODO is that needed?
  96636. impostor.forceUpdate();
  96637. }
  96638. return;
  96639. }
  96640. if (impostor.isBodyInitRequired()) {
  96641. var bodyConfig = {
  96642. name: impostor.uniqueId,
  96643. //Oimo must have mass, also for static objects.
  96644. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  96645. size: [],
  96646. type: [],
  96647. pos: [],
  96648. posShape: [],
  96649. rot: [],
  96650. rotShape: [],
  96651. move: impostor.getParam("mass") !== 0,
  96652. density: impostor.getParam("mass"),
  96653. friction: impostor.getParam("friction"),
  96654. restitution: impostor.getParam("restitution"),
  96655. //Supporting older versions of Oimo
  96656. world: this.world
  96657. };
  96658. var impostors = [impostor];
  96659. var addToArray = function (parent) {
  96660. if (!parent.getChildMeshes)
  96661. return;
  96662. parent.getChildMeshes().forEach(function (m) {
  96663. if (m.physicsImpostor) {
  96664. impostors.push(m.physicsImpostor);
  96665. //m.physicsImpostor._init();
  96666. }
  96667. });
  96668. };
  96669. addToArray(impostor.object);
  96670. var checkWithEpsilon_1 = function (value) {
  96671. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  96672. };
  96673. var globalQuaternion_1 = new BABYLON.Quaternion();
  96674. impostors.forEach(function (i) {
  96675. if (!i.object.rotationQuaternion) {
  96676. return;
  96677. }
  96678. //get the correct bounding box
  96679. var oldQuaternion = i.object.rotationQuaternion;
  96680. globalQuaternion_1 = oldQuaternion.clone();
  96681. var rot = oldQuaternion.toEulerAngles();
  96682. var extendSize = i.getObjectExtendSize();
  96683. var radToDeg = 57.295779513082320876;
  96684. if (i === impostor) {
  96685. var center = impostor.getObjectCenter();
  96686. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  96687. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  96688. //Can also use Array.prototype.push.apply
  96689. bodyConfig.pos.push(center.x);
  96690. bodyConfig.pos.push(center.y);
  96691. bodyConfig.pos.push(center.z);
  96692. bodyConfig.posShape.push(0, 0, 0);
  96693. //tmp solution
  96694. bodyConfig.rot.push(0);
  96695. bodyConfig.rot.push(0);
  96696. bodyConfig.rot.push(0);
  96697. bodyConfig.rotShape.push(0, 0, 0);
  96698. }
  96699. else {
  96700. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  96701. bodyConfig.posShape.push(localPosition.x);
  96702. bodyConfig.posShape.push(localPosition.y);
  96703. bodyConfig.posShape.push(localPosition.z);
  96704. bodyConfig.pos.push(0, 0, 0);
  96705. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  96706. bodyConfig.rot.push(0);
  96707. bodyConfig.rot.push(0);
  96708. bodyConfig.rot.push(0);
  96709. bodyConfig.rotShape.push(rot.x * radToDeg);
  96710. bodyConfig.rotShape.push(rot.y * radToDeg);
  96711. bodyConfig.rotShape.push(rot.z * radToDeg);
  96712. }
  96713. // register mesh
  96714. switch (i.type) {
  96715. case BABYLON.PhysicsImpostor.ParticleImpostor:
  96716. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  96717. case BABYLON.PhysicsImpostor.SphereImpostor:
  96718. var radiusX = extendSize.x;
  96719. var radiusY = extendSize.y;
  96720. var radiusZ = extendSize.z;
  96721. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  96722. bodyConfig.type.push('sphere');
  96723. //due to the way oimo works with compounds, add 3 times
  96724. bodyConfig.size.push(size);
  96725. bodyConfig.size.push(size);
  96726. bodyConfig.size.push(size);
  96727. break;
  96728. case BABYLON.PhysicsImpostor.CylinderImpostor:
  96729. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  96730. var sizeY = checkWithEpsilon_1(extendSize.y);
  96731. bodyConfig.type.push('cylinder');
  96732. bodyConfig.size.push(sizeX);
  96733. bodyConfig.size.push(sizeY);
  96734. //due to the way oimo works with compounds, add one more value.
  96735. bodyConfig.size.push(sizeY);
  96736. break;
  96737. case BABYLON.PhysicsImpostor.PlaneImpostor:
  96738. case BABYLON.PhysicsImpostor.BoxImpostor:
  96739. default:
  96740. var sizeX = checkWithEpsilon_1(extendSize.x);
  96741. var sizeY = checkWithEpsilon_1(extendSize.y);
  96742. var sizeZ = checkWithEpsilon_1(extendSize.z);
  96743. bodyConfig.type.push('box');
  96744. //if (i === impostor) {
  96745. bodyConfig.size.push(sizeX);
  96746. bodyConfig.size.push(sizeY);
  96747. bodyConfig.size.push(sizeZ);
  96748. //} else {
  96749. // bodyConfig.size.push(0,0,0);
  96750. //}
  96751. break;
  96752. }
  96753. //actually not needed, but hey...
  96754. i.object.rotationQuaternion = oldQuaternion;
  96755. });
  96756. impostor.physicsBody = this.world.add(bodyConfig);
  96757. // set the quaternion, ignoring the previously defined (euler) rotation
  96758. impostor.physicsBody.resetQuaternion(globalQuaternion_1);
  96759. // update with delta 0, so the body will reveive the new rotation.
  96760. impostor.physicsBody.updatePosition(0);
  96761. }
  96762. else {
  96763. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  96764. }
  96765. impostor.setDeltaPosition(this._tmpPositionVector);
  96766. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  96767. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  96768. };
  96769. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  96770. //impostor.physicsBody.dispose();
  96771. //Same as : (older oimo versions)
  96772. this.world.removeRigidBody(impostor.physicsBody);
  96773. };
  96774. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  96775. var mainBody = impostorJoint.mainImpostor.physicsBody;
  96776. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  96777. if (!mainBody || !connectedBody) {
  96778. return;
  96779. }
  96780. var jointData = impostorJoint.joint.jointData;
  96781. var options = jointData.nativeParams || {};
  96782. var type;
  96783. var nativeJointData = {
  96784. body1: mainBody,
  96785. body2: connectedBody,
  96786. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  96787. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  96788. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  96789. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  96790. min: options.min,
  96791. max: options.max,
  96792. collision: options.collision || jointData.collision,
  96793. spring: options.spring,
  96794. //supporting older version of Oimo
  96795. world: this.world
  96796. };
  96797. switch (impostorJoint.joint.type) {
  96798. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  96799. type = "jointBall";
  96800. break;
  96801. case BABYLON.PhysicsJoint.SpringJoint:
  96802. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  96803. var springData = jointData;
  96804. nativeJointData.min = springData.length || nativeJointData.min;
  96805. //Max should also be set, just make sure it is at least min
  96806. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  96807. case BABYLON.PhysicsJoint.DistanceJoint:
  96808. type = "jointDistance";
  96809. nativeJointData.max = jointData.maxDistance;
  96810. break;
  96811. case BABYLON.PhysicsJoint.PrismaticJoint:
  96812. type = "jointPrisme";
  96813. break;
  96814. case BABYLON.PhysicsJoint.SliderJoint:
  96815. type = "jointSlide";
  96816. break;
  96817. case BABYLON.PhysicsJoint.WheelJoint:
  96818. type = "jointWheel";
  96819. break;
  96820. case BABYLON.PhysicsJoint.HingeJoint:
  96821. default:
  96822. type = "jointHinge";
  96823. break;
  96824. }
  96825. nativeJointData.type = type;
  96826. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  96827. };
  96828. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  96829. //Bug in Oimo prevents us from disposing a joint in the playground
  96830. //joint.joint.physicsJoint.dispose();
  96831. //So we will bruteforce it!
  96832. try {
  96833. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  96834. }
  96835. catch (e) {
  96836. BABYLON.Tools.Warn(e);
  96837. }
  96838. };
  96839. OimoJSPlugin.prototype.isSupported = function () {
  96840. return this.BJSOIMO !== undefined;
  96841. };
  96842. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  96843. if (!impostor.physicsBody.sleeping) {
  96844. //TODO check that
  96845. /*if (impostor.physicsBody.shapes.next) {
  96846. var parentShape = this._getLastShape(impostor.physicsBody);
  96847. impostor.object.position.copyFrom(parentShape.position);
  96848. console.log(parentShape.position);
  96849. } else {*/
  96850. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  96851. //}
  96852. if (impostor.object.rotationQuaternion) {
  96853. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  96854. }
  96855. }
  96856. };
  96857. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  96858. var body = impostor.physicsBody;
  96859. body.position.copy(newPosition);
  96860. body.orientation.copy(newRotation);
  96861. body.syncShapes();
  96862. body.awake();
  96863. };
  96864. /*private _getLastShape(body: any): any {
  96865. var lastShape = body.shapes;
  96866. while (lastShape.next) {
  96867. lastShape = lastShape.next;
  96868. }
  96869. return lastShape;
  96870. }*/
  96871. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  96872. impostor.physicsBody.linearVelocity.copy(velocity);
  96873. };
  96874. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  96875. impostor.physicsBody.angularVelocity.copy(velocity);
  96876. };
  96877. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  96878. var v = impostor.physicsBody.linearVelocity;
  96879. if (!v) {
  96880. return null;
  96881. }
  96882. return new BABYLON.Vector3(v.x, v.y, v.z);
  96883. };
  96884. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  96885. var v = impostor.physicsBody.angularVelocity;
  96886. if (!v) {
  96887. return null;
  96888. }
  96889. return new BABYLON.Vector3(v.x, v.y, v.z);
  96890. };
  96891. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  96892. var staticBody = mass === 0;
  96893. //this will actually set the body's density and not its mass.
  96894. //But this is how oimo treats the mass variable.
  96895. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  96896. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  96897. };
  96898. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  96899. return impostor.physicsBody.shapes.density;
  96900. };
  96901. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  96902. return impostor.physicsBody.shapes.friction;
  96903. };
  96904. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  96905. impostor.physicsBody.shapes.friction = friction;
  96906. };
  96907. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  96908. return impostor.physicsBody.shapes.restitution;
  96909. };
  96910. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  96911. impostor.physicsBody.shapes.restitution = restitution;
  96912. };
  96913. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  96914. impostor.physicsBody.sleep();
  96915. };
  96916. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  96917. impostor.physicsBody.awake();
  96918. };
  96919. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  96920. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  96921. if (minDistance !== void 0) {
  96922. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  96923. }
  96924. };
  96925. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  96926. //TODO separate rotational and transational motors.
  96927. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  96928. if (motor) {
  96929. motor.setMotor(speed, maxForce);
  96930. }
  96931. };
  96932. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  96933. //TODO separate rotational and transational motors.
  96934. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  96935. if (motor) {
  96936. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  96937. }
  96938. };
  96939. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  96940. var body = impostor.physicsBody;
  96941. mesh.position.x = body.position.x;
  96942. mesh.position.y = body.position.y;
  96943. mesh.position.z = body.position.z;
  96944. if (mesh.rotationQuaternion) {
  96945. mesh.rotationQuaternion.x = body.orientation.x;
  96946. mesh.rotationQuaternion.y = body.orientation.y;
  96947. mesh.rotationQuaternion.z = body.orientation.z;
  96948. mesh.rotationQuaternion.w = body.orientation.s;
  96949. }
  96950. };
  96951. OimoJSPlugin.prototype.getRadius = function (impostor) {
  96952. return impostor.physicsBody.shapes.radius;
  96953. };
  96954. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  96955. var shape = impostor.physicsBody.shapes;
  96956. result.x = shape.halfWidth * 2;
  96957. result.y = shape.halfHeight * 2;
  96958. result.z = shape.halfDepth * 2;
  96959. };
  96960. OimoJSPlugin.prototype.dispose = function () {
  96961. this.world.clear();
  96962. };
  96963. return OimoJSPlugin;
  96964. }());
  96965. BABYLON.OimoJSPlugin = OimoJSPlugin;
  96966. })(BABYLON || (BABYLON = {}));
  96967. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  96968. var BABYLON;
  96969. (function (BABYLON) {
  96970. /**
  96971. * Gets the current physics engine
  96972. * @returns a IPhysicsEngine or null if none attached
  96973. */
  96974. BABYLON.Scene.prototype.getPhysicsEngine = function () {
  96975. return this._physicsEngine;
  96976. };
  96977. /**
  96978. * Enables physics to the current scene
  96979. * @param gravity defines the scene's gravity for the physics engine
  96980. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  96981. * @return a boolean indicating if the physics engine was initialized
  96982. */
  96983. BABYLON.Scene.prototype.enablePhysics = function (gravity, plugin) {
  96984. if (gravity === void 0) { gravity = null; }
  96985. if (this._physicsEngine) {
  96986. return true;
  96987. }
  96988. // Register the component to the scene
  96989. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_PHYSICSENGINE);
  96990. if (!component) {
  96991. component = new PhysicsEngineSceneComponent(this);
  96992. this._addComponent(component);
  96993. }
  96994. try {
  96995. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  96996. return true;
  96997. }
  96998. catch (e) {
  96999. BABYLON.Tools.Error(e.message);
  97000. return false;
  97001. }
  97002. };
  97003. /**
  97004. * Disables and disposes the physics engine associated with the scene
  97005. */
  97006. BABYLON.Scene.prototype.disablePhysicsEngine = function () {
  97007. if (!this._physicsEngine) {
  97008. return;
  97009. }
  97010. this._physicsEngine.dispose();
  97011. this._physicsEngine = null;
  97012. };
  97013. /**
  97014. * Gets a boolean indicating if there is an active physics engine
  97015. * @returns a boolean indicating if there is an active physics engine
  97016. */
  97017. BABYLON.Scene.prototype.isPhysicsEnabled = function () {
  97018. return this._physicsEngine !== undefined;
  97019. };
  97020. /**
  97021. * Deletes a physics compound impostor
  97022. * @param compound defines the compound to delete
  97023. */
  97024. BABYLON.Scene.prototype.deleteCompoundImpostor = function (compound) {
  97025. var mesh = compound.parts[0].mesh;
  97026. if (mesh.physicsImpostor) {
  97027. mesh.physicsImpostor.dispose( /*true*/);
  97028. mesh.physicsImpostor = null;
  97029. }
  97030. };
  97031. /** @hidden */
  97032. BABYLON.Scene.prototype._advancePhysicsEngineStep = function (step) {
  97033. if (this._physicsEngine) {
  97034. this.onBeforePhysicsObservable.notifyObservers(this);
  97035. this._physicsEngine._step(step / 1000);
  97036. this.onAfterPhysicsObservable.notifyObservers(this);
  97037. }
  97038. };
  97039. Object.defineProperty(BABYLON.AbstractMesh.prototype, "physicsImpostor", {
  97040. get: function () {
  97041. return this._physicsImpostor;
  97042. },
  97043. set: function (value) {
  97044. var _this = this;
  97045. if (this._physicsImpostor === value) {
  97046. return;
  97047. }
  97048. if (this._disposePhysicsObserver) {
  97049. this.onDisposeObservable.remove(this._disposePhysicsObserver);
  97050. }
  97051. this._physicsImpostor = value;
  97052. if (value) {
  97053. this._disposePhysicsObserver = this.onDisposeObservable.add(function () {
  97054. // Physics
  97055. if (_this.physicsImpostor) {
  97056. _this.physicsImpostor.dispose( /*!doNotRecurse*/);
  97057. _this.physicsImpostor = null;
  97058. }
  97059. });
  97060. }
  97061. },
  97062. enumerable: true,
  97063. configurable: true
  97064. });
  97065. /**
  97066. * Gets the current physics impostor
  97067. * @see http://doc.babylonjs.com/features/physics_engine
  97068. * @returns a physics impostor or null
  97069. */
  97070. BABYLON.AbstractMesh.prototype.getPhysicsImpostor = function () {
  97071. return this.physicsImpostor;
  97072. };
  97073. /**
  97074. * Apply a physic impulse to the mesh
  97075. * @param force defines the force to apply
  97076. * @param contactPoint defines where to apply the force
  97077. * @returns the current mesh
  97078. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  97079. */
  97080. BABYLON.AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  97081. if (!this.physicsImpostor) {
  97082. return this;
  97083. }
  97084. this.physicsImpostor.applyImpulse(force, contactPoint);
  97085. return this;
  97086. };
  97087. /**
  97088. * Creates a physic joint between two meshes
  97089. * @param otherMesh defines the other mesh to use
  97090. * @param pivot1 defines the pivot to use on this mesh
  97091. * @param pivot2 defines the pivot to use on the other mesh
  97092. * @param options defines additional options (can be plugin dependent)
  97093. * @returns the current mesh
  97094. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  97095. */
  97096. BABYLON.AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  97097. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  97098. return this;
  97099. }
  97100. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  97101. mainPivot: pivot1,
  97102. connectedPivot: pivot2,
  97103. nativeParams: options
  97104. });
  97105. return this;
  97106. };
  97107. /**
  97108. * Defines the physics engine scene component responsible to manage a physics engine
  97109. */
  97110. var PhysicsEngineSceneComponent = /** @class */ (function () {
  97111. /**
  97112. * Creates a new instance of the component for the given scene
  97113. * @param scene Defines the scene to register the component in
  97114. */
  97115. function PhysicsEngineSceneComponent(scene) {
  97116. var _this = this;
  97117. /**
  97118. * The component name helpful to identify the component in the list of scene components.
  97119. */
  97120. this.name = BABYLON.SceneComponentConstants.NAME_PHYSICSENGINE;
  97121. this.scene = scene;
  97122. this.scene.onBeforePhysicsObservable = new BABYLON.Observable();
  97123. this.scene.onAfterPhysicsObservable = new BABYLON.Observable();
  97124. // Replace the function used to get the deterministic frame time
  97125. this.scene.getDeterministicFrameTime = function () {
  97126. if (_this.scene._physicsEngine) {
  97127. return _this.scene._physicsEngine.getTimeStep() * 1000;
  97128. }
  97129. return 1000.0 / 60.0;
  97130. };
  97131. }
  97132. /**
  97133. * Registers the component in a given scene
  97134. */
  97135. PhysicsEngineSceneComponent.prototype.register = function () {
  97136. };
  97137. /**
  97138. * Rebuilds the elements related to this component in case of
  97139. * context lost for instance.
  97140. */
  97141. PhysicsEngineSceneComponent.prototype.rebuild = function () {
  97142. // Nothing to do for this component
  97143. };
  97144. /**
  97145. * Disposes the component and the associated ressources
  97146. */
  97147. PhysicsEngineSceneComponent.prototype.dispose = function () {
  97148. this.scene.onBeforePhysicsObservable.clear();
  97149. this.scene.onAfterPhysicsObservable.clear();
  97150. if (this.scene._physicsEngine) {
  97151. this.scene.disablePhysicsEngine();
  97152. }
  97153. };
  97154. return PhysicsEngineSceneComponent;
  97155. }());
  97156. BABYLON.PhysicsEngineSceneComponent = PhysicsEngineSceneComponent;
  97157. })(BABYLON || (BABYLON = {}));
  97158. //# sourceMappingURL=babylon.physicsEngineComponent.js.map
  97159. var BABYLON;
  97160. (function (BABYLON) {
  97161. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  97162. // All values and structures referenced from:
  97163. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  97164. var DDS_MAGIC = 0x20534444;
  97165. var
  97166. //DDSD_CAPS = 0x1,
  97167. //DDSD_HEIGHT = 0x2,
  97168. //DDSD_WIDTH = 0x4,
  97169. //DDSD_PITCH = 0x8,
  97170. //DDSD_PIXELFORMAT = 0x1000,
  97171. DDSD_MIPMAPCOUNT = 0x20000;
  97172. //DDSD_LINEARSIZE = 0x80000,
  97173. //DDSD_DEPTH = 0x800000;
  97174. // var DDSCAPS_COMPLEX = 0x8,
  97175. // DDSCAPS_MIPMAP = 0x400000,
  97176. // DDSCAPS_TEXTURE = 0x1000;
  97177. var DDSCAPS2_CUBEMAP = 0x200;
  97178. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  97179. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  97180. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  97181. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  97182. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  97183. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  97184. // DDSCAPS2_VOLUME = 0x200000;
  97185. var
  97186. //DDPF_ALPHAPIXELS = 0x1,
  97187. //DDPF_ALPHA = 0x2,
  97188. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  97189. //DDPF_YUV = 0x200,
  97190. DDPF_LUMINANCE = 0x20000;
  97191. function FourCCToInt32(value) {
  97192. return value.charCodeAt(0) +
  97193. (value.charCodeAt(1) << 8) +
  97194. (value.charCodeAt(2) << 16) +
  97195. (value.charCodeAt(3) << 24);
  97196. }
  97197. function Int32ToFourCC(value) {
  97198. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  97199. }
  97200. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  97201. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  97202. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  97203. var FOURCC_DX10 = FourCCToInt32("DX10");
  97204. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  97205. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  97206. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  97207. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  97208. var headerLengthInt = 31; // The header length in 32 bit ints
  97209. // Offsets into the header array
  97210. var off_magic = 0;
  97211. var off_size = 1;
  97212. var off_flags = 2;
  97213. var off_height = 3;
  97214. var off_width = 4;
  97215. var off_mipmapCount = 7;
  97216. var off_pfFlags = 20;
  97217. var off_pfFourCC = 21;
  97218. var off_RGBbpp = 22;
  97219. var off_RMask = 23;
  97220. var off_GMask = 24;
  97221. var off_BMask = 25;
  97222. var off_AMask = 26;
  97223. // var off_caps1 = 27;
  97224. var off_caps2 = 28;
  97225. // var off_caps3 = 29;
  97226. // var off_caps4 = 30;
  97227. var off_dxgiFormat = 32;
  97228. ;
  97229. /**
  97230. * Class used to provide DDS decompression tools
  97231. */
  97232. var DDSTools = /** @class */ (function () {
  97233. function DDSTools() {
  97234. }
  97235. /**
  97236. * Gets DDS information from an array buffer
  97237. * @param arrayBuffer defines the array buffer to read data from
  97238. * @returns the DDS information
  97239. */
  97240. DDSTools.GetDDSInfo = function (arrayBuffer) {
  97241. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  97242. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  97243. var mipmapCount = 1;
  97244. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  97245. mipmapCount = Math.max(1, header[off_mipmapCount]);
  97246. }
  97247. var fourCC = header[off_pfFourCC];
  97248. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  97249. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  97250. switch (fourCC) {
  97251. case FOURCC_D3DFMT_R16G16B16A16F:
  97252. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  97253. break;
  97254. case FOURCC_D3DFMT_R32G32B32A32F:
  97255. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  97256. break;
  97257. case FOURCC_DX10:
  97258. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  97259. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  97260. break;
  97261. }
  97262. }
  97263. return {
  97264. width: header[off_width],
  97265. height: header[off_height],
  97266. mipmapCount: mipmapCount,
  97267. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  97268. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  97269. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  97270. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  97271. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  97272. dxgiFormat: dxgiFormat,
  97273. textureType: textureType
  97274. };
  97275. };
  97276. DDSTools._ToHalfFloat = function (value) {
  97277. if (!DDSTools._FloatView) {
  97278. DDSTools._FloatView = new Float32Array(1);
  97279. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  97280. }
  97281. DDSTools._FloatView[0] = value;
  97282. var x = DDSTools._Int32View[0];
  97283. var bits = (x >> 16) & 0x8000; /* Get the sign */
  97284. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  97285. var e = (x >> 23) & 0xff; /* Using int is faster here */
  97286. /* If zero, or denormal, or exponent underflows too much for a denormal
  97287. * half, return signed zero. */
  97288. if (e < 103) {
  97289. return bits;
  97290. }
  97291. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  97292. if (e > 142) {
  97293. bits |= 0x7c00;
  97294. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  97295. * not Inf, so make sure we set one mantissa bit too. */
  97296. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  97297. return bits;
  97298. }
  97299. /* If exponent underflows but not too much, return a denormal */
  97300. if (e < 113) {
  97301. m |= 0x0800;
  97302. /* Extra rounding may overflow and set mantissa to 0 and exponent
  97303. * to 1, which is OK. */
  97304. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  97305. return bits;
  97306. }
  97307. bits |= ((e - 112) << 10) | (m >> 1);
  97308. bits += m & 1;
  97309. return bits;
  97310. };
  97311. DDSTools._FromHalfFloat = function (value) {
  97312. var s = (value & 0x8000) >> 15;
  97313. var e = (value & 0x7C00) >> 10;
  97314. var f = value & 0x03FF;
  97315. if (e === 0) {
  97316. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  97317. }
  97318. else if (e == 0x1F) {
  97319. return f ? NaN : ((s ? -1 : 1) * Infinity);
  97320. }
  97321. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  97322. };
  97323. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  97324. var destArray = new Float32Array(dataLength);
  97325. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  97326. var index = 0;
  97327. for (var y = 0; y < height; y++) {
  97328. for (var x = 0; x < width; x++) {
  97329. var srcPos = (x + y * width) * 4;
  97330. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  97331. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  97332. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  97333. if (DDSTools.StoreLODInAlphaChannel) {
  97334. destArray[index + 3] = lod;
  97335. }
  97336. else {
  97337. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  97338. }
  97339. index += 4;
  97340. }
  97341. }
  97342. return destArray;
  97343. };
  97344. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  97345. if (DDSTools.StoreLODInAlphaChannel) {
  97346. var destArray = new Uint16Array(dataLength);
  97347. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  97348. var index = 0;
  97349. for (var y = 0; y < height; y++) {
  97350. for (var x = 0; x < width; x++) {
  97351. var srcPos = (x + y * width) * 4;
  97352. destArray[index] = srcData[srcPos];
  97353. destArray[index + 1] = srcData[srcPos + 1];
  97354. destArray[index + 2] = srcData[srcPos + 2];
  97355. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  97356. index += 4;
  97357. }
  97358. }
  97359. return destArray;
  97360. }
  97361. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  97362. };
  97363. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  97364. if (DDSTools.StoreLODInAlphaChannel) {
  97365. var destArray = new Float32Array(dataLength);
  97366. var srcData = new Float32Array(arrayBuffer, dataOffset);
  97367. var index = 0;
  97368. for (var y = 0; y < height; y++) {
  97369. for (var x = 0; x < width; x++) {
  97370. var srcPos = (x + y * width) * 4;
  97371. destArray[index] = srcData[srcPos];
  97372. destArray[index + 1] = srcData[srcPos + 1];
  97373. destArray[index + 2] = srcData[srcPos + 2];
  97374. destArray[index + 3] = lod;
  97375. index += 4;
  97376. }
  97377. }
  97378. return destArray;
  97379. }
  97380. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  97381. };
  97382. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  97383. var destArray = new Uint8Array(dataLength);
  97384. var srcData = new Float32Array(arrayBuffer, dataOffset);
  97385. var index = 0;
  97386. for (var y = 0; y < height; y++) {
  97387. for (var x = 0; x < width; x++) {
  97388. var srcPos = (x + y * width) * 4;
  97389. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  97390. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  97391. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  97392. if (DDSTools.StoreLODInAlphaChannel) {
  97393. destArray[index + 3] = lod;
  97394. }
  97395. else {
  97396. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  97397. }
  97398. index += 4;
  97399. }
  97400. }
  97401. return destArray;
  97402. };
  97403. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  97404. var destArray = new Uint8Array(dataLength);
  97405. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  97406. var index = 0;
  97407. for (var y = 0; y < height; y++) {
  97408. for (var x = 0; x < width; x++) {
  97409. var srcPos = (x + y * width) * 4;
  97410. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  97411. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  97412. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  97413. if (DDSTools.StoreLODInAlphaChannel) {
  97414. destArray[index + 3] = lod;
  97415. }
  97416. else {
  97417. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  97418. }
  97419. index += 4;
  97420. }
  97421. }
  97422. return destArray;
  97423. };
  97424. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  97425. var byteArray = new Uint8Array(dataLength);
  97426. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  97427. var index = 0;
  97428. for (var y = 0; y < height; y++) {
  97429. for (var x = 0; x < width; x++) {
  97430. var srcPos = (x + y * width) * 4;
  97431. byteArray[index] = srcData[srcPos + rOffset];
  97432. byteArray[index + 1] = srcData[srcPos + gOffset];
  97433. byteArray[index + 2] = srcData[srcPos + bOffset];
  97434. byteArray[index + 3] = srcData[srcPos + aOffset];
  97435. index += 4;
  97436. }
  97437. }
  97438. return byteArray;
  97439. };
  97440. DDSTools._ExtractLongWordOrder = function (value) {
  97441. if (value === 0 || value === 255 || value === -16777216) {
  97442. return 0;
  97443. }
  97444. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  97445. };
  97446. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  97447. var byteArray = new Uint8Array(dataLength);
  97448. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  97449. var index = 0;
  97450. for (var y = 0; y < height; y++) {
  97451. for (var x = 0; x < width; x++) {
  97452. var srcPos = (x + y * width) * 3;
  97453. byteArray[index] = srcData[srcPos + rOffset];
  97454. byteArray[index + 1] = srcData[srcPos + gOffset];
  97455. byteArray[index + 2] = srcData[srcPos + bOffset];
  97456. index += 3;
  97457. }
  97458. }
  97459. return byteArray;
  97460. };
  97461. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  97462. var byteArray = new Uint8Array(dataLength);
  97463. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  97464. var index = 0;
  97465. for (var y = 0; y < height; y++) {
  97466. for (var x = 0; x < width; x++) {
  97467. var srcPos = (x + y * width);
  97468. byteArray[index] = srcData[srcPos];
  97469. index++;
  97470. }
  97471. }
  97472. return byteArray;
  97473. };
  97474. /**
  97475. * Uploads DDS Levels to a Babylon Texture
  97476. * @hidden
  97477. */
  97478. DDSTools.UploadDDSLevels = function (engine, texture, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  97479. if (lodIndex === void 0) { lodIndex = -1; }
  97480. var sphericalPolynomialFaces = null;
  97481. if (info.sphericalPolynomial) {
  97482. sphericalPolynomialFaces = new Array();
  97483. }
  97484. var ext = engine.getCaps().s3tc;
  97485. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  97486. var fourCC, width, height, dataLength = 0, dataOffset;
  97487. var byteArray, mipmapCount, mip;
  97488. var internalCompressedFormat = 0;
  97489. var blockBytes = 1;
  97490. if (header[off_magic] !== DDS_MAGIC) {
  97491. BABYLON.Tools.Error("Invalid magic number in DDS header");
  97492. return;
  97493. }
  97494. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  97495. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  97496. return;
  97497. }
  97498. if (info.isCompressed && !ext) {
  97499. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  97500. return;
  97501. }
  97502. var bpp = header[off_RGBbpp];
  97503. dataOffset = header[off_size] + 4;
  97504. var computeFormats = false;
  97505. if (info.isFourCC) {
  97506. fourCC = header[off_pfFourCC];
  97507. switch (fourCC) {
  97508. case FOURCC_DXT1:
  97509. blockBytes = 8;
  97510. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  97511. break;
  97512. case FOURCC_DXT3:
  97513. blockBytes = 16;
  97514. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  97515. break;
  97516. case FOURCC_DXT5:
  97517. blockBytes = 16;
  97518. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  97519. break;
  97520. case FOURCC_D3DFMT_R16G16B16A16F:
  97521. computeFormats = true;
  97522. break;
  97523. case FOURCC_D3DFMT_R32G32B32A32F:
  97524. computeFormats = true;
  97525. break;
  97526. case FOURCC_DX10:
  97527. // There is an additionnal header so dataOffset need to be changed
  97528. dataOffset += 5 * 4; // 5 uints
  97529. var supported = false;
  97530. switch (info.dxgiFormat) {
  97531. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  97532. computeFormats = true;
  97533. supported = true;
  97534. break;
  97535. case DXGI_FORMAT_B8G8R8X8_UNORM:
  97536. info.isRGB = true;
  97537. info.isFourCC = false;
  97538. bpp = 32;
  97539. supported = true;
  97540. break;
  97541. }
  97542. if (supported) {
  97543. break;
  97544. }
  97545. default:
  97546. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  97547. return;
  97548. }
  97549. }
  97550. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  97551. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  97552. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  97553. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  97554. if (computeFormats) {
  97555. internalCompressedFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  97556. }
  97557. mipmapCount = 1;
  97558. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  97559. mipmapCount = Math.max(1, header[off_mipmapCount]);
  97560. }
  97561. for (var face = 0; face < faces; face++) {
  97562. width = header[off_width];
  97563. height = header[off_height];
  97564. for (mip = 0; mip < mipmapCount; ++mip) {
  97565. if (lodIndex === -1 || lodIndex === mip) {
  97566. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  97567. var i = (lodIndex === -1) ? mip : 0;
  97568. if (!info.isCompressed && info.isFourCC) {
  97569. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  97570. dataLength = width * height * 4;
  97571. var floatArray = null;
  97572. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  97573. if (bpp === 128) {
  97574. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  97575. if (sphericalPolynomialFaces && i == 0) {
  97576. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  97577. }
  97578. }
  97579. else if (bpp === 64) {
  97580. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  97581. if (sphericalPolynomialFaces && i == 0) {
  97582. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  97583. }
  97584. }
  97585. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  97586. }
  97587. else {
  97588. if (bpp === 128) {
  97589. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  97590. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  97591. if (sphericalPolynomialFaces && i == 0) {
  97592. sphericalPolynomialFaces.push(floatArray);
  97593. }
  97594. }
  97595. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  97596. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  97597. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  97598. if (sphericalPolynomialFaces && i == 0) {
  97599. sphericalPolynomialFaces.push(floatArray);
  97600. }
  97601. }
  97602. else { // 64
  97603. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  97604. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  97605. if (sphericalPolynomialFaces && i == 0) {
  97606. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  97607. }
  97608. }
  97609. }
  97610. if (floatArray) {
  97611. engine._uploadDataToTextureDirectly(texture, floatArray, face, i);
  97612. }
  97613. }
  97614. else if (info.isRGB) {
  97615. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  97616. if (bpp === 24) {
  97617. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGB;
  97618. dataLength = width * height * 3;
  97619. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  97620. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  97621. }
  97622. else { // 32
  97623. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  97624. dataLength = width * height * 4;
  97625. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  97626. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  97627. }
  97628. }
  97629. else if (info.isLuminance) {
  97630. var unpackAlignment = engine._getUnpackAlignement();
  97631. var unpaddedRowSize = width;
  97632. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  97633. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  97634. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  97635. texture.format = BABYLON.Engine.TEXTUREFORMAT_LUMINANCE;
  97636. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  97637. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  97638. }
  97639. else {
  97640. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  97641. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  97642. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  97643. engine._uploadCompressedDataToTextureDirectly(texture, internalCompressedFormat, width, height, byteArray, face, i);
  97644. }
  97645. }
  97646. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  97647. width *= 0.5;
  97648. height *= 0.5;
  97649. width = Math.max(1.0, width);
  97650. height = Math.max(1.0, height);
  97651. }
  97652. if (currentFace !== undefined) {
  97653. // Loading a single face
  97654. break;
  97655. }
  97656. }
  97657. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  97658. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  97659. size: header[off_width],
  97660. right: sphericalPolynomialFaces[0],
  97661. left: sphericalPolynomialFaces[1],
  97662. up: sphericalPolynomialFaces[2],
  97663. down: sphericalPolynomialFaces[3],
  97664. front: sphericalPolynomialFaces[4],
  97665. back: sphericalPolynomialFaces[5],
  97666. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  97667. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  97668. gammaSpace: false,
  97669. });
  97670. }
  97671. else {
  97672. info.sphericalPolynomial = undefined;
  97673. }
  97674. };
  97675. /**
  97676. * Gets or sets a boolean indicating that LOD info is stored in alpha channel (false by default)
  97677. */
  97678. DDSTools.StoreLODInAlphaChannel = false;
  97679. return DDSTools;
  97680. }());
  97681. BABYLON.DDSTools = DDSTools;
  97682. })(BABYLON || (BABYLON = {}));
  97683. //# sourceMappingURL=babylon.dds.js.map
  97684. var BABYLON;
  97685. (function (BABYLON) {
  97686. /**
  97687. * Implementation of the DDS Texture Loader.
  97688. */
  97689. var DDSTextureLoader = /** @class */ (function () {
  97690. function DDSTextureLoader() {
  97691. /**
  97692. * Defines wether the loader supports cascade loading the different faces.
  97693. */
  97694. this.supportCascades = true;
  97695. }
  97696. /**
  97697. * This returns if the loader support the current file information.
  97698. * @param extension defines the file extension of the file being loaded
  97699. * @param textureFormatInUse defines the current compressed format in use iun the engine
  97700. * @param fallback defines the fallback internal texture if any
  97701. * @param isBase64 defines whether the texture is encoded as a base64
  97702. * @param isBuffer defines whether the texture data are stored as a buffer
  97703. * @returns true if the loader can load the specified file
  97704. */
  97705. DDSTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  97706. return extension.indexOf(".dds") === 0;
  97707. };
  97708. /**
  97709. * Transform the url before loading if required.
  97710. * @param rootUrl the url of the texture
  97711. * @param textureFormatInUse defines the current compressed format in use iun the engine
  97712. * @returns the transformed texture
  97713. */
  97714. DDSTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  97715. return rootUrl;
  97716. };
  97717. /**
  97718. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  97719. * @param rootUrl the url of the texture
  97720. * @param textureFormatInUse defines the current compressed format in use iun the engine
  97721. * @returns the fallback texture
  97722. */
  97723. DDSTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  97724. return null;
  97725. };
  97726. /**
  97727. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  97728. * @param data contains the texture data
  97729. * @param texture defines the BabylonJS internal texture
  97730. * @param createPolynomials will be true if polynomials have been requested
  97731. * @param onLoad defines the callback to trigger once the texture is ready
  97732. * @param onError defines the callback to trigger in case of error
  97733. */
  97734. DDSTextureLoader.prototype.loadCubeData = function (imgs, texture, createPolynomials, onLoad, onError) {
  97735. var engine = texture.getEngine();
  97736. var info;
  97737. var loadMipmap = false;
  97738. if (Array.isArray(imgs)) {
  97739. for (var index = 0; index < imgs.length; index++) {
  97740. var data_1 = imgs[index];
  97741. info = BABYLON.DDSTools.GetDDSInfo(data_1);
  97742. texture.width = info.width;
  97743. texture.height = info.height;
  97744. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  97745. engine._unpackFlipY(info.isCompressed);
  97746. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data_1, info, loadMipmap, 6, -1, index);
  97747. if (!info.isFourCC && info.mipmapCount === 1) {
  97748. engine.generateMipMapsForCubemap(texture);
  97749. }
  97750. }
  97751. }
  97752. else {
  97753. var data = imgs;
  97754. info = BABYLON.DDSTools.GetDDSInfo(data);
  97755. texture.width = info.width;
  97756. texture.height = info.height;
  97757. if (createPolynomials) {
  97758. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  97759. }
  97760. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  97761. engine._unpackFlipY(info.isCompressed);
  97762. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data, info, loadMipmap, 6);
  97763. if (!info.isFourCC && info.mipmapCount === 1) {
  97764. engine.generateMipMapsForCubemap(texture);
  97765. }
  97766. }
  97767. engine._setCubeMapTextureParams(loadMipmap);
  97768. texture.isReady = true;
  97769. if (onLoad) {
  97770. onLoad({ isDDS: true, width: texture.width, info: info, data: imgs, texture: texture });
  97771. }
  97772. };
  97773. /**
  97774. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  97775. * @param data contains the texture data
  97776. * @param texture defines the BabylonJS internal texture
  97777. * @param callback defines the method to call once ready to upload
  97778. */
  97779. DDSTextureLoader.prototype.loadData = function (data, texture, callback) {
  97780. var info = BABYLON.DDSTools.GetDDSInfo(data);
  97781. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps && ((info.width >> (info.mipmapCount - 1)) === 1);
  97782. callback(info.width, info.height, loadMipmap, info.isFourCC, function () {
  97783. BABYLON.DDSTools.UploadDDSLevels(texture.getEngine(), texture, data, info, loadMipmap, 1);
  97784. });
  97785. };
  97786. return DDSTextureLoader;
  97787. }());
  97788. // Register the loader.
  97789. BABYLON.Engine._TextureLoaders.push(new DDSTextureLoader());
  97790. })(BABYLON || (BABYLON = {}));
  97791. //# sourceMappingURL=babylon.ddsTextureLoader.js.map
  97792. var BABYLON;
  97793. (function (BABYLON) {
  97794. /**
  97795. * Based on jsTGALoader - Javascript loader for TGA file
  97796. * By Vincent Thibault
  97797. * @see http://blog.robrowser.com/javascript-tga-loader.html
  97798. */
  97799. var TGATools = /** @class */ (function () {
  97800. function TGATools() {
  97801. }
  97802. /**
  97803. * Gets the header of a TGA file
  97804. * @param data defines the TGA data
  97805. * @returns the header
  97806. */
  97807. TGATools.GetTGAHeader = function (data) {
  97808. var offset = 0;
  97809. var header = {
  97810. id_length: data[offset++],
  97811. colormap_type: data[offset++],
  97812. image_type: data[offset++],
  97813. colormap_index: data[offset++] | data[offset++] << 8,
  97814. colormap_length: data[offset++] | data[offset++] << 8,
  97815. colormap_size: data[offset++],
  97816. origin: [
  97817. data[offset++] | data[offset++] << 8,
  97818. data[offset++] | data[offset++] << 8
  97819. ],
  97820. width: data[offset++] | data[offset++] << 8,
  97821. height: data[offset++] | data[offset++] << 8,
  97822. pixel_size: data[offset++],
  97823. flags: data[offset++]
  97824. };
  97825. return header;
  97826. };
  97827. /**
  97828. * Uploads TGA content to a Babylon Texture
  97829. * @hidden
  97830. */
  97831. TGATools.UploadContent = function (texture, data) {
  97832. // Not enough data to contain header ?
  97833. if (data.length < 19) {
  97834. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  97835. return;
  97836. }
  97837. // Read Header
  97838. var offset = 18;
  97839. var header = TGATools.GetTGAHeader(data);
  97840. // Assume it's a valid Targa file.
  97841. if (header.id_length + offset > data.length) {
  97842. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  97843. return;
  97844. }
  97845. // Skip not needed data
  97846. offset += header.id_length;
  97847. var use_rle = false;
  97848. var use_pal = false;
  97849. var use_grey = false;
  97850. // Get some informations.
  97851. switch (header.image_type) {
  97852. case TGATools._TYPE_RLE_INDEXED:
  97853. use_rle = true;
  97854. case TGATools._TYPE_INDEXED:
  97855. use_pal = true;
  97856. break;
  97857. case TGATools._TYPE_RLE_RGB:
  97858. use_rle = true;
  97859. case TGATools._TYPE_RGB:
  97860. // use_rgb = true;
  97861. break;
  97862. case TGATools._TYPE_RLE_GREY:
  97863. use_rle = true;
  97864. case TGATools._TYPE_GREY:
  97865. use_grey = true;
  97866. break;
  97867. }
  97868. var pixel_data;
  97869. // var numAlphaBits = header.flags & 0xf;
  97870. var pixel_size = header.pixel_size >> 3;
  97871. var pixel_total = header.width * header.height * pixel_size;
  97872. // Read palettes
  97873. var palettes;
  97874. if (use_pal) {
  97875. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  97876. }
  97877. // Read LRE
  97878. if (use_rle) {
  97879. pixel_data = new Uint8Array(pixel_total);
  97880. var c, count, i;
  97881. var localOffset = 0;
  97882. var pixels = new Uint8Array(pixel_size);
  97883. while (offset < pixel_total && localOffset < pixel_total) {
  97884. c = data[offset++];
  97885. count = (c & 0x7f) + 1;
  97886. // RLE pixels
  97887. if (c & 0x80) {
  97888. // Bind pixel tmp array
  97889. for (i = 0; i < pixel_size; ++i) {
  97890. pixels[i] = data[offset++];
  97891. }
  97892. // Copy pixel array
  97893. for (i = 0; i < count; ++i) {
  97894. pixel_data.set(pixels, localOffset + i * pixel_size);
  97895. }
  97896. localOffset += pixel_size * count;
  97897. }
  97898. // Raw pixels
  97899. else {
  97900. count *= pixel_size;
  97901. for (i = 0; i < count; ++i) {
  97902. pixel_data[localOffset + i] = data[offset++];
  97903. }
  97904. localOffset += count;
  97905. }
  97906. }
  97907. }
  97908. // RAW Pixels
  97909. else {
  97910. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  97911. }
  97912. // Load to texture
  97913. var x_start, y_start, x_step, y_step, y_end, x_end;
  97914. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  97915. default:
  97916. case TGATools._ORIGIN_UL:
  97917. x_start = 0;
  97918. x_step = 1;
  97919. x_end = header.width;
  97920. y_start = 0;
  97921. y_step = 1;
  97922. y_end = header.height;
  97923. break;
  97924. case TGATools._ORIGIN_BL:
  97925. x_start = 0;
  97926. x_step = 1;
  97927. x_end = header.width;
  97928. y_start = header.height - 1;
  97929. y_step = -1;
  97930. y_end = -1;
  97931. break;
  97932. case TGATools._ORIGIN_UR:
  97933. x_start = header.width - 1;
  97934. x_step = -1;
  97935. x_end = -1;
  97936. y_start = 0;
  97937. y_step = 1;
  97938. y_end = header.height;
  97939. break;
  97940. case TGATools._ORIGIN_BR:
  97941. x_start = header.width - 1;
  97942. x_step = -1;
  97943. x_end = -1;
  97944. y_start = header.height - 1;
  97945. y_step = -1;
  97946. y_end = -1;
  97947. break;
  97948. }
  97949. // Load the specify method
  97950. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  97951. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  97952. var engine = texture.getEngine();
  97953. engine._uploadDataToTextureDirectly(texture, imageData);
  97954. };
  97955. /** @hidden */
  97956. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  97957. var image = pixel_data, colormap = palettes;
  97958. var width = header.width, height = header.height;
  97959. var color, i = 0, x, y;
  97960. var imageData = new Uint8Array(width * height * 4);
  97961. for (y = y_start; y !== y_end; y += y_step) {
  97962. for (x = x_start; x !== x_end; x += x_step, i++) {
  97963. color = image[i];
  97964. imageData[(x + width * y) * 4 + 3] = 255;
  97965. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  97966. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  97967. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  97968. }
  97969. }
  97970. return imageData;
  97971. };
  97972. /** @hidden */
  97973. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  97974. var image = pixel_data;
  97975. var width = header.width, height = header.height;
  97976. var color, i = 0, x, y;
  97977. var imageData = new Uint8Array(width * height * 4);
  97978. for (y = y_start; y !== y_end; y += y_step) {
  97979. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  97980. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  97981. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  97982. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  97983. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  97984. imageData[(x + width * y) * 4 + 0] = r;
  97985. imageData[(x + width * y) * 4 + 1] = g;
  97986. imageData[(x + width * y) * 4 + 2] = b;
  97987. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  97988. }
  97989. }
  97990. return imageData;
  97991. };
  97992. /** @hidden */
  97993. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  97994. var image = pixel_data;
  97995. var width = header.width, height = header.height;
  97996. var i = 0, x, y;
  97997. var imageData = new Uint8Array(width * height * 4);
  97998. for (y = y_start; y !== y_end; y += y_step) {
  97999. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  98000. imageData[(x + width * y) * 4 + 3] = 255;
  98001. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  98002. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  98003. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  98004. }
  98005. }
  98006. return imageData;
  98007. };
  98008. /** @hidden */
  98009. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  98010. var image = pixel_data;
  98011. var width = header.width, height = header.height;
  98012. var i = 0, x, y;
  98013. var imageData = new Uint8Array(width * height * 4);
  98014. for (y = y_start; y !== y_end; y += y_step) {
  98015. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  98016. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  98017. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  98018. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  98019. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  98020. }
  98021. }
  98022. return imageData;
  98023. };
  98024. /** @hidden */
  98025. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  98026. var image = pixel_data;
  98027. var width = header.width, height = header.height;
  98028. var color, i = 0, x, y;
  98029. var imageData = new Uint8Array(width * height * 4);
  98030. for (y = y_start; y !== y_end; y += y_step) {
  98031. for (x = x_start; x !== x_end; x += x_step, i++) {
  98032. color = image[i];
  98033. imageData[(x + width * y) * 4 + 0] = color;
  98034. imageData[(x + width * y) * 4 + 1] = color;
  98035. imageData[(x + width * y) * 4 + 2] = color;
  98036. imageData[(x + width * y) * 4 + 3] = 255;
  98037. }
  98038. }
  98039. return imageData;
  98040. };
  98041. /** @hidden */
  98042. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  98043. var image = pixel_data;
  98044. var width = header.width, height = header.height;
  98045. var i = 0, x, y;
  98046. var imageData = new Uint8Array(width * height * 4);
  98047. for (y = y_start; y !== y_end; y += y_step) {
  98048. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  98049. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  98050. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  98051. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  98052. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  98053. }
  98054. }
  98055. return imageData;
  98056. };
  98057. //private static _TYPE_NO_DATA = 0;
  98058. TGATools._TYPE_INDEXED = 1;
  98059. TGATools._TYPE_RGB = 2;
  98060. TGATools._TYPE_GREY = 3;
  98061. TGATools._TYPE_RLE_INDEXED = 9;
  98062. TGATools._TYPE_RLE_RGB = 10;
  98063. TGATools._TYPE_RLE_GREY = 11;
  98064. TGATools._ORIGIN_MASK = 0x30;
  98065. TGATools._ORIGIN_SHIFT = 0x04;
  98066. TGATools._ORIGIN_BL = 0x00;
  98067. TGATools._ORIGIN_BR = 0x01;
  98068. TGATools._ORIGIN_UL = 0x02;
  98069. TGATools._ORIGIN_UR = 0x03;
  98070. return TGATools;
  98071. }());
  98072. BABYLON.TGATools = TGATools;
  98073. })(BABYLON || (BABYLON = {}));
  98074. //# sourceMappingURL=babylon.tga.js.map
  98075. var BABYLON;
  98076. (function (BABYLON) {
  98077. /**
  98078. * Implementation of the TGA Texture Loader.
  98079. */
  98080. var TGATextureLoader = /** @class */ (function () {
  98081. function TGATextureLoader() {
  98082. /**
  98083. * Defines wether the loader supports cascade loading the different faces.
  98084. */
  98085. this.supportCascades = false;
  98086. }
  98087. /**
  98088. * This returns if the loader support the current file information.
  98089. * @param extension defines the file extension of the file being loaded
  98090. * @param textureFormatInUse defines the current compressed format in use iun the engine
  98091. * @param fallback defines the fallback internal texture if any
  98092. * @param isBase64 defines whether the texture is encoded as a base64
  98093. * @param isBuffer defines whether the texture data are stored as a buffer
  98094. * @returns true if the loader can load the specified file
  98095. */
  98096. TGATextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  98097. return extension.indexOf(".tga") === 0;
  98098. };
  98099. /**
  98100. * Transform the url before loading if required.
  98101. * @param rootUrl the url of the texture
  98102. * @param textureFormatInUse defines the current compressed format in use iun the engine
  98103. * @returns the transformed texture
  98104. */
  98105. TGATextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  98106. return rootUrl;
  98107. };
  98108. /**
  98109. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  98110. * @param rootUrl the url of the texture
  98111. * @param textureFormatInUse defines the current compressed format in use iun the engine
  98112. * @returns the fallback texture
  98113. */
  98114. TGATextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  98115. return null;
  98116. };
  98117. /**
  98118. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  98119. * @param data contains the texture data
  98120. * @param texture defines the BabylonJS internal texture
  98121. * @param createPolynomials will be true if polynomials have been requested
  98122. * @param onLoad defines the callback to trigger once the texture is ready
  98123. * @param onError defines the callback to trigger in case of error
  98124. */
  98125. TGATextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  98126. throw ".env not supported in Cube.";
  98127. };
  98128. /**
  98129. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  98130. * @param data contains the texture data
  98131. * @param texture defines the BabylonJS internal texture
  98132. * @param callback defines the method to call once ready to upload
  98133. */
  98134. TGATextureLoader.prototype.loadData = function (data, texture, callback) {
  98135. var uintData = new Uint8Array(data);
  98136. var header = BABYLON.TGATools.GetTGAHeader(uintData);
  98137. callback(header.width, header.height, texture.generateMipMaps, false, function () {
  98138. BABYLON.TGATools.UploadContent(texture, uintData);
  98139. });
  98140. };
  98141. return TGATextureLoader;
  98142. }());
  98143. // Register the loader.
  98144. BABYLON.Engine._TextureLoaders.push(new TGATextureLoader());
  98145. })(BABYLON || (BABYLON = {}));
  98146. //# sourceMappingURL=babylon.tgaTextureLoader.js.map
  98147. var BABYLON;
  98148. (function (BABYLON) {
  98149. /**
  98150. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  98151. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  98152. */
  98153. var KhronosTextureContainer = /** @class */ (function () {
  98154. /**
  98155. * Creates a new KhronosTextureContainer
  98156. * @param arrayBuffer contents of the KTX container file
  98157. * @param facesExpected should be either 1 or 6, based whether a cube texture or or
  98158. * @param threeDExpected provision for indicating that data should be a 3D texture, not implemented
  98159. * @param textureArrayExpected provision for indicating that data should be a texture array, not implemented
  98160. */
  98161. function KhronosTextureContainer(
  98162. /** contents of the KTX container file */
  98163. arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  98164. this.arrayBuffer = arrayBuffer;
  98165. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  98166. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  98167. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  98168. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  98169. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  98170. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  98171. BABYLON.Tools.Error("texture missing KTX identifier");
  98172. return;
  98173. }
  98174. // load the reset of the header in native 32 bit int
  98175. var header = new Int32Array(this.arrayBuffer, 12, 13);
  98176. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  98177. var oppositeEndianess = header[0] === 0x01020304;
  98178. // read all the header elements in order they exist in the file, without modification (sans endainness)
  98179. this.glType = oppositeEndianess ? this.switchEndianness(header[1]) : header[1]; // must be 0 for compressed textures
  98180. this.glTypeSize = oppositeEndianess ? this.switchEndianness(header[2]) : header[2]; // must be 1 for compressed textures
  98181. this.glFormat = oppositeEndianess ? this.switchEndianness(header[3]) : header[3]; // must be 0 for compressed textures
  98182. this.glInternalFormat = oppositeEndianess ? this.switchEndianness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  98183. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndianness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  98184. this.pixelWidth = oppositeEndianess ? this.switchEndianness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  98185. this.pixelHeight = oppositeEndianess ? this.switchEndianness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  98186. this.pixelDepth = oppositeEndianess ? this.switchEndianness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  98187. this.numberOfArrayElements = oppositeEndianess ? this.switchEndianness(header[9]) : header[9]; // used for texture arrays
  98188. this.numberOfFaces = oppositeEndianess ? this.switchEndianness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  98189. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndianness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  98190. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndianness(header[12]) : header[12]; // the amount of space after the header for meta-data
  98191. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  98192. if (this.glType !== 0) {
  98193. BABYLON.Tools.Error("only compressed formats currently supported");
  98194. return;
  98195. }
  98196. else {
  98197. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  98198. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  98199. }
  98200. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  98201. BABYLON.Tools.Error("only 2D textures currently supported");
  98202. return;
  98203. }
  98204. if (this.numberOfArrayElements !== 0) {
  98205. BABYLON.Tools.Error("texture arrays not currently supported");
  98206. return;
  98207. }
  98208. if (this.numberOfFaces !== facesExpected) {
  98209. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  98210. return;
  98211. }
  98212. // we now have a completely validated file, so could use existence of loadType as success
  98213. // would need to make this more elaborate & adjust checks above to support more than one load type
  98214. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  98215. }
  98216. //
  98217. /**
  98218. * Revert the endianness of a value.
  98219. * Not as fast hardware based, but will probably never need to use
  98220. * @param val defines the value to convert
  98221. * @returns the new value
  98222. */
  98223. KhronosTextureContainer.prototype.switchEndianness = function (val) {
  98224. return ((val & 0xFF) << 24)
  98225. | ((val & 0xFF00) << 8)
  98226. | ((val >> 8) & 0xFF00)
  98227. | ((val >> 24) & 0xFF);
  98228. };
  98229. /**
  98230. * Uploads KTX content to a Babylon Texture.
  98231. * It is assumed that the texture has already been created & is currently bound
  98232. * @hidden
  98233. */
  98234. KhronosTextureContainer.prototype.uploadLevels = function (texture, loadMipmaps) {
  98235. switch (this.loadType) {
  98236. case KhronosTextureContainer.COMPRESSED_2D:
  98237. this._upload2DCompressedLevels(texture, loadMipmaps);
  98238. break;
  98239. case KhronosTextureContainer.TEX_2D:
  98240. case KhronosTextureContainer.COMPRESSED_3D:
  98241. case KhronosTextureContainer.TEX_3D:
  98242. }
  98243. };
  98244. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (texture, loadMipmaps) {
  98245. // initialize width & height for level 1
  98246. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  98247. var width = this.pixelWidth;
  98248. var height = this.pixelHeight;
  98249. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  98250. for (var level = 0; level < mipmapCount; level++) {
  98251. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  98252. dataOffset += 4; //image data starts from next multiple of 4 offset. Each face refers to same imagesize field above.
  98253. for (var face = 0; face < this.numberOfFaces; face++) {
  98254. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset, imageSize);
  98255. var engine = texture.getEngine();
  98256. engine._uploadCompressedDataToTextureDirectly(texture, this.glInternalFormat, width, height, byteArray, face, level);
  98257. dataOffset += imageSize; // add size of the image for the next face/mipmap
  98258. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  98259. }
  98260. width = Math.max(1.0, width * 0.5);
  98261. height = Math.max(1.0, height * 0.5);
  98262. }
  98263. };
  98264. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  98265. // load types
  98266. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  98267. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  98268. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  98269. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  98270. return KhronosTextureContainer;
  98271. }());
  98272. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  98273. })(BABYLON || (BABYLON = {}));
  98274. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  98275. var BABYLON;
  98276. (function (BABYLON) {
  98277. /**
  98278. * Implementation of the KTX Texture Loader.
  98279. */
  98280. var KTXTextureLoader = /** @class */ (function () {
  98281. function KTXTextureLoader() {
  98282. /**
  98283. * Defines wether the loader supports cascade loading the different faces.
  98284. */
  98285. this.supportCascades = false;
  98286. }
  98287. /**
  98288. * This returns if the loader support the current file information.
  98289. * @param extension defines the file extension of the file being loaded
  98290. * @param textureFormatInUse defines the current compressed format in use iun the engine
  98291. * @param fallback defines the fallback internal texture if any
  98292. * @param isBase64 defines whether the texture is encoded as a base64
  98293. * @param isBuffer defines whether the texture data are stored as a buffer
  98294. * @returns true if the loader can load the specified file
  98295. */
  98296. KTXTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  98297. if (textureFormatInUse && !isBase64 && !fallback && !isBuffer) {
  98298. return true;
  98299. }
  98300. return false;
  98301. };
  98302. /**
  98303. * Transform the url before loading if required.
  98304. * @param rootUrl the url of the texture
  98305. * @param textureFormatInUse defines the current compressed format in use iun the engine
  98306. * @returns the transformed texture
  98307. */
  98308. KTXTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  98309. var lastDot = rootUrl.lastIndexOf('.');
  98310. return (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + textureFormatInUse;
  98311. };
  98312. /**
  98313. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  98314. * @param rootUrl the url of the texture
  98315. * @param textureFormatInUse defines the current compressed format in use iun the engine
  98316. * @returns the fallback texture
  98317. */
  98318. KTXTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  98319. // remove the format appended to the rootUrl in the original createCubeTexture call.
  98320. var exp = new RegExp("" + textureFormatInUse + "$");
  98321. return rootUrl.replace(exp, "");
  98322. };
  98323. /**
  98324. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  98325. * @param data contains the texture data
  98326. * @param texture defines the BabylonJS internal texture
  98327. * @param createPolynomials will be true if polynomials have been requested
  98328. * @param onLoad defines the callback to trigger once the texture is ready
  98329. * @param onError defines the callback to trigger in case of error
  98330. */
  98331. KTXTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  98332. if (Array.isArray(data)) {
  98333. return;
  98334. }
  98335. var engine = texture.getEngine();
  98336. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  98337. var loadMipmap = ktx.numberOfMipmapLevels > 1 && texture.generateMipMaps;
  98338. engine._unpackFlipY(true);
  98339. ktx.uploadLevels(texture, texture.generateMipMaps);
  98340. texture.width = ktx.pixelWidth;
  98341. texture.height = ktx.pixelHeight;
  98342. engine._setCubeMapTextureParams(loadMipmap);
  98343. texture.isReady = true;
  98344. };
  98345. /**
  98346. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  98347. * @param data contains the texture data
  98348. * @param texture defines the BabylonJS internal texture
  98349. * @param callback defines the method to call once ready to upload
  98350. */
  98351. KTXTextureLoader.prototype.loadData = function (data, texture, callback) {
  98352. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  98353. callback(ktx.pixelWidth, ktx.pixelHeight, false, true, function () {
  98354. ktx.uploadLevels(texture, texture.generateMipMaps);
  98355. });
  98356. };
  98357. return KTXTextureLoader;
  98358. }());
  98359. // Register the loader.
  98360. BABYLON.Engine._TextureLoaders.unshift(new KTXTextureLoader());
  98361. })(BABYLON || (BABYLON = {}));
  98362. //# sourceMappingURL=babylon.ktxTextureLoader.js.map
  98363. var BABYLON;
  98364. (function (BABYLON) {
  98365. /**
  98366. * Sets of helpers addressing the serialization and deserialization of environment texture
  98367. * stored in a BabylonJS env file.
  98368. * Those files are usually stored as .env files.
  98369. */
  98370. var EnvironmentTextureTools = /** @class */ (function () {
  98371. function EnvironmentTextureTools() {
  98372. }
  98373. /**
  98374. * Gets the environment info from an env file.
  98375. * @param data The array buffer containing the .env bytes.
  98376. * @returns the environment file info (the json header) if successfully parsed.
  98377. */
  98378. EnvironmentTextureTools.GetEnvInfo = function (data) {
  98379. var dataView = new DataView(data);
  98380. var pos = 0;
  98381. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  98382. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  98383. BABYLON.Tools.Error('Not a babylon environment map');
  98384. return null;
  98385. }
  98386. }
  98387. // Read json manifest - collect characters up to null terminator
  98388. var manifestString = '';
  98389. var charCode = 0x00;
  98390. while ((charCode = dataView.getUint8(pos++))) {
  98391. manifestString += String.fromCharCode(charCode);
  98392. }
  98393. var manifest = JSON.parse(manifestString);
  98394. if (manifest.specular) {
  98395. // Extend the header with the position of the payload.
  98396. manifest.specular.specularDataPosition = pos;
  98397. // Fallback to 0.8 exactly if lodGenerationScale is not defined for backward compatibility.
  98398. manifest.specular.lodGenerationScale = manifest.specular.lodGenerationScale || 0.8;
  98399. }
  98400. return manifest;
  98401. };
  98402. /**
  98403. * Creates an environment texture from a loaded cube texture.
  98404. * @param texture defines the cube texture to convert in env file
  98405. * @return a promise containing the environment data if succesfull.
  98406. */
  98407. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  98408. var _this = this;
  98409. var internalTexture = texture.getInternalTexture();
  98410. if (!internalTexture) {
  98411. return Promise.reject("The cube texture is invalid.");
  98412. }
  98413. if (!texture._prefiltered) {
  98414. return Promise.reject("The cube texture is invalid (not prefiltered).");
  98415. }
  98416. var engine = internalTexture.getEngine();
  98417. if (engine && engine.premultipliedAlpha) {
  98418. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  98419. }
  98420. if (texture.textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  98421. return Promise.reject("The cube texture should allow HDR (Full Float or Half Float).");
  98422. }
  98423. var canvas = engine.getRenderingCanvas();
  98424. if (!canvas) {
  98425. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  98426. }
  98427. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  98428. if (!engine.getCaps().textureFloatRender) {
  98429. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  98430. if (!engine.getCaps().textureHalfFloatRender) {
  98431. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  98432. }
  98433. }
  98434. var cubeWidth = internalTexture.width;
  98435. var hostingScene = new BABYLON.Scene(engine);
  98436. var specularTextures = {};
  98437. var promises = [];
  98438. // Read and collect all mipmaps data from the cube.
  98439. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  98440. mipmapsCount = Math.round(mipmapsCount);
  98441. var _loop_1 = function (i) {
  98442. var faceWidth = Math.pow(2, mipmapsCount - i);
  98443. var _loop_2 = function (face) {
  98444. var data = texture.readPixels(face, i);
  98445. // Creates a temp texture with the face data.
  98446. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  98447. // And rgbdEncode them.
  98448. var promise = new Promise(function (resolve, reject) {
  98449. 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);
  98450. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  98451. rgbdPostProcess.onApply = function (effect) {
  98452. effect._bindTexture("textureSampler", tempTexture);
  98453. };
  98454. // As the process needs to happen on the main canvas, keep track of the current size
  98455. var currentW = engine.getRenderWidth();
  98456. var currentH = engine.getRenderHeight();
  98457. // Set the desired size for the texture
  98458. engine.setSize(faceWidth, faceWidth);
  98459. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  98460. // Reading datas from WebGL
  98461. BABYLON.Tools.ToBlob(canvas, function (blob) {
  98462. var fileReader = new FileReader();
  98463. fileReader.onload = function (event) {
  98464. var arrayBuffer = event.target.result;
  98465. specularTextures[i * 6 + face] = arrayBuffer;
  98466. resolve();
  98467. };
  98468. fileReader.readAsArrayBuffer(blob);
  98469. });
  98470. // Reapply the previous canvas size
  98471. engine.setSize(currentW, currentH);
  98472. });
  98473. });
  98474. promises.push(promise);
  98475. };
  98476. // All faces of the cube.
  98477. for (var face = 0; face < 6; face++) {
  98478. _loop_2(face);
  98479. }
  98480. };
  98481. for (var i = 0; i <= mipmapsCount; i++) {
  98482. _loop_1(i);
  98483. }
  98484. // Once all the textures haves been collected as RGBD stored in PNGs
  98485. return Promise.all(promises).then(function () {
  98486. // We can delete the hosting scene keeping track of all the creation objects
  98487. hostingScene.dispose();
  98488. // Creates the json header for the env texture
  98489. var info = {
  98490. version: 1,
  98491. width: cubeWidth,
  98492. irradiance: _this._CreateEnvTextureIrradiance(texture),
  98493. specular: {
  98494. mipmaps: [],
  98495. lodGenerationScale: texture.lodGenerationScale
  98496. }
  98497. };
  98498. // Sets the specular image data information
  98499. var position = 0;
  98500. for (var i = 0; i <= mipmapsCount; i++) {
  98501. for (var face = 0; face < 6; face++) {
  98502. var byteLength = specularTextures[i * 6 + face].byteLength;
  98503. info.specular.mipmaps.push({
  98504. length: byteLength,
  98505. position: position
  98506. });
  98507. position += byteLength;
  98508. }
  98509. }
  98510. // Encode the JSON as an array buffer
  98511. var infoString = JSON.stringify(info);
  98512. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  98513. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  98514. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  98515. infoView[i] = infoString.charCodeAt(i);
  98516. }
  98517. // Ends up with a null terminator for easier parsing
  98518. infoView[infoString.length] = 0x00;
  98519. // Computes the final required size and creates the storage
  98520. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  98521. var finalBuffer = new ArrayBuffer(totalSize);
  98522. var finalBufferView = new Uint8Array(finalBuffer);
  98523. var dataView = new DataView(finalBuffer);
  98524. // Copy the magic bytes identifying the file in
  98525. var pos = 0;
  98526. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  98527. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  98528. }
  98529. // Add the json info
  98530. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  98531. pos += infoBuffer.byteLength;
  98532. // Finally inserts the texture data
  98533. for (var i = 0; i <= mipmapsCount; i++) {
  98534. for (var face = 0; face < 6; face++) {
  98535. var dataBuffer = specularTextures[i * 6 + face];
  98536. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  98537. pos += dataBuffer.byteLength;
  98538. }
  98539. }
  98540. // Voila
  98541. return finalBuffer;
  98542. });
  98543. };
  98544. /**
  98545. * Creates a JSON representation of the spherical data.
  98546. * @param texture defines the texture containing the polynomials
  98547. * @return the JSON representation of the spherical info
  98548. */
  98549. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  98550. var polynmials = texture.sphericalPolynomial;
  98551. if (polynmials == null) {
  98552. return null;
  98553. }
  98554. return {
  98555. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  98556. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  98557. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  98558. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  98559. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  98560. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  98561. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  98562. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  98563. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  98564. };
  98565. };
  98566. /**
  98567. * Uploads the texture info contained in the env file to the GPU.
  98568. * @param texture defines the internal texture to upload to
  98569. * @param arrayBuffer defines the buffer cotaining the data to load
  98570. * @param info defines the texture info retrieved through the GetEnvInfo method
  98571. * @returns a promise
  98572. */
  98573. EnvironmentTextureTools.UploadEnvLevelsAsync = function (texture, arrayBuffer, info) {
  98574. if (info.version !== 1) {
  98575. throw new Error("Unsupported babylon environment map version \"" + info.version + "\"");
  98576. }
  98577. var specularInfo = info.specular;
  98578. if (!specularInfo) {
  98579. // Nothing else parsed so far
  98580. return Promise.resolve();
  98581. }
  98582. // Double checks the enclosed info
  98583. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  98584. mipmapsCount = Math.round(mipmapsCount) + 1;
  98585. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  98586. throw new Error("Unsupported specular mipmaps number \"" + specularInfo.mipmaps.length + "\"");
  98587. }
  98588. texture._lodGenerationScale = specularInfo.lodGenerationScale;
  98589. var imageData = new Array(mipmapsCount);
  98590. for (var i = 0; i < mipmapsCount; i++) {
  98591. imageData[i] = new Array(6);
  98592. for (var face = 0; face < 6; face++) {
  98593. var imageInfo = specularInfo.mipmaps[i * 6 + face];
  98594. imageData[i][face] = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageInfo.position, imageInfo.length);
  98595. }
  98596. }
  98597. return EnvironmentTextureTools.UploadLevelsAsync(texture, imageData);
  98598. };
  98599. /**
  98600. * Uploads the levels of image data to the GPU.
  98601. * @param texture defines the internal texture to upload to
  98602. * @param imageData defines the array buffer views of image data [mipmap][face]
  98603. * @returns a promise
  98604. */
  98605. EnvironmentTextureTools.UploadLevelsAsync = function (texture, imageData) {
  98606. if (!BABYLON.Tools.IsExponentOfTwo(texture.width)) {
  98607. throw new Error("Texture size must be a power of two");
  98608. }
  98609. var mipmapsCount = Math.round(BABYLON.Scalar.Log2(texture.width)) + 1;
  98610. // Gets everything ready.
  98611. var engine = texture.getEngine();
  98612. var expandTexture = false;
  98613. var generateNonLODTextures = false;
  98614. var rgbdPostProcess = null;
  98615. var cubeRtt = null;
  98616. var lodTextures = null;
  98617. var caps = engine.getCaps();
  98618. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  98619. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  98620. texture.generateMipMaps = true;
  98621. engine.updateTextureSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE, texture);
  98622. // Add extra process if texture lod is not supported
  98623. if (!caps.textureLOD) {
  98624. expandTexture = false;
  98625. generateNonLODTextures = true;
  98626. lodTextures = {};
  98627. }
  98628. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  98629. else if (engine.webGLVersion < 2) {
  98630. expandTexture = false;
  98631. }
  98632. // If half float available we can uncompress the texture
  98633. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  98634. expandTexture = true;
  98635. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  98636. }
  98637. // If full float available we can uncompress the texture
  98638. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  98639. expandTexture = true;
  98640. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  98641. }
  98642. // Expand the texture if possible
  98643. if (expandTexture) {
  98644. // Simply run through the decode PP
  98645. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  98646. texture._isRGBD = false;
  98647. texture.invertY = false;
  98648. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  98649. generateDepthBuffer: false,
  98650. generateMipMaps: true,
  98651. generateStencilBuffer: false,
  98652. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  98653. type: texture.type,
  98654. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  98655. });
  98656. }
  98657. else {
  98658. texture._isRGBD = true;
  98659. texture.invertY = true;
  98660. // In case of missing support, applies the same patch than DDS files.
  98661. if (generateNonLODTextures) {
  98662. var mipSlices = 3;
  98663. var scale = texture._lodGenerationScale;
  98664. var offset = texture._lodGenerationOffset;
  98665. for (var i = 0; i < mipSlices; i++) {
  98666. //compute LOD from even spacing in smoothness (matching shader calculation)
  98667. var smoothness = i / (mipSlices - 1);
  98668. var roughness = 1 - smoothness;
  98669. var minLODIndex = offset; // roughness = 0
  98670. var maxLODIndex = (mipmapsCount - 1) * scale + offset; // roughness = 1 (mipmaps start from 0)
  98671. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  98672. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  98673. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  98674. glTextureFromLod.isCube = true;
  98675. glTextureFromLod.invertY = true;
  98676. glTextureFromLod.generateMipMaps = false;
  98677. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  98678. // Wrap in a base texture for easy binding.
  98679. var lodTexture = new BABYLON.BaseTexture(null);
  98680. lodTexture.isCube = true;
  98681. lodTexture._texture = glTextureFromLod;
  98682. lodTextures[mipmapIndex] = lodTexture;
  98683. switch (i) {
  98684. case 0:
  98685. texture._lodTextureLow = lodTexture;
  98686. break;
  98687. case 1:
  98688. texture._lodTextureMid = lodTexture;
  98689. break;
  98690. case 2:
  98691. texture._lodTextureHigh = lodTexture;
  98692. break;
  98693. }
  98694. }
  98695. }
  98696. }
  98697. var promises = [];
  98698. var _loop_3 = function (i) {
  98699. var _loop_4 = function (face) {
  98700. // Constructs an image element from image data
  98701. var bytes = imageData[i][face];
  98702. var blob = new Blob([bytes], { type: 'image/png' });
  98703. var url = URL.createObjectURL(blob);
  98704. var image = new Image();
  98705. image.src = url;
  98706. // Enqueue promise to upload to the texture.
  98707. var promise = new Promise(function (resolve, reject) {
  98708. image.onload = function () {
  98709. if (expandTexture) {
  98710. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  98711. reject(message);
  98712. }, image);
  98713. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  98714. // Uncompress the data to a RTT
  98715. rgbdPostProcess.onApply = function (effect) {
  98716. effect._bindTexture("textureSampler", tempTexture_1);
  98717. effect.setFloat2("scale", 1, 1);
  98718. };
  98719. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  98720. // Cleanup
  98721. engine.restoreDefaultFramebuffer();
  98722. tempTexture_1.dispose();
  98723. window.URL.revokeObjectURL(url);
  98724. resolve();
  98725. });
  98726. }
  98727. else {
  98728. engine._uploadImageToTexture(texture, image, face, i);
  98729. // Upload the face to the non lod texture support
  98730. if (generateNonLODTextures) {
  98731. var lodTexture = lodTextures[i];
  98732. if (lodTexture) {
  98733. engine._uploadImageToTexture(lodTexture._texture, image, face, 0);
  98734. }
  98735. }
  98736. resolve();
  98737. }
  98738. };
  98739. image.onerror = function (error) {
  98740. reject(error);
  98741. };
  98742. });
  98743. promises.push(promise);
  98744. };
  98745. // All faces
  98746. for (var face = 0; face < 6; face++) {
  98747. _loop_4(face);
  98748. }
  98749. };
  98750. // All mipmaps up to provided number of images
  98751. for (var i = 0; i < imageData.length; i++) {
  98752. _loop_3(i);
  98753. }
  98754. // Fill remaining mipmaps with black textures.
  98755. if (imageData.length < mipmapsCount) {
  98756. var data = void 0;
  98757. var size = Math.pow(2, mipmapsCount - 1 - imageData.length);
  98758. var dataLength = size * size * 4;
  98759. switch (texture.type) {
  98760. case BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT: {
  98761. data = new Uint8Array(dataLength);
  98762. break;
  98763. }
  98764. case BABYLON.Engine.TEXTURETYPE_HALF_FLOAT: {
  98765. data = new Uint16Array(dataLength);
  98766. break;
  98767. }
  98768. case BABYLON.Engine.TEXTURETYPE_FLOAT: {
  98769. data = new Float32Array(dataLength);
  98770. break;
  98771. }
  98772. }
  98773. for (var i = imageData.length; i < mipmapsCount; i++) {
  98774. for (var face = 0; face < 6; face++) {
  98775. engine._uploadArrayBufferViewToTexture(texture, data, face, i);
  98776. }
  98777. }
  98778. }
  98779. // Once all done, finishes the cleanup and return
  98780. return Promise.all(promises).then(function () {
  98781. // Release temp RTT.
  98782. if (cubeRtt) {
  98783. engine._releaseFramebufferObjects(cubeRtt);
  98784. cubeRtt._swapAndDie(texture);
  98785. }
  98786. // Release temp Post Process.
  98787. if (rgbdPostProcess) {
  98788. rgbdPostProcess.dispose();
  98789. }
  98790. // Flag internal texture as ready in case they are in use.
  98791. if (generateNonLODTextures) {
  98792. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  98793. texture._lodTextureHigh._texture.isReady = true;
  98794. }
  98795. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  98796. texture._lodTextureMid._texture.isReady = true;
  98797. }
  98798. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  98799. texture._lodTextureLow._texture.isReady = true;
  98800. }
  98801. }
  98802. });
  98803. };
  98804. /**
  98805. * Uploads spherical polynomials information to the texture.
  98806. * @param texture defines the texture we are trying to upload the information to
  98807. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  98808. */
  98809. EnvironmentTextureTools.UploadEnvSpherical = function (texture, info) {
  98810. if (info.version !== 1) {
  98811. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  98812. }
  98813. var irradianceInfo = info.irradiance;
  98814. if (!irradianceInfo) {
  98815. return;
  98816. }
  98817. var sp = new BABYLON.SphericalPolynomial();
  98818. BABYLON.Vector3.FromArrayToRef(irradianceInfo.x, 0, sp.x);
  98819. BABYLON.Vector3.FromArrayToRef(irradianceInfo.y, 0, sp.y);
  98820. BABYLON.Vector3.FromArrayToRef(irradianceInfo.z, 0, sp.z);
  98821. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xx, 0, sp.xx);
  98822. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yy, 0, sp.yy);
  98823. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zz, 0, sp.zz);
  98824. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yz, 0, sp.yz);
  98825. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zx, 0, sp.zx);
  98826. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xy, 0, sp.xy);
  98827. texture._sphericalPolynomial = sp;
  98828. };
  98829. /**
  98830. * Magic number identifying the env file.
  98831. */
  98832. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  98833. return EnvironmentTextureTools;
  98834. }());
  98835. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  98836. })(BABYLON || (BABYLON = {}));
  98837. //# sourceMappingURL=babylon.environmentTextureTools.js.map
  98838. var BABYLON;
  98839. (function (BABYLON) {
  98840. /**
  98841. * Implementation of the ENV Texture Loader.
  98842. */
  98843. var ENVTextureLoader = /** @class */ (function () {
  98844. function ENVTextureLoader() {
  98845. /**
  98846. * Defines wether the loader supports cascade loading the different faces.
  98847. */
  98848. this.supportCascades = false;
  98849. }
  98850. /**
  98851. * This returns if the loader support the current file information.
  98852. * @param extension defines the file extension of the file being loaded
  98853. * @param textureFormatInUse defines the current compressed format in use iun the engine
  98854. * @param fallback defines the fallback internal texture if any
  98855. * @param isBase64 defines whether the texture is encoded as a base64
  98856. * @param isBuffer defines whether the texture data are stored as a buffer
  98857. * @returns true if the loader can load the specified file
  98858. */
  98859. ENVTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  98860. return extension.indexOf(".env") === 0;
  98861. };
  98862. /**
  98863. * Transform the url before loading if required.
  98864. * @param rootUrl the url of the texture
  98865. * @param textureFormatInUse defines the current compressed format in use iun the engine
  98866. * @returns the transformed texture
  98867. */
  98868. ENVTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  98869. return rootUrl;
  98870. };
  98871. /**
  98872. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  98873. * @param rootUrl the url of the texture
  98874. * @param textureFormatInUse defines the current compressed format in use iun the engine
  98875. * @returns the fallback texture
  98876. */
  98877. ENVTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  98878. return null;
  98879. };
  98880. /**
  98881. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  98882. * @param data contains the texture data
  98883. * @param texture defines the BabylonJS internal texture
  98884. * @param createPolynomials will be true if polynomials have been requested
  98885. * @param onLoad defines the callback to trigger once the texture is ready
  98886. * @param onError defines the callback to trigger in case of error
  98887. */
  98888. ENVTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  98889. if (Array.isArray(data)) {
  98890. return;
  98891. }
  98892. data = data;
  98893. var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
  98894. if (info) {
  98895. texture.width = info.width;
  98896. texture.height = info.width;
  98897. BABYLON.EnvironmentTextureTools.UploadEnvSpherical(texture, info);
  98898. BABYLON.EnvironmentTextureTools.UploadEnvLevelsAsync(texture, data, info).then(function () {
  98899. texture.isReady = true;
  98900. if (onLoad) {
  98901. onLoad();
  98902. }
  98903. });
  98904. }
  98905. else if (onError) {
  98906. onError("Can not parse the environment file", null);
  98907. }
  98908. };
  98909. /**
  98910. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  98911. * @param data contains the texture data
  98912. * @param texture defines the BabylonJS internal texture
  98913. * @param callback defines the method to call once ready to upload
  98914. */
  98915. ENVTextureLoader.prototype.loadData = function (data, texture, callback) {
  98916. throw ".env not supported in 2d.";
  98917. };
  98918. return ENVTextureLoader;
  98919. }());
  98920. // Register the loader.
  98921. BABYLON.Engine._TextureLoaders.push(new ENVTextureLoader());
  98922. })(BABYLON || (BABYLON = {}));
  98923. //# sourceMappingURL=babylon.envTextureLoader.js.map
  98924. var BABYLON;
  98925. (function (BABYLON) {
  98926. /**
  98927. * Renders a layer on top of an existing scene
  98928. */
  98929. var UtilityLayerRenderer = /** @class */ (function () {
  98930. /**
  98931. * Instantiates a UtilityLayerRenderer
  98932. * @param originalScene the original scene that will be rendered on top of
  98933. */
  98934. function UtilityLayerRenderer(
  98935. /** the original scene that will be rendered on top of */
  98936. originalScene) {
  98937. var _this = this;
  98938. this.originalScene = originalScene;
  98939. this._pointerCaptures = {};
  98940. this._lastPointerEvents = {};
  98941. /**
  98942. * If the utility layer should automatically be rendered on top of existing scene
  98943. */
  98944. this.shouldRender = true;
  98945. /**
  98946. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  98947. */
  98948. this.onlyCheckPointerDownEvents = true;
  98949. /**
  98950. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  98951. */
  98952. this.processAllEvents = false;
  98953. /**
  98954. * Observable raised when the pointer move from the utility layer scene to the main scene
  98955. */
  98956. this.onPointerOutObservable = new BABYLON.Observable();
  98957. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  98958. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  98959. this.utilityLayerScene.useRightHandedSystem = originalScene.useRightHandedSystem;
  98960. this.utilityLayerScene._allowPostProcessClearColor = false;
  98961. originalScene.getEngine().scenes.pop();
  98962. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  98963. this.utilityLayerScene.detachControl();
  98964. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  98965. if (!_this.processAllEvents) {
  98966. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  98967. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  98968. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  98969. return;
  98970. }
  98971. }
  98972. var pointerEvent = (prePointerInfo.event);
  98973. if (originalScene.isPointerCaptured(pointerEvent.pointerId)) {
  98974. _this._pointerCaptures[pointerEvent.pointerId] = false;
  98975. return;
  98976. }
  98977. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  98978. if (!prePointerInfo.ray && utilityScenePick) {
  98979. prePointerInfo.ray = utilityScenePick.ray;
  98980. }
  98981. // always fire the prepointer oversvable
  98982. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  98983. // allow every non pointer down event to flow to the utility layer
  98984. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  98985. if (!prePointerInfo.skipOnPointerObservable) {
  98986. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  98987. }
  98988. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  98989. _this._pointerCaptures[pointerEvent.pointerId] = false;
  98990. }
  98991. return;
  98992. }
  98993. if (_this.utilityLayerScene.autoClearDepthAndStencil) {
  98994. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  98995. if (utilityScenePick && utilityScenePick.hit) {
  98996. if (!prePointerInfo.skipOnPointerObservable) {
  98997. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  98998. }
  98999. prePointerInfo.skipOnPointerObservable = true;
  99000. }
  99001. }
  99002. else {
  99003. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  99004. var pointerEvent_1 = (prePointerInfo.event);
  99005. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  99006. if (originalScenePick && utilityScenePick) {
  99007. // No pick in utility scene
  99008. if (utilityScenePick.distance === 0 && originalScenePick.pickedMesh) {
  99009. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  99010. // We touched an utility mesh present in the main scene
  99011. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  99012. prePointerInfo.skipOnPointerObservable = true;
  99013. }
  99014. else if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  99015. _this._pointerCaptures[pointerEvent_1.pointerId] = true;
  99016. }
  99017. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  99018. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  99019. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  99020. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  99021. }
  99022. }
  99023. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  99024. // We pick something in utility scene or the pick in utility is closer than the one in main scene
  99025. _this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent_1);
  99026. // If a previous utility layer set this, do not unset this
  99027. if (!prePointerInfo.skipOnPointerObservable) {
  99028. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  99029. }
  99030. }
  99031. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  99032. // We have a pick in both scenes but main is closer than utility
  99033. // We touched an utility mesh present in the main scene
  99034. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  99035. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  99036. prePointerInfo.skipOnPointerObservable = true;
  99037. }
  99038. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  99039. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  99040. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  99041. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  99042. }
  99043. }
  99044. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent_1.pointerId]) {
  99045. _this._pointerCaptures[pointerEvent_1.pointerId] = false;
  99046. }
  99047. }
  99048. }
  99049. });
  99050. // Render directly on top of existing scene without clearing
  99051. this.utilityLayerScene.autoClear = false;
  99052. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  99053. if (_this.shouldRender) {
  99054. _this.render();
  99055. }
  99056. });
  99057. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  99058. _this.dispose();
  99059. });
  99060. this._updateCamera();
  99061. }
  99062. Object.defineProperty(UtilityLayerRenderer, "DefaultUtilityLayer", {
  99063. /**
  99064. * A shared utility layer that can be used to overlay objects into a scene (Depth map of the previous scene is cleared before drawing on top of it)
  99065. */
  99066. get: function () {
  99067. if (UtilityLayerRenderer._DefaultUtilityLayer == null) {
  99068. UtilityLayerRenderer._DefaultUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  99069. UtilityLayerRenderer._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  99070. UtilityLayerRenderer._DefaultUtilityLayer = null;
  99071. });
  99072. }
  99073. return UtilityLayerRenderer._DefaultUtilityLayer;
  99074. },
  99075. enumerable: true,
  99076. configurable: true
  99077. });
  99078. Object.defineProperty(UtilityLayerRenderer, "DefaultKeepDepthUtilityLayer", {
  99079. /**
  99080. * A shared utility layer that can be used to embed objects into a scene (Depth map of the previous scene is not cleared before drawing on top of it)
  99081. */
  99082. get: function () {
  99083. if (UtilityLayerRenderer._DefaultKeepDepthUtilityLayer == null) {
  99084. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  99085. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = false;
  99086. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  99087. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  99088. });
  99089. }
  99090. return UtilityLayerRenderer._DefaultKeepDepthUtilityLayer;
  99091. },
  99092. enumerable: true,
  99093. configurable: true
  99094. });
  99095. UtilityLayerRenderer.prototype._notifyObservers = function (prePointerInfo, pickInfo, pointerEvent) {
  99096. if (!prePointerInfo.skipOnPointerObservable) {
  99097. this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo));
  99098. this._lastPointerEvents[pointerEvent.pointerId] = true;
  99099. }
  99100. };
  99101. /**
  99102. * Renders the utility layers scene on top of the original scene
  99103. */
  99104. UtilityLayerRenderer.prototype.render = function () {
  99105. this._updateCamera();
  99106. if (this.utilityLayerScene.activeCamera) {
  99107. // Set the camera's scene to utility layers scene
  99108. var oldScene = this.utilityLayerScene.activeCamera.getScene();
  99109. var camera = this.utilityLayerScene.activeCamera;
  99110. camera._scene = this.utilityLayerScene;
  99111. if (camera.leftCamera) {
  99112. camera.leftCamera._scene = this.utilityLayerScene;
  99113. }
  99114. if (camera.rightCamera) {
  99115. camera.rightCamera._scene = this.utilityLayerScene;
  99116. }
  99117. this.utilityLayerScene.render(false);
  99118. // Reset camera's scene back to original
  99119. camera._scene = oldScene;
  99120. if (camera.leftCamera) {
  99121. camera.leftCamera._scene = oldScene;
  99122. }
  99123. if (camera.rightCamera) {
  99124. camera.rightCamera._scene = oldScene;
  99125. }
  99126. }
  99127. };
  99128. /**
  99129. * Disposes of the renderer
  99130. */
  99131. UtilityLayerRenderer.prototype.dispose = function () {
  99132. this.onPointerOutObservable.clear();
  99133. if (this._afterRenderObserver) {
  99134. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  99135. }
  99136. if (this._sceneDisposeObserver) {
  99137. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  99138. }
  99139. if (this._originalPointerObserver) {
  99140. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  99141. }
  99142. this.utilityLayerScene.dispose();
  99143. };
  99144. UtilityLayerRenderer.prototype._updateCamera = function () {
  99145. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  99146. };
  99147. UtilityLayerRenderer._DefaultUtilityLayer = null;
  99148. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  99149. return UtilityLayerRenderer;
  99150. }());
  99151. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  99152. })(BABYLON || (BABYLON = {}));
  99153. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  99154. //# sourceMappingURL=babylon.behavior.js.map
  99155. var BABYLON;
  99156. (function (BABYLON) {
  99157. /**
  99158. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  99159. */
  99160. var PointerDragBehavior = /** @class */ (function () {
  99161. /**
  99162. * Creates a pointer drag behavior that can be attached to a mesh
  99163. * @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)
  99164. */
  99165. function PointerDragBehavior(options) {
  99166. /**
  99167. * The maximum tolerated angle between the drag plane and dragging pointer rays to trigger pointer events. Set to 0 to allow any angle (default: 0)
  99168. */
  99169. this.maxDragAngle = 0;
  99170. /**
  99171. * @hidden
  99172. */
  99173. this._useAlternatePickedPointAboveMaxDragAngle = false;
  99174. /**
  99175. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  99176. */
  99177. this.currentDraggingPointerID = -1;
  99178. /**
  99179. * If the behavior is currently in a dragging state
  99180. */
  99181. this.dragging = false;
  99182. /**
  99183. * 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)
  99184. */
  99185. this.dragDeltaRatio = 0.2;
  99186. /**
  99187. * If the drag plane orientation should be updated during the dragging (Default: true)
  99188. */
  99189. this.updateDragPlane = true;
  99190. // Debug mode will display drag planes to help visualize behavior
  99191. this._debugMode = false;
  99192. this._moving = false;
  99193. /**
  99194. * Fires each time the attached mesh is dragged with the pointer
  99195. * * delta between last drag position and current drag position in world space
  99196. * * dragDistance along the drag axis
  99197. * * dragPlaneNormal normal of the current drag plane used during the drag
  99198. * * dragPlanePoint in world space where the drag intersects the drag plane
  99199. */
  99200. this.onDragObservable = new BABYLON.Observable();
  99201. /**
  99202. * Fires each time a drag begins (eg. mouse down on mesh)
  99203. */
  99204. this.onDragStartObservable = new BABYLON.Observable();
  99205. /**
  99206. * Fires each time a drag ends (eg. mouse release after drag)
  99207. */
  99208. this.onDragEndObservable = new BABYLON.Observable();
  99209. /**
  99210. * If the attached mesh should be moved when dragged
  99211. */
  99212. this.moveAttached = true;
  99213. /**
  99214. * If the drag behavior will react to drag events (Default: true)
  99215. */
  99216. this.enabled = true;
  99217. /**
  99218. * If camera controls should be detached during the drag
  99219. */
  99220. this.detachCameraControls = true;
  99221. /**
  99222. * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true)
  99223. */
  99224. this.useObjectOrienationForDragging = true;
  99225. this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  99226. this._alternatePickedPoint = new BABYLON.Vector3(0, 0, 0);
  99227. this._worldDragAxis = new BABYLON.Vector3(0, 0, 0);
  99228. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  99229. this._attachedElement = null;
  99230. this._startDragRay = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  99231. this._lastPointerRay = {};
  99232. this._dragDelta = new BABYLON.Vector3();
  99233. // Variables to avoid instantiation in the below method
  99234. this._pointA = new BABYLON.Vector3(0, 0, 0);
  99235. this._pointB = new BABYLON.Vector3(0, 0, 0);
  99236. this._pointC = new BABYLON.Vector3(0, 0, 0);
  99237. this._lineA = new BABYLON.Vector3(0, 0, 0);
  99238. this._lineB = new BABYLON.Vector3(0, 0, 0);
  99239. this._localAxis = new BABYLON.Vector3(0, 0, 0);
  99240. this._lookAt = new BABYLON.Vector3(0, 0, 0);
  99241. this._options = options ? options : {};
  99242. var optionCount = 0;
  99243. if (this._options.dragAxis) {
  99244. optionCount++;
  99245. }
  99246. if (this._options.dragPlaneNormal) {
  99247. optionCount++;
  99248. }
  99249. if (optionCount > 1) {
  99250. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  99251. }
  99252. }
  99253. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  99254. /**
  99255. * The name of the behavior
  99256. */
  99257. get: function () {
  99258. return "PointerDrag";
  99259. },
  99260. enumerable: true,
  99261. configurable: true
  99262. });
  99263. /**
  99264. * Initializes the behavior
  99265. */
  99266. PointerDragBehavior.prototype.init = function () { };
  99267. /**
  99268. * Attaches the drag behavior the passed in mesh
  99269. * @param ownerNode The mesh that will be dragged around once attached
  99270. */
  99271. PointerDragBehavior.prototype.attach = function (ownerNode) {
  99272. var _this = this;
  99273. this._scene = ownerNode.getScene();
  99274. this._attachedNode = ownerNode;
  99275. // Initialize drag plane to not interfere with existing scene
  99276. if (!PointerDragBehavior._planeScene) {
  99277. if (this._debugMode) {
  99278. PointerDragBehavior._planeScene = this._scene;
  99279. }
  99280. else {
  99281. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  99282. PointerDragBehavior._planeScene.detachControl();
  99283. this._scene.getEngine().scenes.pop();
  99284. this._scene.onDisposeObservable.addOnce(function () {
  99285. PointerDragBehavior._planeScene.dispose();
  99286. PointerDragBehavior._planeScene = null;
  99287. });
  99288. }
  99289. }
  99290. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  99291. // State of the drag
  99292. this.lastDragPosition = new BABYLON.Vector3(0, 0, 0);
  99293. var pickPredicate = function (m) {
  99294. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  99295. };
  99296. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  99297. if (!_this.enabled) {
  99298. return;
  99299. }
  99300. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  99301. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  99302. _this._startDrag(pointerInfo.event.pointerId, pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint);
  99303. }
  99304. }
  99305. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  99306. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  99307. _this.releaseDrag();
  99308. }
  99309. }
  99310. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  99311. var pointerId = pointerInfo.event.pointerId;
  99312. // If drag was started with anyMouseID specified, set pointerID to the next mouse that moved
  99313. if (_this.currentDraggingPointerID === PointerDragBehavior._AnyMouseID && pointerId !== PointerDragBehavior._AnyMouseID && pointerInfo.event.pointerType == "mouse") {
  99314. if (_this._lastPointerRay[_this.currentDraggingPointerID]) {
  99315. _this._lastPointerRay[pointerId] = _this._lastPointerRay[_this.currentDraggingPointerID];
  99316. delete _this._lastPointerRay[_this.currentDraggingPointerID];
  99317. }
  99318. _this.currentDraggingPointerID = pointerId;
  99319. }
  99320. // Keep track of last pointer ray, this is used simulating the start of a drag in startDrag()
  99321. if (!_this._lastPointerRay[pointerId]) {
  99322. _this._lastPointerRay[pointerId] = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  99323. }
  99324. if (pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  99325. _this._lastPointerRay[pointerId].origin.copyFrom(pointerInfo.pickInfo.ray.origin);
  99326. _this._lastPointerRay[pointerId].direction.copyFrom(pointerInfo.pickInfo.ray.direction);
  99327. if (_this.currentDraggingPointerID == pointerId && _this.dragging) {
  99328. _this._moveDrag(pointerInfo.pickInfo.ray);
  99329. }
  99330. }
  99331. }
  99332. });
  99333. this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  99334. if (_this._moving && _this.moveAttached) {
  99335. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(_this._attachedNode);
  99336. // Slowly move mesh to avoid jitter
  99337. _this._targetPosition.subtractToRef((_this._attachedNode).absolutePosition, _this._tmpVector);
  99338. _this._tmpVector.scaleInPlace(_this.dragDeltaRatio);
  99339. (_this._attachedNode).getAbsolutePosition().addToRef(_this._tmpVector, _this._tmpVector);
  99340. (_this._attachedNode).setAbsolutePosition(_this._tmpVector);
  99341. BABYLON.BoundingBoxGizmo._RestorePivotPoint(_this._attachedNode);
  99342. }
  99343. });
  99344. };
  99345. /**
  99346. * Force relase the drag action by code.
  99347. */
  99348. PointerDragBehavior.prototype.releaseDrag = function () {
  99349. this.dragging = false;
  99350. this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerID });
  99351. this.currentDraggingPointerID = -1;
  99352. this._moving = false;
  99353. // Reattach camera controls
  99354. if (this.detachCameraControls && this._attachedElement && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  99355. this._scene.activeCamera.attachControl(this._attachedElement, true);
  99356. }
  99357. };
  99358. /**
  99359. * Simulates the start of a pointer drag event on the behavior
  99360. * @param pointerId pointerID of the pointer that should be simulated (Default: Any mouse pointer ID)
  99361. * @param fromRay initial ray of the pointer to be simulated (Default: Ray from camera to attached mesh)
  99362. * @param startPickedPoint picked point of the pointer to be simulated (Default: attached mesh position)
  99363. */
  99364. PointerDragBehavior.prototype.startDrag = function (pointerId, fromRay, startPickedPoint) {
  99365. if (pointerId === void 0) { pointerId = PointerDragBehavior._AnyMouseID; }
  99366. this._startDrag(pointerId, fromRay, startPickedPoint);
  99367. var lastRay = this._lastPointerRay[pointerId];
  99368. if (pointerId === PointerDragBehavior._AnyMouseID) {
  99369. lastRay = this._lastPointerRay[Object.keys(this._lastPointerRay)[0]];
  99370. }
  99371. if (lastRay) {
  99372. // if there was a last pointer ray drag the object there
  99373. this._moveDrag(lastRay);
  99374. }
  99375. };
  99376. PointerDragBehavior.prototype._startDrag = function (pointerId, fromRay, startPickedPoint) {
  99377. if (!this._scene.activeCamera || this.dragging || !this._attachedNode) {
  99378. return;
  99379. }
  99380. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(this._attachedNode);
  99381. // Create start ray from the camera to the object
  99382. if (fromRay) {
  99383. this._startDragRay.direction.copyFrom(fromRay.direction);
  99384. this._startDragRay.origin.copyFrom(fromRay.origin);
  99385. }
  99386. else {
  99387. this._startDragRay.origin.copyFrom(this._scene.activeCamera.position);
  99388. this._attachedNode.getWorldMatrix().getTranslationToRef(this._tmpVector);
  99389. this._tmpVector.subtractToRef(this._scene.activeCamera.position, this._startDragRay.direction);
  99390. }
  99391. this._updateDragPlanePosition(this._startDragRay, startPickedPoint ? startPickedPoint : this._tmpVector);
  99392. var pickedPoint = this._pickWithRayOnDragPlane(this._startDragRay);
  99393. if (pickedPoint) {
  99394. this.dragging = true;
  99395. this.currentDraggingPointerID = pointerId;
  99396. this.lastDragPosition.copyFrom(pickedPoint);
  99397. this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: this.currentDraggingPointerID });
  99398. this._targetPosition.copyFrom((this._attachedNode).absolutePosition);
  99399. // Detatch camera controls
  99400. if (this.detachCameraControls && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  99401. if (this._scene.activeCamera.inputs.attachedElement) {
  99402. this._attachedElement = this._scene.activeCamera.inputs.attachedElement;
  99403. this._scene.activeCamera.detachControl(this._scene.activeCamera.inputs.attachedElement);
  99404. }
  99405. else {
  99406. this._attachedElement = null;
  99407. }
  99408. }
  99409. }
  99410. BABYLON.BoundingBoxGizmo._RestorePivotPoint(this._attachedNode);
  99411. };
  99412. PointerDragBehavior.prototype._moveDrag = function (ray) {
  99413. this._moving = true;
  99414. var pickedPoint = this._pickWithRayOnDragPlane(ray);
  99415. if (pickedPoint) {
  99416. if (this.updateDragPlane) {
  99417. this._updateDragPlanePosition(ray, pickedPoint);
  99418. }
  99419. var dragLength = 0;
  99420. // depending on the drag mode option drag accordingly
  99421. if (this._options.dragAxis) {
  99422. // Convert local drag axis to world
  99423. BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._worldDragAxis);
  99424. // Project delta drag from the drag plane onto the drag axis
  99425. pickedPoint.subtractToRef(this.lastDragPosition, this._tmpVector);
  99426. dragLength = BABYLON.Vector3.Dot(this._tmpVector, this._worldDragAxis);
  99427. this._worldDragAxis.scaleToRef(dragLength, this._dragDelta);
  99428. }
  99429. else {
  99430. dragLength = this._dragDelta.length();
  99431. pickedPoint.subtractToRef(this.lastDragPosition, this._dragDelta);
  99432. }
  99433. this._targetPosition.addInPlace(this._dragDelta);
  99434. this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: this._dragDelta, dragPlanePoint: pickedPoint, dragPlaneNormal: this._dragPlane.forward, pointerId: this.currentDraggingPointerID });
  99435. this.lastDragPosition.copyFrom(pickedPoint);
  99436. }
  99437. };
  99438. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  99439. var _this = this;
  99440. if (!ray) {
  99441. return null;
  99442. }
  99443. // Calculate angle between plane normal and ray
  99444. var angle = Math.acos(BABYLON.Vector3.Dot(this._dragPlane.forward, ray.direction));
  99445. // Correct if ray is casted from oposite side
  99446. if (angle > Math.PI / 2) {
  99447. angle = Math.PI - angle;
  99448. }
  99449. // If the angle is too perpendicular to the plane pick another point on the plane where it is looking
  99450. if (this.maxDragAngle > 0 && angle > this.maxDragAngle) {
  99451. if (this._useAlternatePickedPointAboveMaxDragAngle) {
  99452. // Invert ray direction along the towards object axis
  99453. this._tmpVector.copyFrom(ray.direction);
  99454. (this._attachedNode).absolutePosition.subtractToRef(ray.origin, this._alternatePickedPoint);
  99455. this._alternatePickedPoint.normalize();
  99456. this._alternatePickedPoint.scaleInPlace(-2 * BABYLON.Vector3.Dot(this._alternatePickedPoint, this._tmpVector));
  99457. this._tmpVector.addInPlace(this._alternatePickedPoint);
  99458. // Project resulting vector onto the drag plane and add it to the attached nodes absolute position to get a picked point
  99459. var dot = BABYLON.Vector3.Dot(this._dragPlane.forward, this._tmpVector);
  99460. this._dragPlane.forward.scaleToRef(-dot, this._alternatePickedPoint);
  99461. this._alternatePickedPoint.addInPlace(this._tmpVector);
  99462. this._alternatePickedPoint.addInPlace((this._attachedNode).absolutePosition);
  99463. return this._alternatePickedPoint;
  99464. }
  99465. else {
  99466. return null;
  99467. }
  99468. }
  99469. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  99470. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  99471. return pickResult.pickedPoint;
  99472. }
  99473. else {
  99474. return null;
  99475. }
  99476. };
  99477. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  99478. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray, dragPlanePosition) {
  99479. this._pointA.copyFrom(dragPlanePosition);
  99480. if (this._options.dragAxis) {
  99481. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragAxis);
  99482. // Calculate plane normal in direction of camera but perpendicular to drag axis
  99483. this._pointA.addToRef(this._localAxis, this._pointB); // towards drag axis
  99484. ray.origin.subtractToRef(this._pointA, this._pointC);
  99485. this._pointA.addToRef(this._pointC.normalize(), this._pointC); // towards camera
  99486. // Get perpendicular line from direction to camera and drag axis
  99487. this._pointB.subtractToRef(this._pointA, this._lineA);
  99488. this._pointC.subtractToRef(this._pointA, this._lineB);
  99489. BABYLON.Vector3.CrossToRef(this._lineA, this._lineB, this._lookAt);
  99490. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  99491. BABYLON.Vector3.CrossToRef(this._lineA, this._lookAt, this._lookAt);
  99492. this._lookAt.normalize();
  99493. this._dragPlane.position.copyFrom(this._pointA);
  99494. this._pointA.subtractToRef(this._lookAt, this._lookAt);
  99495. this._dragPlane.lookAt(this._lookAt);
  99496. }
  99497. else if (this._options.dragPlaneNormal) {
  99498. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragPlaneNormal, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragPlaneNormal);
  99499. this._dragPlane.position.copyFrom(this._pointA);
  99500. this._pointA.subtractToRef(this._localAxis, this._lookAt);
  99501. this._dragPlane.lookAt(this._lookAt);
  99502. }
  99503. else {
  99504. this._dragPlane.position.copyFrom(this._pointA);
  99505. this._dragPlane.lookAt(ray.origin);
  99506. }
  99507. this._dragPlane.computeWorldMatrix(true);
  99508. };
  99509. /**
  99510. * Detaches the behavior from the mesh
  99511. */
  99512. PointerDragBehavior.prototype.detach = function () {
  99513. if (this._pointerObserver) {
  99514. this._scene.onPointerObservable.remove(this._pointerObserver);
  99515. }
  99516. if (this._beforeRenderObserver) {
  99517. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  99518. }
  99519. };
  99520. PointerDragBehavior._AnyMouseID = -2;
  99521. return PointerDragBehavior;
  99522. }());
  99523. BABYLON.PointerDragBehavior = PointerDragBehavior;
  99524. })(BABYLON || (BABYLON = {}));
  99525. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  99526. var BABYLON;
  99527. (function (BABYLON) {
  99528. /**
  99529. * A behavior that when attached to a mesh will allow the mesh to be scaled
  99530. */
  99531. var MultiPointerScaleBehavior = /** @class */ (function () {
  99532. /**
  99533. * Instantiate a new behavior that when attached to a mesh will allow the mesh to be scaled
  99534. */
  99535. function MultiPointerScaleBehavior() {
  99536. this._startDistance = 0;
  99537. this._initialScale = new BABYLON.Vector3(0, 0, 0);
  99538. this._targetScale = new BABYLON.Vector3(0, 0, 0);
  99539. this._sceneRenderObserver = null;
  99540. this._dragBehaviorA = new BABYLON.PointerDragBehavior({});
  99541. this._dragBehaviorA.moveAttached = false;
  99542. this._dragBehaviorB = new BABYLON.PointerDragBehavior({});
  99543. this._dragBehaviorB.moveAttached = false;
  99544. }
  99545. Object.defineProperty(MultiPointerScaleBehavior.prototype, "name", {
  99546. /**
  99547. * The name of the behavior
  99548. */
  99549. get: function () {
  99550. return "MultiPointerScale";
  99551. },
  99552. enumerable: true,
  99553. configurable: true
  99554. });
  99555. /**
  99556. * Initializes the behavior
  99557. */
  99558. MultiPointerScaleBehavior.prototype.init = function () { };
  99559. MultiPointerScaleBehavior.prototype._getCurrentDistance = function () {
  99560. return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length();
  99561. };
  99562. /**
  99563. * Attaches the scale behavior the passed in mesh
  99564. * @param ownerNode The mesh that will be scaled around once attached
  99565. */
  99566. MultiPointerScaleBehavior.prototype.attach = function (ownerNode) {
  99567. var _this = this;
  99568. this._ownerNode = ownerNode;
  99569. // Create 2 drag behaviors such that each will only be triggered by a separate pointer
  99570. this._dragBehaviorA.onDragStartObservable.add(function (e) {
  99571. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  99572. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  99573. _this._dragBehaviorA.releaseDrag();
  99574. }
  99575. else {
  99576. _this._initialScale.copyFrom(ownerNode.scaling);
  99577. _this._startDistance = _this._getCurrentDistance();
  99578. }
  99579. }
  99580. });
  99581. this._dragBehaviorB.onDragStartObservable.add(function (e) {
  99582. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  99583. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  99584. _this._dragBehaviorB.releaseDrag();
  99585. }
  99586. else {
  99587. _this._initialScale.copyFrom(ownerNode.scaling);
  99588. _this._startDistance = _this._getCurrentDistance();
  99589. }
  99590. }
  99591. });
  99592. // Once both drag behaviors are active scale based on the distance between the two pointers
  99593. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  99594. behavior.onDragObservable.add(function () {
  99595. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  99596. var ratio = _this._getCurrentDistance() / _this._startDistance;
  99597. _this._initialScale.scaleToRef(ratio, _this._targetScale);
  99598. }
  99599. });
  99600. });
  99601. ownerNode.addBehavior(this._dragBehaviorA);
  99602. ownerNode.addBehavior(this._dragBehaviorB);
  99603. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  99604. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  99605. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  99606. var change = _this._targetScale.subtract(ownerNode.scaling).scaleInPlace(0.1);
  99607. if (change.length() > 0.01) {
  99608. ownerNode.scaling.addInPlace(change);
  99609. }
  99610. }
  99611. });
  99612. };
  99613. /**
  99614. * Detaches the behavior from the mesh
  99615. */
  99616. MultiPointerScaleBehavior.prototype.detach = function () {
  99617. var _this = this;
  99618. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  99619. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  99620. behavior.onDragStartObservable.clear();
  99621. behavior.onDragObservable.clear();
  99622. _this._ownerNode.removeBehavior(behavior);
  99623. });
  99624. };
  99625. return MultiPointerScaleBehavior;
  99626. }());
  99627. BABYLON.MultiPointerScaleBehavior = MultiPointerScaleBehavior;
  99628. })(BABYLON || (BABYLON = {}));
  99629. //# sourceMappingURL=babylon.multiPointerScaleBehavior.js.map
  99630. var BABYLON;
  99631. (function (BABYLON) {
  99632. /**
  99633. * 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
  99634. */
  99635. var SixDofDragBehavior = /** @class */ (function () {
  99636. /**
  99637. * Instantiates 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
  99638. */
  99639. function SixDofDragBehavior() {
  99640. this._sceneRenderObserver = null;
  99641. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  99642. this._moving = false;
  99643. this._startingOrientation = new BABYLON.Quaternion();
  99644. /**
  99645. * How much faster the object should move when the controller is moving towards it. This is useful to bring objects that are far away from the user to them faster. Set this to 0 to avoid any speed increase. (Default: 3)
  99646. */
  99647. this.zDragFactor = 3;
  99648. /**
  99649. * If the behavior is currently in a dragging state
  99650. */
  99651. this.dragging = false;
  99652. /**
  99653. * 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)
  99654. */
  99655. this.dragDeltaRatio = 0.2;
  99656. /**
  99657. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  99658. */
  99659. this.currentDraggingPointerID = -1;
  99660. /**
  99661. * If camera controls should be detached during the drag
  99662. */
  99663. this.detachCameraControls = true;
  99664. /**
  99665. * Fires each time a drag starts
  99666. */
  99667. this.onDragStartObservable = new BABYLON.Observable();
  99668. /**
  99669. * Fires each time a drag ends (eg. mouse release after drag)
  99670. */
  99671. this.onDragEndObservable = new BABYLON.Observable();
  99672. }
  99673. Object.defineProperty(SixDofDragBehavior.prototype, "name", {
  99674. /**
  99675. * The name of the behavior
  99676. */
  99677. get: function () {
  99678. return "SixDofDrag";
  99679. },
  99680. enumerable: true,
  99681. configurable: true
  99682. });
  99683. /**
  99684. * Initializes the behavior
  99685. */
  99686. SixDofDragBehavior.prototype.init = function () { };
  99687. /**
  99688. * Attaches the scale behavior the passed in mesh
  99689. * @param ownerNode The mesh that will be scaled around once attached
  99690. */
  99691. SixDofDragBehavior.prototype.attach = function (ownerNode) {
  99692. var _this = this;
  99693. this._ownerNode = ownerNode;
  99694. this._scene = this._ownerNode.getScene();
  99695. if (!SixDofDragBehavior._virtualScene) {
  99696. SixDofDragBehavior._virtualScene = new BABYLON.Scene(this._scene.getEngine());
  99697. this._scene.getEngine().scenes.pop();
  99698. }
  99699. var pickedMesh = null;
  99700. var lastSixDofOriginPosition = new BABYLON.Vector3(0, 0, 0);
  99701. // Setup virtual meshes to be used for dragging without dirtying the existing scene
  99702. this._virtualOriginMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  99703. this._virtualOriginMesh.rotationQuaternion = new BABYLON.Quaternion();
  99704. this._virtualDragMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  99705. this._virtualDragMesh.rotationQuaternion = new BABYLON.Quaternion();
  99706. var pickPredicate = function (m) {
  99707. return _this._ownerNode == m || m.isDescendantOf(_this._ownerNode);
  99708. };
  99709. var attachedElement = null;
  99710. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  99711. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  99712. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  99713. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  99714. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  99715. }
  99716. pickedMesh = _this._ownerNode;
  99717. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(pickedMesh);
  99718. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  99719. // Set position and orientation of the controller
  99720. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  99721. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  99722. // Attach the virtual drag mesh to the virtual origin mesh so it can be dragged
  99723. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  99724. pickedMesh.computeWorldMatrix();
  99725. _this._virtualDragMesh.position.copyFrom(pickedMesh.absolutePosition);
  99726. if (!pickedMesh.rotationQuaternion) {
  99727. pickedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(pickedMesh.rotation.y, pickedMesh.rotation.x, pickedMesh.rotation.z);
  99728. }
  99729. var oldParent = pickedMesh.parent;
  99730. pickedMesh.setParent(null);
  99731. _this._virtualDragMesh.rotationQuaternion.copyFrom(pickedMesh.rotationQuaternion);
  99732. pickedMesh.setParent(oldParent);
  99733. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  99734. // Update state
  99735. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  99736. _this.dragging = true;
  99737. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  99738. // Detatch camera controls
  99739. if (_this.detachCameraControls && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  99740. if (_this._scene.activeCamera.inputs.attachedElement) {
  99741. attachedElement = _this._scene.activeCamera.inputs.attachedElement;
  99742. _this._scene.activeCamera.detachControl(_this._scene.activeCamera.inputs.attachedElement);
  99743. }
  99744. else {
  99745. attachedElement = null;
  99746. }
  99747. }
  99748. BABYLON.BoundingBoxGizmo._RestorePivotPoint(pickedMesh);
  99749. _this.onDragStartObservable.notifyObservers({});
  99750. }
  99751. }
  99752. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  99753. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  99754. _this.dragging = false;
  99755. _this._moving = false;
  99756. _this.currentDraggingPointerID = -1;
  99757. pickedMesh = null;
  99758. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  99759. // Reattach camera controls
  99760. if (_this.detachCameraControls && attachedElement && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  99761. _this._scene.activeCamera.attachControl(attachedElement, true);
  99762. }
  99763. _this.onDragEndObservable.notifyObservers({});
  99764. }
  99765. }
  99766. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  99767. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray && pickedMesh) {
  99768. var zDragFactor = _this.zDragFactor;
  99769. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  99770. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  99771. zDragFactor = 0;
  99772. }
  99773. // Calculate controller drag distance in controller space
  99774. var originDragDifference = pointerInfo.pickInfo.ray.origin.subtract(lastSixDofOriginPosition);
  99775. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  99776. var localOriginDragDifference = -BABYLON.Vector3.Dot(originDragDifference, pointerInfo.pickInfo.ray.direction);
  99777. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  99778. // Determine how much the controller moved to/away towards the dragged object and use this to move the object further when its further away
  99779. _this._virtualDragMesh.position.z -= _this._virtualDragMesh.position.z < 1 ? localOriginDragDifference * _this.zDragFactor : localOriginDragDifference * zDragFactor * _this._virtualDragMesh.position.z;
  99780. if (_this._virtualDragMesh.position.z < 0) {
  99781. _this._virtualDragMesh.position.z = 0;
  99782. }
  99783. // Update the controller position
  99784. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  99785. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  99786. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  99787. // Move the virtualObjectsPosition into the picked mesh's space if needed
  99788. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  99789. if (pickedMesh.parent) {
  99790. BABYLON.Vector3.TransformCoordinatesToRef(_this._targetPosition, BABYLON.Matrix.Invert(pickedMesh.parent.getWorldMatrix()), _this._targetPosition);
  99791. }
  99792. if (!_this._moving) {
  99793. _this._startingOrientation.copyFrom(_this._virtualDragMesh.rotationQuaternion);
  99794. }
  99795. _this._moving = true;
  99796. }
  99797. }
  99798. });
  99799. var tmpQuaternion = new BABYLON.Quaternion();
  99800. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  99801. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  99802. if (_this.dragging && _this._moving && pickedMesh) {
  99803. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(pickedMesh);
  99804. // Slowly move mesh to avoid jitter
  99805. pickedMesh.position.addInPlace(_this._targetPosition.subtract(pickedMesh.position).scale(_this.dragDeltaRatio));
  99806. // Get change in rotation
  99807. tmpQuaternion.copyFrom(_this._startingOrientation);
  99808. tmpQuaternion.x = -tmpQuaternion.x;
  99809. tmpQuaternion.y = -tmpQuaternion.y;
  99810. tmpQuaternion.z = -tmpQuaternion.z;
  99811. _this._virtualDragMesh.rotationQuaternion.multiplyToRef(tmpQuaternion, tmpQuaternion);
  99812. // Convert change in rotation to only y axis rotation
  99813. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpQuaternion.toEulerAngles("xyz").y, 0, 0, tmpQuaternion);
  99814. tmpQuaternion.multiplyToRef(_this._startingOrientation, tmpQuaternion);
  99815. // Slowly move mesh to avoid jitter
  99816. var oldParent = pickedMesh.parent;
  99817. pickedMesh.setParent(null);
  99818. BABYLON.Quaternion.SlerpToRef(pickedMesh.rotationQuaternion, tmpQuaternion, _this.dragDeltaRatio, pickedMesh.rotationQuaternion);
  99819. pickedMesh.setParent(oldParent);
  99820. BABYLON.BoundingBoxGizmo._RestorePivotPoint(pickedMesh);
  99821. }
  99822. });
  99823. };
  99824. /**
  99825. * Detaches the behavior from the mesh
  99826. */
  99827. SixDofDragBehavior.prototype.detach = function () {
  99828. if (this._scene) {
  99829. this._scene.onPointerObservable.remove(this._pointerObserver);
  99830. }
  99831. if (this._ownerNode) {
  99832. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  99833. }
  99834. if (this._virtualOriginMesh) {
  99835. this._virtualOriginMesh.dispose();
  99836. }
  99837. if (this._virtualDragMesh) {
  99838. this._virtualDragMesh.dispose();
  99839. }
  99840. this.onDragEndObservable.clear();
  99841. this.onDragStartObservable.clear();
  99842. };
  99843. return SixDofDragBehavior;
  99844. }());
  99845. BABYLON.SixDofDragBehavior = SixDofDragBehavior;
  99846. })(BABYLON || (BABYLON = {}));
  99847. //# sourceMappingURL=babylon.sixDofDragBehavior.js.map
  99848. var BABYLON;
  99849. (function (BABYLON) {
  99850. /**
  99851. * @hidden
  99852. */
  99853. var FaceDirectionInfo = /** @class */ (function () {
  99854. function FaceDirectionInfo(direction, rotatedDirection, diff, ignore) {
  99855. if (rotatedDirection === void 0) { rotatedDirection = new BABYLON.Vector3(); }
  99856. if (diff === void 0) { diff = 0; }
  99857. if (ignore === void 0) { ignore = false; }
  99858. this.direction = direction;
  99859. this.rotatedDirection = rotatedDirection;
  99860. this.diff = diff;
  99861. this.ignore = ignore;
  99862. }
  99863. return FaceDirectionInfo;
  99864. }());
  99865. /**
  99866. * A behavior that when attached to a mesh will will place a specified node on the meshes face pointing towards the camera
  99867. */
  99868. var AttachToBoxBehavior = /** @class */ (function () {
  99869. /**
  99870. * Creates the AttachToBoxBehavior, used to attach UI to the closest face of the box to a camera
  99871. * @param ui The transform node that should be attched to the mesh
  99872. */
  99873. function AttachToBoxBehavior(ui) {
  99874. this.ui = ui;
  99875. /**
  99876. * The name of the behavior
  99877. */
  99878. this.name = "AttachToBoxBehavior";
  99879. /**
  99880. * The distance away from the face of the mesh that the UI should be attached to (default: 0.15)
  99881. */
  99882. this.distanceAwayFromFace = 0.15;
  99883. /**
  99884. * The distance from the bottom of the face that the UI should be attached to (default: 0.15)
  99885. */
  99886. this.distanceAwayFromBottomOfFace = 0.15;
  99887. this._faceVectors = [new FaceDirectionInfo(BABYLON.Vector3.Up()), new FaceDirectionInfo(BABYLON.Vector3.Down()), new FaceDirectionInfo(BABYLON.Vector3.Left()), new FaceDirectionInfo(BABYLON.Vector3.Right()), new FaceDirectionInfo(BABYLON.Vector3.Forward()), new FaceDirectionInfo(BABYLON.Vector3.Forward().scaleInPlace(-1))];
  99888. this._tmpMatrix = new BABYLON.Matrix();
  99889. this._tmpVector = new BABYLON.Vector3();
  99890. this._zeroVector = BABYLON.Vector3.Zero();
  99891. this._lookAtTmpMatrix = new BABYLON.Matrix();
  99892. /* Does nothing */
  99893. }
  99894. /**
  99895. * Initializes the behavior
  99896. */
  99897. AttachToBoxBehavior.prototype.init = function () {
  99898. /* Does nothing */
  99899. };
  99900. AttachToBoxBehavior.prototype._closestFace = function (targetDirection) {
  99901. var _this = this;
  99902. // Go over each face and calculate the angle between the face's normal and targetDirection
  99903. this._faceVectors.forEach(function (v) {
  99904. if (!_this._target.rotationQuaternion) {
  99905. _this._target.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._target.rotation.y, _this._target.rotation.x, _this._target.rotation.z);
  99906. }
  99907. _this._target.rotationQuaternion.toRotationMatrix(_this._tmpMatrix);
  99908. BABYLON.Vector3.TransformCoordinatesToRef(v.direction, _this._tmpMatrix, v.rotatedDirection);
  99909. v.diff = BABYLON.Vector3.GetAngleBetweenVectors(v.rotatedDirection, targetDirection, BABYLON.Vector3.Cross(v.rotatedDirection, targetDirection));
  99910. });
  99911. // Return the face information of the one with the normal closeset to target direction
  99912. return this._faceVectors.reduce(function (min, p) {
  99913. if (min.ignore) {
  99914. return p;
  99915. }
  99916. else if (p.ignore) {
  99917. return min;
  99918. }
  99919. else {
  99920. return min.diff < p.diff ? min : p;
  99921. }
  99922. }, this._faceVectors[0]);
  99923. };
  99924. AttachToBoxBehavior.prototype._lookAtToRef = function (pos, up, ref) {
  99925. if (up === void 0) { up = new BABYLON.Vector3(0, 1, 0); }
  99926. BABYLON.Matrix.LookAtLHToRef(this._zeroVector, pos, up, this._lookAtTmpMatrix);
  99927. this._lookAtTmpMatrix.invert();
  99928. BABYLON.Quaternion.FromRotationMatrixToRef(this._lookAtTmpMatrix, ref);
  99929. };
  99930. /**
  99931. * Attaches the AttachToBoxBehavior to the passed in mesh
  99932. * @param target The mesh that the specified node will be attached to
  99933. */
  99934. AttachToBoxBehavior.prototype.attach = function (target) {
  99935. var _this = this;
  99936. this._target = target;
  99937. this._scene = this._target.getScene();
  99938. // Every frame, update the app bars position
  99939. this._onRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  99940. if (!_this._scene.activeCamera) {
  99941. return;
  99942. }
  99943. // Find the face closest to the cameras position
  99944. var cameraPos = _this._scene.activeCamera.position;
  99945. if (_this._scene.activeCamera.devicePosition) {
  99946. cameraPos = _this._scene.activeCamera.devicePosition;
  99947. }
  99948. var facing = _this._closestFace(cameraPos.subtract(target.position));
  99949. if (_this._scene.activeCamera.leftCamera) {
  99950. _this._scene.activeCamera.leftCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  99951. }
  99952. else {
  99953. _this._scene.activeCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  99954. }
  99955. // Get camera up direction
  99956. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Vector3.Up(), _this._tmpMatrix, _this._tmpVector);
  99957. // Ignore faces to not select a parrelel face for the up vector of the UI
  99958. _this._faceVectors.forEach(function (v) {
  99959. if (facing.direction.x && v.direction.x) {
  99960. v.ignore = true;
  99961. }
  99962. if (facing.direction.y && v.direction.y) {
  99963. v.ignore = true;
  99964. }
  99965. if (facing.direction.z && v.direction.z) {
  99966. v.ignore = true;
  99967. }
  99968. });
  99969. var facingUp = _this._closestFace(_this._tmpVector);
  99970. // Unignore faces
  99971. _this._faceVectors.forEach(function (v) {
  99972. v.ignore = false;
  99973. });
  99974. // Position the app bar on that face
  99975. _this.ui.position.copyFrom(target.position);
  99976. if (facing.direction.x) {
  99977. facing.rotatedDirection.scaleToRef((target.scaling.x / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  99978. _this.ui.position.addInPlace(_this._tmpVector);
  99979. }
  99980. if (facing.direction.y) {
  99981. facing.rotatedDirection.scaleToRef((target.scaling.y / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  99982. _this.ui.position.addInPlace(_this._tmpVector);
  99983. }
  99984. if (facing.direction.z) {
  99985. facing.rotatedDirection.scaleToRef((target.scaling.z / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  99986. _this.ui.position.addInPlace(_this._tmpVector);
  99987. }
  99988. // Rotate to be oriented properly to the camera
  99989. if (!_this.ui.rotationQuaternion) {
  99990. _this.ui.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.ui.rotation.y, _this.ui.rotation.x, _this.ui.rotation.z);
  99991. }
  99992. facing.rotatedDirection.scaleToRef(-1, _this._tmpVector);
  99993. _this._lookAtToRef(_this._tmpVector, facingUp.rotatedDirection, _this.ui.rotationQuaternion);
  99994. // Place ui the correct distance from the bottom of the mesh
  99995. if (facingUp.direction.x) {
  99996. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.x / 2, _this._tmpVector);
  99997. }
  99998. if (facingUp.direction.y) {
  99999. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.y / 2, _this._tmpVector);
  100000. }
  100001. if (facingUp.direction.z) {
  100002. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.z / 2, _this._tmpVector);
  100003. }
  100004. _this.ui.position.addInPlace(_this._tmpVector);
  100005. });
  100006. };
  100007. /**
  100008. * Detaches the behavior from the mesh
  100009. */
  100010. AttachToBoxBehavior.prototype.detach = function () {
  100011. this._scene.onBeforeRenderObservable.remove(this._onRenderObserver);
  100012. };
  100013. return AttachToBoxBehavior;
  100014. }());
  100015. BABYLON.AttachToBoxBehavior = AttachToBoxBehavior;
  100016. })(BABYLON || (BABYLON = {}));
  100017. //# sourceMappingURL=babylon.attachToBoxBehavior.js.map
  100018. var BABYLON;
  100019. (function (BABYLON) {
  100020. /**
  100021. * A behavior that when attached to a mesh will allow the mesh to fade in and out
  100022. */
  100023. var FadeInOutBehavior = /** @class */ (function () {
  100024. /**
  100025. * Instatiates the FadeInOutBehavior
  100026. */
  100027. function FadeInOutBehavior() {
  100028. var _this = this;
  100029. /**
  100030. * Time in milliseconds to delay before fading in (Default: 0)
  100031. */
  100032. this.delay = 0;
  100033. /**
  100034. * Time in milliseconds for the mesh to fade in (Default: 300)
  100035. */
  100036. this.fadeInTime = 300;
  100037. this._millisecondsPerFrame = 1000 / 60;
  100038. this._hovered = false;
  100039. this._hoverValue = 0;
  100040. this._ownerNode = null;
  100041. this._update = function () {
  100042. if (_this._ownerNode) {
  100043. _this._hoverValue += _this._hovered ? _this._millisecondsPerFrame : -_this._millisecondsPerFrame;
  100044. _this._setAllVisibility(_this._ownerNode, (_this._hoverValue - _this.delay) / _this.fadeInTime);
  100045. if (_this._ownerNode.visibility > 1) {
  100046. _this._setAllVisibility(_this._ownerNode, 1);
  100047. _this._hoverValue = _this.fadeInTime + _this.delay;
  100048. return;
  100049. }
  100050. else if (_this._ownerNode.visibility < 0) {
  100051. _this._setAllVisibility(_this._ownerNode, 0);
  100052. if (_this._hoverValue < 0) {
  100053. _this._hoverValue = 0;
  100054. return;
  100055. }
  100056. }
  100057. setTimeout(_this._update, _this._millisecondsPerFrame);
  100058. }
  100059. };
  100060. }
  100061. Object.defineProperty(FadeInOutBehavior.prototype, "name", {
  100062. /**
  100063. * The name of the behavior
  100064. */
  100065. get: function () {
  100066. return "FadeInOut";
  100067. },
  100068. enumerable: true,
  100069. configurable: true
  100070. });
  100071. /**
  100072. * Initializes the behavior
  100073. */
  100074. FadeInOutBehavior.prototype.init = function () {
  100075. };
  100076. /**
  100077. * Attaches the fade behavior on the passed in mesh
  100078. * @param ownerNode The mesh that will be faded in/out once attached
  100079. */
  100080. FadeInOutBehavior.prototype.attach = function (ownerNode) {
  100081. this._ownerNode = ownerNode;
  100082. this._setAllVisibility(this._ownerNode, 0);
  100083. };
  100084. /**
  100085. * Detaches the behavior from the mesh
  100086. */
  100087. FadeInOutBehavior.prototype.detach = function () {
  100088. this._ownerNode = null;
  100089. };
  100090. /**
  100091. * Triggers the mesh to begin fading in or out
  100092. * @param value if the object should fade in or out (true to fade in)
  100093. */
  100094. FadeInOutBehavior.prototype.fadeIn = function (value) {
  100095. this._hovered = value;
  100096. this._update();
  100097. };
  100098. FadeInOutBehavior.prototype._setAllVisibility = function (mesh, value) {
  100099. var _this = this;
  100100. mesh.visibility = value;
  100101. mesh.getChildMeshes().forEach(function (c) {
  100102. _this._setAllVisibility(c, value);
  100103. });
  100104. };
  100105. return FadeInOutBehavior;
  100106. }());
  100107. BABYLON.FadeInOutBehavior = FadeInOutBehavior;
  100108. })(BABYLON || (BABYLON = {}));
  100109. //# sourceMappingURL=babylon.fadeInOutBehavior.js.map
  100110. var BABYLON;
  100111. (function (BABYLON) {
  100112. /**
  100113. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  100114. */
  100115. var Gizmo = /** @class */ (function () {
  100116. /**
  100117. * Creates a gizmo
  100118. * @param gizmoLayer The utility layer the gizmo will be added to
  100119. */
  100120. function Gizmo(
  100121. /** The utility layer the gizmo will be added to */
  100122. gizmoLayer) {
  100123. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  100124. var _this = this;
  100125. this.gizmoLayer = gizmoLayer;
  100126. /**
  100127. * Ratio for the scale of the gizmo (Default: 1)
  100128. */
  100129. this.scaleRatio = 1;
  100130. this._tmpMatrix = new BABYLON.Matrix();
  100131. /**
  100132. * If a custom mesh has been set (Default: false)
  100133. */
  100134. this._customMeshSet = false;
  100135. /**
  100136. * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)
  100137. */
  100138. this.updateGizmoRotationToMatchAttachedMesh = true;
  100139. /**
  100140. * If set the gizmo's position will be updated to match the attached mesh each frame (Default: true)
  100141. */
  100142. this.updateGizmoPositionToMatchAttachedMesh = true;
  100143. /**
  100144. * When set, the gizmo will always appear the same size no matter where the camera is (default: false)
  100145. */
  100146. this._updateScale = true;
  100147. this._interactionsEnabled = true;
  100148. this._tempVector = new BABYLON.Vector3();
  100149. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  100150. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  100151. _this._update();
  100152. });
  100153. this.attachedMesh = null;
  100154. }
  100155. Object.defineProperty(Gizmo.prototype, "attachedMesh", {
  100156. /**
  100157. * Mesh that the gizmo will be attached to. (eg. on a drag gizmo the mesh that will be dragged)
  100158. * * When set, interactions will be enabled
  100159. */
  100160. get: function () {
  100161. return this._attachedMesh;
  100162. },
  100163. set: function (value) {
  100164. this._attachedMesh = value;
  100165. this._rootMesh.setEnabled(value ? true : false);
  100166. this._attachedMeshChanged(value);
  100167. },
  100168. enumerable: true,
  100169. configurable: true
  100170. });
  100171. /**
  100172. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  100173. * @param mesh The mesh to replace the default mesh of the gizmo
  100174. */
  100175. Gizmo.prototype.setCustomMesh = function (mesh) {
  100176. if (mesh.getScene() != this.gizmoLayer.utilityLayerScene) {
  100177. throw "When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";
  100178. }
  100179. this._rootMesh.getChildMeshes().forEach(function (c) {
  100180. c.dispose();
  100181. });
  100182. mesh.parent = this._rootMesh;
  100183. this._customMeshSet = true;
  100184. };
  100185. Gizmo.prototype._attachedMeshChanged = function (value) {
  100186. };
  100187. /**
  100188. * @hidden
  100189. * Updates the gizmo to match the attached mesh's position/rotation
  100190. */
  100191. Gizmo.prototype._update = function () {
  100192. if (this.attachedMesh) {
  100193. if (this.updateGizmoRotationToMatchAttachedMesh) {
  100194. if (!this._rootMesh.rotationQuaternion) {
  100195. this._rootMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._rootMesh.rotation.y, this._rootMesh.rotation.x, this._rootMesh.rotation.z);
  100196. }
  100197. // Remove scaling before getting rotation matrix to get rotation matrix unmodified by scale
  100198. this._tempVector.copyFrom(this.attachedMesh.scaling);
  100199. if (this.attachedMesh.scaling.x < 0) {
  100200. this.attachedMesh.scaling.x *= -1;
  100201. }
  100202. if (this.attachedMesh.scaling.y < 0) {
  100203. this.attachedMesh.scaling.y *= -1;
  100204. }
  100205. if (this.attachedMesh.scaling.z < 0) {
  100206. this.attachedMesh.scaling.z *= -1;
  100207. }
  100208. this.attachedMesh.computeWorldMatrix().getRotationMatrixToRef(this._tmpMatrix);
  100209. this.attachedMesh.scaling.copyFrom(this._tempVector);
  100210. this.attachedMesh.computeWorldMatrix();
  100211. BABYLON.Quaternion.FromRotationMatrixToRef(this._tmpMatrix, this._rootMesh.rotationQuaternion);
  100212. }
  100213. else if (this._rootMesh.rotationQuaternion) {
  100214. this._rootMesh.rotationQuaternion.set(0, 0, 0, 1);
  100215. }
  100216. if (this.updateGizmoPositionToMatchAttachedMesh) {
  100217. this._rootMesh.position.copyFrom(this.attachedMesh.absolutePosition);
  100218. }
  100219. if (this._updateScale && this.gizmoLayer.utilityLayerScene.activeCamera && this.attachedMesh) {
  100220. var cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.position;
  100221. if (this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition) {
  100222. cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition;
  100223. }
  100224. this._rootMesh.position.subtractToRef(cameraPosition, this._tempVector);
  100225. var dist = this._tempVector.length() * this.scaleRatio;
  100226. this._rootMesh.scaling.set(dist, dist, dist);
  100227. }
  100228. }
  100229. };
  100230. /**
  100231. * Disposes of the gizmo
  100232. */
  100233. Gizmo.prototype.dispose = function () {
  100234. this._rootMesh.dispose();
  100235. if (this._beforeRenderObserver) {
  100236. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  100237. }
  100238. };
  100239. return Gizmo;
  100240. }());
  100241. BABYLON.Gizmo = Gizmo;
  100242. })(BABYLON || (BABYLON = {}));
  100243. //# sourceMappingURL=babylon.gizmo.js.map
  100244. var BABYLON;
  100245. (function (BABYLON) {
  100246. /**
  100247. * Single axis drag gizmo
  100248. */
  100249. var AxisDragGizmo = /** @class */ (function (_super) {
  100250. __extends(AxisDragGizmo, _super);
  100251. /**
  100252. * Creates an AxisDragGizmo
  100253. * @param gizmoLayer The utility layer the gizmo will be added to
  100254. * @param dragAxis The axis which the gizmo will be able to drag on
  100255. * @param color The color of the gizmo
  100256. */
  100257. function AxisDragGizmo(dragAxis, color, gizmoLayer) {
  100258. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  100259. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  100260. var _this = _super.call(this, gizmoLayer) || this;
  100261. _this._pointerObserver = null;
  100262. /**
  100263. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  100264. */
  100265. _this.snapDistance = 0;
  100266. /**
  100267. * Event that fires each time the gizmo snaps to a new location.
  100268. * * snapDistance is the the change in distance
  100269. */
  100270. _this.onSnapObservable = new BABYLON.Observable();
  100271. // Create Material
  100272. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  100273. coloredMaterial.disableLighting = true;
  100274. coloredMaterial.emissiveColor = color;
  100275. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  100276. hoverMaterial.disableLighting = true;
  100277. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  100278. // Build mesh on root node
  100279. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  100280. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 1.5, diameterBottom: 0.75, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  100281. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  100282. arrowTail.color = coloredMaterial.emissiveColor;
  100283. arrow.addChild(arrowMesh);
  100284. arrow.addChild(arrowTail);
  100285. // Position arrow pointing in its drag axis
  100286. arrowMesh.scaling.scaleInPlace(0.05);
  100287. arrowMesh.material = coloredMaterial;
  100288. arrowMesh.rotation.x = Math.PI / 2;
  100289. arrowMesh.position.z += 0.3;
  100290. arrowTail.scaling.scaleInPlace(0.26);
  100291. arrowTail.rotation.x = Math.PI / 2;
  100292. arrowTail.material = coloredMaterial;
  100293. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  100294. arrow.scaling.scaleInPlace(1 / 3);
  100295. _this._rootMesh.addChild(arrow);
  100296. var currentSnapDragDistance = 0;
  100297. var tmpVector = new BABYLON.Vector3();
  100298. var tmpSnapEvent = { snapDistance: 0 };
  100299. // Add drag behavior to handle events when the gizmo is dragged
  100300. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  100301. _this.dragBehavior.moveAttached = false;
  100302. _this._rootMesh.addBehavior(_this.dragBehavior);
  100303. var localDelta = new BABYLON.Vector3();
  100304. var tmpMatrix = new BABYLON.Matrix();
  100305. _this.dragBehavior.onDragObservable.add(function (event) {
  100306. if (_this.attachedMesh) {
  100307. // Convert delta to local translation if it has a parent
  100308. if (_this.attachedMesh.parent) {
  100309. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  100310. tmpMatrix.setTranslationFromFloats(0, 0, 0);
  100311. BABYLON.Vector3.TransformCoordinatesToRef(event.delta, tmpMatrix, localDelta);
  100312. }
  100313. else {
  100314. localDelta.copyFrom(event.delta);
  100315. }
  100316. // Snapping logic
  100317. if (_this.snapDistance == 0) {
  100318. _this.attachedMesh.position.addInPlace(localDelta);
  100319. }
  100320. else {
  100321. currentSnapDragDistance += event.dragDistance;
  100322. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  100323. var dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / _this.snapDistance);
  100324. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  100325. localDelta.normalizeToRef(tmpVector);
  100326. tmpVector.scaleInPlace(_this.snapDistance * dragSteps);
  100327. _this.attachedMesh.position.addInPlace(tmpVector);
  100328. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  100329. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  100330. }
  100331. }
  100332. }
  100333. });
  100334. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  100335. if (_this._customMeshSet) {
  100336. return;
  100337. }
  100338. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  100339. var material = isHovered ? hoverMaterial : coloredMaterial;
  100340. _this._rootMesh.getChildMeshes().forEach(function (m) {
  100341. m.material = material;
  100342. if (m.color) {
  100343. m.color = material.emissiveColor;
  100344. }
  100345. });
  100346. });
  100347. return _this;
  100348. }
  100349. AxisDragGizmo.prototype._attachedMeshChanged = function (value) {
  100350. if (this.dragBehavior) {
  100351. this.dragBehavior.enabled = value ? true : false;
  100352. }
  100353. };
  100354. /**
  100355. * Disposes of the gizmo
  100356. */
  100357. AxisDragGizmo.prototype.dispose = function () {
  100358. this.onSnapObservable.clear();
  100359. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  100360. this.dragBehavior.detach();
  100361. _super.prototype.dispose.call(this);
  100362. };
  100363. return AxisDragGizmo;
  100364. }(BABYLON.Gizmo));
  100365. BABYLON.AxisDragGizmo = AxisDragGizmo;
  100366. })(BABYLON || (BABYLON = {}));
  100367. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  100368. var BABYLON;
  100369. (function (BABYLON) {
  100370. /**
  100371. * Single axis scale gizmo
  100372. */
  100373. var AxisScaleGizmo = /** @class */ (function (_super) {
  100374. __extends(AxisScaleGizmo, _super);
  100375. /**
  100376. * Creates an AxisScaleGizmo
  100377. * @param gizmoLayer The utility layer the gizmo will be added to
  100378. * @param dragAxis The axis which the gizmo will be able to scale on
  100379. * @param color The color of the gizmo
  100380. */
  100381. function AxisScaleGizmo(dragAxis, color, gizmoLayer) {
  100382. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  100383. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  100384. var _this = _super.call(this, gizmoLayer) || this;
  100385. _this._pointerObserver = null;
  100386. /**
  100387. * Scale distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  100388. */
  100389. _this.snapDistance = 0;
  100390. /**
  100391. * Event that fires each time the gizmo snaps to a new location.
  100392. * * snapDistance is the the change in distance
  100393. */
  100394. _this.onSnapObservable = new BABYLON.Observable();
  100395. /**
  100396. * If the scaling operation should be done on all axis (default: false)
  100397. */
  100398. _this.uniformScaling = false;
  100399. // Create Material
  100400. _this._coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  100401. _this._coloredMaterial.disableLighting = true;
  100402. _this._coloredMaterial.emissiveColor = color;
  100403. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  100404. hoverMaterial.disableLighting = true;
  100405. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  100406. // Build mesh on root node
  100407. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  100408. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 0.4 }, gizmoLayer.utilityLayerScene);
  100409. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  100410. arrowTail.color = _this._coloredMaterial.emissiveColor;
  100411. arrow.addChild(arrowMesh);
  100412. arrow.addChild(arrowTail);
  100413. // Position arrow pointing in its drag axis
  100414. arrowMesh.scaling.scaleInPlace(0.1);
  100415. arrowMesh.material = _this._coloredMaterial;
  100416. arrowMesh.rotation.x = Math.PI / 2;
  100417. arrowMesh.position.z += 0.3;
  100418. arrowTail.scaling.scaleInPlace(0.26);
  100419. arrowTail.rotation.x = Math.PI / 2;
  100420. arrowTail.material = _this._coloredMaterial;
  100421. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  100422. _this._rootMesh.addChild(arrow);
  100423. arrow.scaling.scaleInPlace(1 / 3);
  100424. // Add drag behavior to handle events when the gizmo is dragged
  100425. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  100426. _this.dragBehavior.moveAttached = false;
  100427. _this._rootMesh.addBehavior(_this.dragBehavior);
  100428. var currentSnapDragDistance = 0;
  100429. var tmpVector = new BABYLON.Vector3();
  100430. var tmpSnapEvent = { snapDistance: 0 };
  100431. _this.dragBehavior.onDragObservable.add(function (event) {
  100432. if (_this.attachedMesh) {
  100433. // Snapping logic
  100434. var snapped = false;
  100435. var dragSteps = 0;
  100436. if (_this.uniformScaling) {
  100437. _this.attachedMesh.scaling.normalizeToRef(tmpVector);
  100438. if (tmpVector.y < 0) {
  100439. tmpVector.scaleInPlace(-1);
  100440. }
  100441. }
  100442. else {
  100443. tmpVector.copyFrom(dragAxis);
  100444. }
  100445. if (_this.snapDistance == 0) {
  100446. tmpVector.scaleToRef(event.dragDistance, tmpVector);
  100447. }
  100448. else {
  100449. currentSnapDragDistance += event.dragDistance;
  100450. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  100451. dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  100452. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  100453. tmpVector.scaleToRef(_this.snapDistance * dragSteps, tmpVector);
  100454. snapped = true;
  100455. }
  100456. else {
  100457. tmpVector.scaleInPlace(0);
  100458. }
  100459. }
  100460. _this.attachedMesh.scaling.addInPlace(tmpVector);
  100461. if (snapped) {
  100462. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  100463. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  100464. }
  100465. }
  100466. });
  100467. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  100468. if (_this._customMeshSet) {
  100469. return;
  100470. }
  100471. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  100472. var material = isHovered ? hoverMaterial : _this._coloredMaterial;
  100473. _this._rootMesh.getChildMeshes().forEach(function (m) {
  100474. m.material = material;
  100475. if (m.color) {
  100476. m.color = material.emissiveColor;
  100477. }
  100478. });
  100479. });
  100480. return _this;
  100481. }
  100482. AxisScaleGizmo.prototype._attachedMeshChanged = function (value) {
  100483. if (this.dragBehavior) {
  100484. this.dragBehavior.enabled = value ? true : false;
  100485. }
  100486. };
  100487. /**
  100488. * Disposes of the gizmo
  100489. */
  100490. AxisScaleGizmo.prototype.dispose = function () {
  100491. this.onSnapObservable.clear();
  100492. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  100493. this.dragBehavior.detach();
  100494. _super.prototype.dispose.call(this);
  100495. };
  100496. /**
  100497. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  100498. * @param mesh The mesh to replace the default mesh of the gizmo
  100499. * @param useGizmoMaterial If the gizmo's default material should be used (default: false)
  100500. */
  100501. AxisScaleGizmo.prototype.setCustomMesh = function (mesh, useGizmoMaterial) {
  100502. var _this = this;
  100503. if (useGizmoMaterial === void 0) { useGizmoMaterial = false; }
  100504. _super.prototype.setCustomMesh.call(this, mesh);
  100505. if (useGizmoMaterial) {
  100506. this._rootMesh.getChildMeshes().forEach(function (m) {
  100507. m.material = _this._coloredMaterial;
  100508. if (m.color) {
  100509. m.color = _this._coloredMaterial.emissiveColor;
  100510. }
  100511. });
  100512. this._customMeshSet = false;
  100513. }
  100514. };
  100515. return AxisScaleGizmo;
  100516. }(BABYLON.Gizmo));
  100517. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  100518. })(BABYLON || (BABYLON = {}));
  100519. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  100520. var BABYLON;
  100521. (function (BABYLON) {
  100522. /**
  100523. * Single plane rotation gizmo
  100524. */
  100525. var PlaneRotationGizmo = /** @class */ (function (_super) {
  100526. __extends(PlaneRotationGizmo, _super);
  100527. /**
  100528. * Creates a PlaneRotationGizmo
  100529. * @param gizmoLayer The utility layer the gizmo will be added to
  100530. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  100531. * @param color The color of the gizmo
  100532. */
  100533. function PlaneRotationGizmo(planeNormal, color, gizmoLayer) {
  100534. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  100535. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  100536. var _this = _super.call(this, gizmoLayer) || this;
  100537. _this._pointerObserver = null;
  100538. /**
  100539. * Rotation distance in radians that the gizmo will snap to (Default: 0)
  100540. */
  100541. _this.snapDistance = 0;
  100542. /**
  100543. * Event that fires each time the gizmo snaps to a new location.
  100544. * * snapDistance is the the change in distance
  100545. */
  100546. _this.onSnapObservable = new BABYLON.Observable();
  100547. // Create Material
  100548. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  100549. coloredMaterial.disableLighting = true;
  100550. coloredMaterial.emissiveColor = color;
  100551. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  100552. hoverMaterial.disableLighting = true;
  100553. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  100554. // Build mesh on root node
  100555. var parentMesh = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  100556. // Create circle out of lines
  100557. var tessellation = 20;
  100558. var radius = 0.8;
  100559. var points = new Array();
  100560. for (var i = 0; i < tessellation; i++) {
  100561. var radian = (2 * Math.PI) * (i / (tessellation - 1));
  100562. points.push(new BABYLON.Vector3(radius * Math.sin(radian), 0, radius * Math.cos(radian)));
  100563. }
  100564. var rotationMesh = BABYLON.Mesh.CreateLines("", points, gizmoLayer.utilityLayerScene);
  100565. rotationMesh.color = coloredMaterial.emissiveColor;
  100566. // Position arrow pointing in its drag axis
  100567. rotationMesh.scaling.scaleInPlace(0.26);
  100568. rotationMesh.material = coloredMaterial;
  100569. rotationMesh.rotation.x = Math.PI / 2;
  100570. parentMesh.addChild(rotationMesh);
  100571. parentMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  100572. _this._rootMesh.addChild(parentMesh);
  100573. parentMesh.scaling.scaleInPlace(1 / 3);
  100574. // Add drag behavior to handle events when the gizmo is dragged
  100575. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal });
  100576. _this.dragBehavior.moveAttached = false;
  100577. _this.dragBehavior.maxDragAngle = Math.PI * 9 / 20;
  100578. _this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle = true;
  100579. _this._rootMesh.addBehavior(_this.dragBehavior);
  100580. var lastDragPosition = new BABYLON.Vector3();
  100581. _this.dragBehavior.onDragStartObservable.add(function (e) {
  100582. if (_this.attachedMesh) {
  100583. lastDragPosition.copyFrom(e.dragPlanePoint);
  100584. }
  100585. });
  100586. var rotationMatrix = new BABYLON.Matrix();
  100587. var planeNormalTowardsCamera = new BABYLON.Vector3();
  100588. var localPlaneNormalTowardsCamera = new BABYLON.Vector3();
  100589. var tmpSnapEvent = { snapDistance: 0 };
  100590. var currentSnapDragDistance = 0;
  100591. var tmpMatrix = new BABYLON.Matrix();
  100592. var tmpVector = new BABYLON.Vector3();
  100593. var amountToRotate = new BABYLON.Quaternion();
  100594. _this.dragBehavior.onDragObservable.add(function (event) {
  100595. if (_this.attachedMesh) {
  100596. if (!_this.attachedMesh.rotationQuaternion) {
  100597. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  100598. }
  100599. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  100600. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.absolutePosition).normalize();
  100601. var originalVector = lastDragPosition.subtract(_this.attachedMesh.absolutePosition).normalize();
  100602. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  100603. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  100604. var angle = Math.atan2(cross.length(), dot);
  100605. planeNormalTowardsCamera.copyFrom(planeNormal);
  100606. localPlaneNormalTowardsCamera.copyFrom(planeNormal);
  100607. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  100608. _this.attachedMesh.rotationQuaternion.toRotationMatrix(rotationMatrix);
  100609. localPlaneNormalTowardsCamera = BABYLON.Vector3.TransformCoordinates(planeNormalTowardsCamera, rotationMatrix);
  100610. }
  100611. // Flip up vector depending on which side the camera is on
  100612. if (gizmoLayer.utilityLayerScene.activeCamera) {
  100613. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  100614. if (BABYLON.Vector3.Dot(camVec, localPlaneNormalTowardsCamera) > 0) {
  100615. planeNormalTowardsCamera.scaleInPlace(-1);
  100616. localPlaneNormalTowardsCamera.scaleInPlace(-1);
  100617. }
  100618. }
  100619. var halfCircleSide = BABYLON.Vector3.Dot(localPlaneNormalTowardsCamera, cross) > 0.0;
  100620. if (halfCircleSide)
  100621. angle = -angle;
  100622. // Snapping logic
  100623. var snapped = false;
  100624. if (_this.snapDistance != 0) {
  100625. currentSnapDragDistance += angle;
  100626. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  100627. var dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  100628. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  100629. angle = _this.snapDistance * dragSteps;
  100630. snapped = true;
  100631. }
  100632. else {
  100633. angle = 0;
  100634. }
  100635. }
  100636. // If the mesh has a parent, convert needed world rotation to local rotation
  100637. tmpMatrix.reset();
  100638. if (_this.attachedMesh.parent) {
  100639. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  100640. tmpMatrix.getRotationMatrixToRef(tmpMatrix);
  100641. BABYLON.Vector3.TransformCoordinatesToRef(planeNormalTowardsCamera, tmpMatrix, planeNormalTowardsCamera);
  100642. }
  100643. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  100644. var quaternionCoefficient = Math.sin(angle / 2);
  100645. amountToRotate.set(planeNormalTowardsCamera.x * quaternionCoefficient, planeNormalTowardsCamera.y * quaternionCoefficient, planeNormalTowardsCamera.z * quaternionCoefficient, Math.cos(angle / 2));
  100646. // If the meshes local scale is inverted (eg. loaded gltf file parent with z scale of -1) the rotation needs to be inverted on the y axis
  100647. if (tmpMatrix.determinant() > 0) {
  100648. amountToRotate.toEulerAnglesToRef(tmpVector);
  100649. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpVector.y, -tmpVector.x, -tmpVector.z, amountToRotate);
  100650. }
  100651. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  100652. // Rotate selected mesh quaternion over fixed axis
  100653. _this.attachedMesh.rotationQuaternion.multiplyToRef(amountToRotate, _this.attachedMesh.rotationQuaternion);
  100654. }
  100655. else {
  100656. // Rotate selected mesh quaternion over rotated axis
  100657. amountToRotate.multiplyToRef(_this.attachedMesh.rotationQuaternion, _this.attachedMesh.rotationQuaternion);
  100658. }
  100659. lastDragPosition.copyFrom(event.dragPlanePoint);
  100660. if (snapped) {
  100661. tmpSnapEvent.snapDistance = angle;
  100662. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  100663. }
  100664. }
  100665. });
  100666. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  100667. if (_this._customMeshSet) {
  100668. return;
  100669. }
  100670. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  100671. var material = isHovered ? hoverMaterial : coloredMaterial;
  100672. _this._rootMesh.getChildMeshes().forEach(function (m) {
  100673. m.material = material;
  100674. if (m.color) {
  100675. m.color = material.emissiveColor;
  100676. }
  100677. });
  100678. });
  100679. return _this;
  100680. }
  100681. PlaneRotationGizmo.prototype._attachedMeshChanged = function (value) {
  100682. if (this.dragBehavior) {
  100683. this.dragBehavior.enabled = value ? true : false;
  100684. }
  100685. };
  100686. /**
  100687. * Disposes of the gizmo
  100688. */
  100689. PlaneRotationGizmo.prototype.dispose = function () {
  100690. this.onSnapObservable.clear();
  100691. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  100692. this.dragBehavior.detach();
  100693. _super.prototype.dispose.call(this);
  100694. };
  100695. return PlaneRotationGizmo;
  100696. }(BABYLON.Gizmo));
  100697. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  100698. })(BABYLON || (BABYLON = {}));
  100699. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  100700. var BABYLON;
  100701. (function (BABYLON) {
  100702. /**
  100703. * Gizmo that enables dragging a mesh along 3 axis
  100704. */
  100705. var PositionGizmo = /** @class */ (function (_super) {
  100706. __extends(PositionGizmo, _super);
  100707. /**
  100708. * Creates a PositionGizmo
  100709. * @param gizmoLayer The utility layer the gizmo will be added to
  100710. */
  100711. function PositionGizmo(gizmoLayer) {
  100712. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  100713. var _this = _super.call(this, gizmoLayer) || this;
  100714. _this.xGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  100715. _this.yGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  100716. _this.zGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  100717. _this.attachedMesh = null;
  100718. return _this;
  100719. }
  100720. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  100721. set: function (mesh) {
  100722. if (this.xGizmo) {
  100723. this.xGizmo.attachedMesh = mesh;
  100724. this.yGizmo.attachedMesh = mesh;
  100725. this.zGizmo.attachedMesh = mesh;
  100726. }
  100727. },
  100728. enumerable: true,
  100729. configurable: true
  100730. });
  100731. Object.defineProperty(PositionGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  100732. get: function () {
  100733. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  100734. },
  100735. set: function (value) {
  100736. if (this.xGizmo) {
  100737. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  100738. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  100739. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  100740. }
  100741. },
  100742. enumerable: true,
  100743. configurable: true
  100744. });
  100745. Object.defineProperty(PositionGizmo.prototype, "snapDistance", {
  100746. get: function () {
  100747. return this.xGizmo.snapDistance;
  100748. },
  100749. /**
  100750. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  100751. */
  100752. set: function (value) {
  100753. if (this.xGizmo) {
  100754. this.xGizmo.snapDistance = value;
  100755. this.yGizmo.snapDistance = value;
  100756. this.zGizmo.snapDistance = value;
  100757. }
  100758. },
  100759. enumerable: true,
  100760. configurable: true
  100761. });
  100762. Object.defineProperty(PositionGizmo.prototype, "scaleRatio", {
  100763. get: function () {
  100764. return this.xGizmo.scaleRatio;
  100765. },
  100766. /**
  100767. * Ratio for the scale of the gizmo (Default: 1)
  100768. */
  100769. set: function (value) {
  100770. if (this.xGizmo) {
  100771. this.xGizmo.scaleRatio = value;
  100772. this.yGizmo.scaleRatio = value;
  100773. this.zGizmo.scaleRatio = value;
  100774. }
  100775. },
  100776. enumerable: true,
  100777. configurable: true
  100778. });
  100779. /**
  100780. * Disposes of the gizmo
  100781. */
  100782. PositionGizmo.prototype.dispose = function () {
  100783. this.xGizmo.dispose();
  100784. this.yGizmo.dispose();
  100785. this.zGizmo.dispose();
  100786. };
  100787. /**
  100788. * CustomMeshes are not supported by this gizmo
  100789. * @param mesh The mesh to replace the default mesh of the gizmo
  100790. */
  100791. PositionGizmo.prototype.setCustomMesh = function (mesh) {
  100792. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo, please set the custom meshes on the gizmos contained within this one (gizmo.xGizmo, gizmo.yGizmo, gizmo.zGizmo)");
  100793. };
  100794. return PositionGizmo;
  100795. }(BABYLON.Gizmo));
  100796. BABYLON.PositionGizmo = PositionGizmo;
  100797. })(BABYLON || (BABYLON = {}));
  100798. //# sourceMappingURL=babylon.positionGizmo.js.map
  100799. var BABYLON;
  100800. (function (BABYLON) {
  100801. /**
  100802. * Gizmo that enables rotating a mesh along 3 axis
  100803. */
  100804. var RotationGizmo = /** @class */ (function (_super) {
  100805. __extends(RotationGizmo, _super);
  100806. /**
  100807. * Creates a RotationGizmo
  100808. * @param gizmoLayer The utility layer the gizmo will be added to
  100809. */
  100810. function RotationGizmo(gizmoLayer) {
  100811. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  100812. var _this = _super.call(this, gizmoLayer) || this;
  100813. _this.xGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  100814. _this.yGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  100815. _this.zGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  100816. _this.attachedMesh = null;
  100817. return _this;
  100818. }
  100819. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  100820. set: function (mesh) {
  100821. if (this.xGizmo) {
  100822. this.xGizmo.attachedMesh = mesh;
  100823. this.yGizmo.attachedMesh = mesh;
  100824. this.zGizmo.attachedMesh = mesh;
  100825. }
  100826. },
  100827. enumerable: true,
  100828. configurable: true
  100829. });
  100830. Object.defineProperty(RotationGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  100831. get: function () {
  100832. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  100833. },
  100834. set: function (value) {
  100835. if (this.xGizmo) {
  100836. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  100837. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  100838. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  100839. }
  100840. },
  100841. enumerable: true,
  100842. configurable: true
  100843. });
  100844. Object.defineProperty(RotationGizmo.prototype, "snapDistance", {
  100845. get: function () {
  100846. return this.xGizmo.snapDistance;
  100847. },
  100848. /**
  100849. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  100850. */
  100851. set: function (value) {
  100852. if (this.xGizmo) {
  100853. this.xGizmo.snapDistance = value;
  100854. this.yGizmo.snapDistance = value;
  100855. this.zGizmo.snapDistance = value;
  100856. }
  100857. },
  100858. enumerable: true,
  100859. configurable: true
  100860. });
  100861. Object.defineProperty(RotationGizmo.prototype, "scaleRatio", {
  100862. get: function () {
  100863. return this.xGizmo.scaleRatio;
  100864. },
  100865. /**
  100866. * Ratio for the scale of the gizmo (Default: 1)
  100867. */
  100868. set: function (value) {
  100869. if (this.xGizmo) {
  100870. this.xGizmo.scaleRatio = value;
  100871. this.yGizmo.scaleRatio = value;
  100872. this.zGizmo.scaleRatio = value;
  100873. }
  100874. },
  100875. enumerable: true,
  100876. configurable: true
  100877. });
  100878. /**
  100879. * Disposes of the gizmo
  100880. */
  100881. RotationGizmo.prototype.dispose = function () {
  100882. this.xGizmo.dispose();
  100883. this.yGizmo.dispose();
  100884. this.zGizmo.dispose();
  100885. };
  100886. /**
  100887. * CustomMeshes are not supported by this gizmo
  100888. * @param mesh The mesh to replace the default mesh of the gizmo
  100889. */
  100890. RotationGizmo.prototype.setCustomMesh = function (mesh) {
  100891. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo, please set the custom meshes on the gizmos contained within this one (gizmo.xGizmo, gizmo.yGizmo, gizmo.zGizmo)");
  100892. };
  100893. return RotationGizmo;
  100894. }(BABYLON.Gizmo));
  100895. BABYLON.RotationGizmo = RotationGizmo;
  100896. })(BABYLON || (BABYLON = {}));
  100897. //# sourceMappingURL=babylon.rotationGizmo.js.map
  100898. var BABYLON;
  100899. (function (BABYLON) {
  100900. /**
  100901. * Gizmo that enables scaling a mesh along 3 axis
  100902. */
  100903. var ScaleGizmo = /** @class */ (function (_super) {
  100904. __extends(ScaleGizmo, _super);
  100905. /**
  100906. * Creates a ScaleGizmo
  100907. * @param gizmoLayer The utility layer the gizmo will be added to
  100908. */
  100909. function ScaleGizmo(gizmoLayer) {
  100910. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  100911. var _this = _super.call(this, gizmoLayer) || this;
  100912. _this.xGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  100913. _this.yGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  100914. _this.zGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  100915. // Create uniform scale gizmo
  100916. _this.uniformScaleGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Yellow().scale(0.5), gizmoLayer);
  100917. _this.uniformScaleGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  100918. _this.uniformScaleGizmo.uniformScaling = true;
  100919. var octahedron = BABYLON.Mesh.CreatePolyhedron("", { type: 1 }, _this.uniformScaleGizmo.gizmoLayer.utilityLayerScene);
  100920. octahedron.scaling.scaleInPlace(0.007);
  100921. _this.uniformScaleGizmo.setCustomMesh(octahedron, true);
  100922. _this.attachedMesh = null;
  100923. return _this;
  100924. }
  100925. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  100926. set: function (mesh) {
  100927. if (this.xGizmo) {
  100928. this.xGizmo.attachedMesh = mesh;
  100929. this.yGizmo.attachedMesh = mesh;
  100930. this.zGizmo.attachedMesh = mesh;
  100931. this.uniformScaleGizmo.attachedMesh = mesh;
  100932. }
  100933. },
  100934. enumerable: true,
  100935. configurable: true
  100936. });
  100937. Object.defineProperty(ScaleGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  100938. get: function () {
  100939. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  100940. },
  100941. set: function (value) {
  100942. if (this.xGizmo) {
  100943. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  100944. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  100945. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  100946. }
  100947. },
  100948. enumerable: true,
  100949. configurable: true
  100950. });
  100951. Object.defineProperty(ScaleGizmo.prototype, "snapDistance", {
  100952. get: function () {
  100953. return this.xGizmo.snapDistance;
  100954. },
  100955. /**
  100956. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  100957. */
  100958. set: function (value) {
  100959. if (this.xGizmo) {
  100960. this.xGizmo.snapDistance = value;
  100961. this.yGizmo.snapDistance = value;
  100962. this.zGizmo.snapDistance = value;
  100963. this.uniformScaleGizmo.snapDistance = value;
  100964. }
  100965. },
  100966. enumerable: true,
  100967. configurable: true
  100968. });
  100969. Object.defineProperty(ScaleGizmo.prototype, "scaleRatio", {
  100970. get: function () {
  100971. return this.xGizmo.scaleRatio;
  100972. },
  100973. /**
  100974. * Ratio for the scale of the gizmo (Default: 1)
  100975. */
  100976. set: function (value) {
  100977. if (this.xGizmo) {
  100978. this.xGizmo.scaleRatio = value;
  100979. this.yGizmo.scaleRatio = value;
  100980. this.zGizmo.scaleRatio = value;
  100981. this.uniformScaleGizmo.scaleRatio = value;
  100982. }
  100983. },
  100984. enumerable: true,
  100985. configurable: true
  100986. });
  100987. /**
  100988. * Disposes of the gizmo
  100989. */
  100990. ScaleGizmo.prototype.dispose = function () {
  100991. this.xGizmo.dispose();
  100992. this.yGizmo.dispose();
  100993. this.zGizmo.dispose();
  100994. this.uniformScaleGizmo.dispose();
  100995. };
  100996. return ScaleGizmo;
  100997. }(BABYLON.Gizmo));
  100998. BABYLON.ScaleGizmo = ScaleGizmo;
  100999. })(BABYLON || (BABYLON = {}));
  101000. //# sourceMappingURL=babylon.scaleGizmo.js.map
  101001. var BABYLON;
  101002. (function (BABYLON) {
  101003. /**
  101004. * Bounding box gizmo
  101005. */
  101006. var BoundingBoxGizmo = /** @class */ (function (_super) {
  101007. __extends(BoundingBoxGizmo, _super);
  101008. /**
  101009. * Creates an BoundingBoxGizmo
  101010. * @param gizmoLayer The utility layer the gizmo will be added to
  101011. * @param color The color of the gizmo
  101012. */
  101013. function BoundingBoxGizmo(color, gizmoLayer) {
  101014. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  101015. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultKeepDepthUtilityLayer; }
  101016. var _this = _super.call(this, gizmoLayer) || this;
  101017. _this._boundingDimensions = new BABYLON.Vector3(1, 1, 1);
  101018. _this._renderObserver = null;
  101019. _this._pointerObserver = null;
  101020. _this._scaleDragSpeed = 0.2;
  101021. _this._tmpQuaternion = new BABYLON.Quaternion();
  101022. _this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  101023. _this._tmpRotationMatrix = new BABYLON.Matrix();
  101024. /**
  101025. * If child meshes should be ignored when calculating the boudning box. This should be set to true to avoid perf hits with heavily nested meshes (Default: false)
  101026. */
  101027. _this.ignoreChildren = false;
  101028. /**
  101029. * Returns true if a descendant should be included when computing the bounding box. When null, all descendants are included. If ignoreChildren is set this will be ignored. (Default: null)
  101030. */
  101031. _this.includeChildPredicate = null;
  101032. /**
  101033. * The size of the rotation spheres attached to the bounding box (Default: 0.1)
  101034. */
  101035. _this.rotationSphereSize = 0.1;
  101036. /**
  101037. * The size of the scale boxes attached to the bounding box (Default: 0.1)
  101038. */
  101039. _this.scaleBoxSize = 0.1;
  101040. /**
  101041. * If set, the rotation spheres and scale boxes will increase in size based on the distance away from the camera to have a consistent screen size (Default: false)
  101042. */
  101043. _this.fixedDragMeshScreenSize = false;
  101044. /**
  101045. * The distance away from the object which the draggable meshes should appear world sized when fixedDragMeshScreenSize is set to true (default: 10)
  101046. */
  101047. _this.fixedDragMeshScreenSizeDistanceFactor = 10;
  101048. /**
  101049. * Fired when a rotation sphere or scale box is dragged
  101050. */
  101051. _this.onDragStartObservable = new BABYLON.Observable();
  101052. /**
  101053. * Fired when a scale box is dragged
  101054. */
  101055. _this.onScaleBoxDragObservable = new BABYLON.Observable();
  101056. /**
  101057. * Fired when a scale box drag is ended
  101058. */
  101059. _this.onScaleBoxDragEndObservable = new BABYLON.Observable();
  101060. /**
  101061. * Fired when a rotation sphere is dragged
  101062. */
  101063. _this.onRotationSphereDragObservable = new BABYLON.Observable();
  101064. /**
  101065. * Fired when a rotation sphere drag is ended
  101066. */
  101067. _this.onRotationSphereDragEndObservable = new BABYLON.Observable();
  101068. /**
  101069. * Relative bounding box pivot used when scaling the attached mesh. When null object with scale from the opposite corner. 0.5,0.5,0.5 for center and 0.5,0,0.5 for bottom (Default: null)
  101070. */
  101071. _this.scalePivot = null;
  101072. _this._existingMeshScale = new BABYLON.Vector3();
  101073. // Do not update the gizmo's scale so it has a fixed size to the object its attached to
  101074. _this._updateScale = false;
  101075. _this._anchorMesh = new BABYLON.AbstractMesh("anchor", gizmoLayer.utilityLayerScene);
  101076. // Create Materials
  101077. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  101078. coloredMaterial.disableLighting = true;
  101079. coloredMaterial.emissiveColor = color;
  101080. var hoverColoredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  101081. hoverColoredMaterial.disableLighting = true;
  101082. hoverColoredMaterial.emissiveColor = color.clone().add(new BABYLON.Color3(0.3, 0.3, 0.3));
  101083. // Build bounding box out of lines
  101084. _this._lineBoundingBox = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  101085. _this._lineBoundingBox.rotationQuaternion = new BABYLON.Quaternion();
  101086. var lines = [];
  101087. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));
  101088. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  101089. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  101090. 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));
  101091. 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));
  101092. 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));
  101093. 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));
  101094. 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));
  101095. 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));
  101096. 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));
  101097. 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));
  101098. 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));
  101099. lines.forEach(function (l) {
  101100. l.color = color;
  101101. l.position.addInPlace(new BABYLON.Vector3(-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2));
  101102. l.isPickable = false;
  101103. _this._lineBoundingBox.addChild(l);
  101104. });
  101105. _this._rootMesh.addChild(_this._lineBoundingBox);
  101106. // Create rotation spheres
  101107. _this._rotateSpheresParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  101108. _this._rotateSpheresParent.rotationQuaternion = new BABYLON.Quaternion();
  101109. var _loop_1 = function (i_1) {
  101110. var sphere = BABYLON.MeshBuilder.CreateSphere("", { diameter: 1 }, gizmoLayer.utilityLayerScene);
  101111. sphere.rotationQuaternion = new BABYLON.Quaternion();
  101112. sphere.material = coloredMaterial;
  101113. // Drag behavior
  101114. _dragBehavior = new BABYLON.PointerDragBehavior({});
  101115. _dragBehavior.moveAttached = false;
  101116. _dragBehavior.updateDragPlane = false;
  101117. sphere.addBehavior(_dragBehavior);
  101118. var startingTurnDirection = new BABYLON.Vector3(1, 0, 0);
  101119. var totalTurnAmountOfDrag = 0;
  101120. _dragBehavior.onDragStartObservable.add(function (event) {
  101121. startingTurnDirection.copyFrom(sphere.forward);
  101122. totalTurnAmountOfDrag = 0;
  101123. });
  101124. _dragBehavior.onDragObservable.add(function (event) {
  101125. _this.onRotationSphereDragObservable.notifyObservers({});
  101126. if (_this.attachedMesh) {
  101127. BoundingBoxGizmo._RemoveAndStorePivotPoint(_this.attachedMesh);
  101128. var worldDragDirection = startingTurnDirection;
  101129. // Project the world right on to the drag plane
  101130. var toSub = event.dragPlaneNormal.scale(BABYLON.Vector3.Dot(event.dragPlaneNormal, worldDragDirection));
  101131. var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();
  101132. // project drag delta on to the resulting drag axis and rotate based on that
  101133. var projectDist = -BABYLON.Vector3.Dot(dragAxis, event.delta);
  101134. // Make rotation relative to size of mesh.
  101135. projectDist = (projectDist / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  101136. // Rotate based on axis
  101137. if (!_this.attachedMesh.rotationQuaternion) {
  101138. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  101139. }
  101140. if (!_this._anchorMesh.rotationQuaternion) {
  101141. _this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._anchorMesh.rotation.y, _this._anchorMesh.rotation.x, _this._anchorMesh.rotation.z);
  101142. }
  101143. // Do not allow the object to turn more than a full circle
  101144. totalTurnAmountOfDrag += projectDist;
  101145. if (Math.abs(totalTurnAmountOfDrag) <= 2 * Math.PI) {
  101146. if (i_1 >= 8) {
  101147. BABYLON.Quaternion.RotationYawPitchRollToRef(0, 0, projectDist, _this._tmpQuaternion);
  101148. }
  101149. else if (i_1 >= 4) {
  101150. BABYLON.Quaternion.RotationYawPitchRollToRef(projectDist, 0, 0, _this._tmpQuaternion);
  101151. }
  101152. else {
  101153. BABYLON.Quaternion.RotationYawPitchRollToRef(0, projectDist, 0, _this._tmpQuaternion);
  101154. }
  101155. // Rotate around center of bounding box
  101156. _this._anchorMesh.addChild(_this.attachedMesh);
  101157. _this._anchorMesh.rotationQuaternion.multiplyToRef(_this._tmpQuaternion, _this._anchorMesh.rotationQuaternion);
  101158. _this._anchorMesh.removeChild(_this.attachedMesh);
  101159. }
  101160. _this.updateBoundingBox();
  101161. BoundingBoxGizmo._RestorePivotPoint(_this.attachedMesh);
  101162. }
  101163. });
  101164. // Selection/deselection
  101165. _dragBehavior.onDragStartObservable.add(function () {
  101166. _this.onDragStartObservable.notifyObservers({});
  101167. _this._selectNode(sphere);
  101168. });
  101169. _dragBehavior.onDragEndObservable.add(function () {
  101170. _this.onRotationSphereDragEndObservable.notifyObservers({});
  101171. _this._selectNode(null);
  101172. });
  101173. this_1._rotateSpheresParent.addChild(sphere);
  101174. };
  101175. var this_1 = this, _dragBehavior;
  101176. for (var i_1 = 0; i_1 < 12; i_1++) {
  101177. _loop_1(i_1);
  101178. }
  101179. _this._rootMesh.addChild(_this._rotateSpheresParent);
  101180. // Create scale cubes
  101181. _this._scaleBoxesParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  101182. _this._scaleBoxesParent.rotationQuaternion = new BABYLON.Quaternion();
  101183. for (var i = 0; i < 2; i++) {
  101184. for (var j = 0; j < 2; j++) {
  101185. var _loop_2 = function () {
  101186. var box = BABYLON.MeshBuilder.CreateBox("", { size: 1 }, gizmoLayer.utilityLayerScene);
  101187. box.material = coloredMaterial;
  101188. // Dragging logic
  101189. var dragAxis = new BABYLON.Vector3(i == 0 ? -1 : 1, j == 0 ? -1 : 1, k == 0 ? -1 : 1);
  101190. _dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  101191. _dragBehavior.moveAttached = false;
  101192. box.addBehavior(_dragBehavior);
  101193. _dragBehavior.onDragObservable.add(function (event) {
  101194. _this.onScaleBoxDragObservable.notifyObservers({});
  101195. if (_this.attachedMesh) {
  101196. BoundingBoxGizmo._RemoveAndStorePivotPoint(_this.attachedMesh);
  101197. var relativeDragDistance = (event.dragDistance / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  101198. var deltaScale = new BABYLON.Vector3(relativeDragDistance, relativeDragDistance, relativeDragDistance);
  101199. deltaScale.scaleInPlace(_this._scaleDragSpeed);
  101200. _this.updateBoundingBox();
  101201. if (_this.scalePivot) {
  101202. _this.attachedMesh.getWorldMatrix().getRotationMatrixToRef(_this._tmpRotationMatrix);
  101203. // Move anchor to desired pivot point (Bottom left corner + dimension/2)
  101204. _this._boundingDimensions.scaleToRef(0.5, _this._tmpVector);
  101205. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  101206. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  101207. _this._boundingDimensions.multiplyToRef(_this.scalePivot, _this._tmpVector);
  101208. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  101209. _this._anchorMesh.position.addInPlace(_this._tmpVector);
  101210. }
  101211. else {
  101212. // Scale from the position of the opposite corner
  101213. box.absolutePosition.subtractToRef(_this._anchorMesh.position, _this._tmpVector);
  101214. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  101215. }
  101216. _this._anchorMesh.addChild(_this.attachedMesh);
  101217. _this._anchorMesh.scaling.addInPlace(deltaScale);
  101218. if (_this._anchorMesh.scaling.x < 0 || _this._anchorMesh.scaling.y < 0 || _this._anchorMesh.scaling.z < 0) {
  101219. _this._anchorMesh.scaling.subtractInPlace(deltaScale);
  101220. }
  101221. _this._anchorMesh.removeChild(_this.attachedMesh);
  101222. BoundingBoxGizmo._RestorePivotPoint(_this.attachedMesh);
  101223. }
  101224. });
  101225. // Selection/deselection
  101226. _dragBehavior.onDragStartObservable.add(function () {
  101227. _this.onDragStartObservable.notifyObservers({});
  101228. _this._selectNode(box);
  101229. });
  101230. _dragBehavior.onDragEndObservable.add(function () {
  101231. _this.onScaleBoxDragEndObservable.notifyObservers({});
  101232. _this._selectNode(null);
  101233. });
  101234. this_2._scaleBoxesParent.addChild(box);
  101235. };
  101236. var this_2 = this, _dragBehavior;
  101237. for (var k = 0; k < 2; k++) {
  101238. _loop_2();
  101239. }
  101240. }
  101241. }
  101242. _this._rootMesh.addChild(_this._scaleBoxesParent);
  101243. // Hover color change
  101244. var pointerIds = new Array();
  101245. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  101246. if (!pointerIds[pointerInfo.event.pointerId]) {
  101247. _this._rotateSpheresParent.getChildMeshes().concat(_this._scaleBoxesParent.getChildMeshes()).forEach(function (mesh) {
  101248. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh == mesh) {
  101249. pointerIds[pointerInfo.event.pointerId] = mesh;
  101250. mesh.material = hoverColoredMaterial;
  101251. }
  101252. });
  101253. }
  101254. else {
  101255. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh != pointerIds[pointerInfo.event.pointerId]) {
  101256. pointerIds[pointerInfo.event.pointerId].material = coloredMaterial;
  101257. delete pointerIds[pointerInfo.event.pointerId];
  101258. }
  101259. }
  101260. });
  101261. // Update bounding box positions
  101262. _this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () {
  101263. // Only update the bouding box if scaling has changed
  101264. if (_this.attachedMesh && !_this._existingMeshScale.equals(_this.attachedMesh.scaling)) {
  101265. _this.updateBoundingBox();
  101266. }
  101267. });
  101268. _this.updateBoundingBox();
  101269. return _this;
  101270. }
  101271. /** @hidden */
  101272. BoundingBoxGizmo._RemoveAndStorePivotPoint = function (mesh) {
  101273. if (mesh && BoundingBoxGizmo._PivotCached === 0) {
  101274. // Save old pivot and set pivot to 0,0,0
  101275. mesh.getPivotPointToRef(BoundingBoxGizmo._OldPivotPoint);
  101276. if (!BoundingBoxGizmo._OldPivotPoint.equalsToFloats(0, 0, 0)) {
  101277. mesh.setPivotMatrix(BABYLON.Matrix.IdentityReadOnly);
  101278. BoundingBoxGizmo._OldPivotPoint.subtractToRef(mesh.getPivotPoint(), BoundingBoxGizmo._PivotTranslation);
  101279. BoundingBoxGizmo._PivotTmpVector.copyFromFloats(1, 1, 1);
  101280. BoundingBoxGizmo._PivotTmpVector.subtractInPlace(mesh.scaling);
  101281. BoundingBoxGizmo._PivotTmpVector.multiplyInPlace(BoundingBoxGizmo._PivotTranslation);
  101282. mesh.position.addInPlace(BoundingBoxGizmo._PivotTmpVector);
  101283. }
  101284. }
  101285. BoundingBoxGizmo._PivotCached++;
  101286. };
  101287. /** @hidden */
  101288. BoundingBoxGizmo._RestorePivotPoint = function (mesh) {
  101289. if (mesh && !BoundingBoxGizmo._OldPivotPoint.equalsToFloats(0, 0, 0) && BoundingBoxGizmo._PivotCached === 1) {
  101290. mesh.setPivotPoint(BoundingBoxGizmo._OldPivotPoint);
  101291. BoundingBoxGizmo._PivotTmpVector.copyFromFloats(1, 1, 1);
  101292. BoundingBoxGizmo._PivotTmpVector.subtractInPlace(mesh.scaling);
  101293. BoundingBoxGizmo._PivotTmpVector.multiplyInPlace(BoundingBoxGizmo._PivotTranslation);
  101294. mesh.position.subtractInPlace(BoundingBoxGizmo._PivotTmpVector);
  101295. }
  101296. this._PivotCached--;
  101297. };
  101298. BoundingBoxGizmo.prototype._attachedMeshChanged = function (value) {
  101299. if (value) {
  101300. // Reset anchor mesh to match attached mesh's scale
  101301. // This is needed to avoid invalid box/sphere position on first drag
  101302. BoundingBoxGizmo._RemoveAndStorePivotPoint(value);
  101303. this._anchorMesh.addChild(value);
  101304. this._anchorMesh.removeChild(value);
  101305. BoundingBoxGizmo._RestorePivotPoint(value);
  101306. this.updateBoundingBox();
  101307. }
  101308. };
  101309. BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) {
  101310. this._rotateSpheresParent.getChildMeshes()
  101311. .concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m, i) {
  101312. m.isVisible = (!selectedMesh || m == selectedMesh);
  101313. });
  101314. };
  101315. /**
  101316. * Updates the bounding box information for the Gizmo
  101317. */
  101318. BoundingBoxGizmo.prototype.updateBoundingBox = function () {
  101319. if (this.attachedMesh) {
  101320. BoundingBoxGizmo._RemoveAndStorePivotPoint(this.attachedMesh);
  101321. this._update();
  101322. // Rotate based on axis
  101323. if (!this.attachedMesh.rotationQuaternion) {
  101324. this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.attachedMesh.rotation.y, this.attachedMesh.rotation.x, this.attachedMesh.rotation.z);
  101325. }
  101326. if (!this._anchorMesh.rotationQuaternion) {
  101327. this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._anchorMesh.rotation.y, this._anchorMesh.rotation.x, this._anchorMesh.rotation.z);
  101328. }
  101329. this._anchorMesh.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  101330. // Store original position and reset mesh to origin before computing the bounding box
  101331. this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  101332. this._tmpVector.copyFrom(this.attachedMesh.position);
  101333. this.attachedMesh.rotationQuaternion.set(0, 0, 0, 1);
  101334. this.attachedMesh.position.set(0, 0, 0);
  101335. // Update bounding dimensions/positions
  101336. var boundingMinMax = this.attachedMesh.getHierarchyBoundingVectors(!this.ignoreChildren, this.includeChildPredicate);
  101337. boundingMinMax.max.subtractToRef(boundingMinMax.min, this._boundingDimensions);
  101338. // Update gizmo to match bounding box scaling and rotation
  101339. this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);
  101340. this._lineBoundingBox.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);
  101341. this._rotateSpheresParent.position.copyFrom(this._lineBoundingBox.position);
  101342. this._scaleBoxesParent.position.copyFrom(this._lineBoundingBox.position);
  101343. this._lineBoundingBox.computeWorldMatrix();
  101344. this._anchorMesh.position.copyFrom(this._lineBoundingBox.absolutePosition);
  101345. // restore position/rotation values
  101346. this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion);
  101347. this.attachedMesh.position.copyFrom(this._tmpVector);
  101348. }
  101349. // Update rotation sphere locations
  101350. var rotateSpheres = this._rotateSpheresParent.getChildMeshes();
  101351. for (var i = 0; i < 3; i++) {
  101352. for (var j = 0; j < 2; j++) {
  101353. for (var k = 0; k < 2; k++) {
  101354. var index = ((i * 4) + (j * 2)) + k;
  101355. if (i == 0) {
  101356. rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  101357. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  101358. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Right(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  101359. }
  101360. if (i == 1) {
  101361. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);
  101362. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  101363. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Up(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  101364. }
  101365. if (i == 2) {
  101366. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);
  101367. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  101368. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Forward(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  101369. }
  101370. if (this.fixedDragMeshScreenSize) {
  101371. this._rootMesh.computeWorldMatrix();
  101372. this._rotateSpheresParent.computeWorldMatrix();
  101373. rotateSpheres[index].computeWorldMatrix();
  101374. rotateSpheres[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  101375. var distanceFromCamera = this.rotationSphereSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  101376. rotateSpheres[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  101377. }
  101378. else {
  101379. rotateSpheres[index].scaling.set(this.rotationSphereSize, this.rotationSphereSize, this.rotationSphereSize);
  101380. }
  101381. }
  101382. }
  101383. }
  101384. // Update scale box locations
  101385. var scaleBoxes = this._scaleBoxesParent.getChildMeshes();
  101386. for (var i = 0; i < 2; i++) {
  101387. for (var j = 0; j < 2; j++) {
  101388. for (var k = 0; k < 2; k++) {
  101389. var index = ((i * 4) + (j * 2)) + k;
  101390. if (scaleBoxes[index]) {
  101391. scaleBoxes[index].position.set(this._boundingDimensions.x * i, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  101392. scaleBoxes[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  101393. if (this.fixedDragMeshScreenSize) {
  101394. this._rootMesh.computeWorldMatrix();
  101395. this._scaleBoxesParent.computeWorldMatrix();
  101396. scaleBoxes[index].computeWorldMatrix();
  101397. scaleBoxes[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  101398. var distanceFromCamera = this.scaleBoxSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  101399. scaleBoxes[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  101400. }
  101401. else {
  101402. scaleBoxes[index].scaling.set(this.scaleBoxSize, this.scaleBoxSize, this.scaleBoxSize);
  101403. }
  101404. }
  101405. }
  101406. }
  101407. }
  101408. if (this.attachedMesh) {
  101409. this._existingMeshScale.copyFrom(this.attachedMesh.scaling);
  101410. BoundingBoxGizmo._RestorePivotPoint(this.attachedMesh);
  101411. }
  101412. };
  101413. /**
  101414. * Enables rotation on the specified axis and disables rotation on the others
  101415. * @param axis The list of axis that should be enabled (eg. "xy" or "xyz")
  101416. */
  101417. BoundingBoxGizmo.prototype.setEnabledRotationAxis = function (axis) {
  101418. this._rotateSpheresParent.getChildMeshes().forEach(function (m, i) {
  101419. if (i < 4) {
  101420. m.setEnabled(axis.indexOf("x") != -1);
  101421. }
  101422. else if (i < 8) {
  101423. m.setEnabled(axis.indexOf("y") != -1);
  101424. }
  101425. else {
  101426. m.setEnabled(axis.indexOf("z") != -1);
  101427. }
  101428. });
  101429. };
  101430. /**
  101431. * Disposes of the gizmo
  101432. */
  101433. BoundingBoxGizmo.prototype.dispose = function () {
  101434. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  101435. this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);
  101436. this._lineBoundingBox.dispose();
  101437. this._rotateSpheresParent.dispose();
  101438. this._scaleBoxesParent.dispose();
  101439. _super.prototype.dispose.call(this);
  101440. };
  101441. /**
  101442. * Makes a mesh not pickable and wraps the mesh inside of a bounding box mesh that is pickable. (This is useful to avoid picking within complex geometry)
  101443. * @param mesh the mesh to wrap in the bounding box mesh and make not pickable
  101444. * @returns the bounding box mesh with the passed in mesh as a child
  101445. */
  101446. BoundingBoxGizmo.MakeNotPickableAndWrapInBoundingBox = function (mesh) {
  101447. var makeNotPickable = function (root) {
  101448. root.isPickable = false;
  101449. root.getChildMeshes().forEach(function (c) {
  101450. makeNotPickable(c);
  101451. });
  101452. };
  101453. makeNotPickable(mesh);
  101454. // Reset position to get boudning box from origin with no rotation
  101455. if (!mesh.rotationQuaternion) {
  101456. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  101457. }
  101458. var oldPos = mesh.position.clone();
  101459. var oldRot = mesh.rotationQuaternion.clone();
  101460. mesh.rotationQuaternion.set(0, 0, 0, 1);
  101461. mesh.position.set(0, 0, 0);
  101462. // Update bounding dimensions/positions
  101463. var box = BABYLON.MeshBuilder.CreateBox("box", { size: 1 }, mesh.getScene());
  101464. var boundingMinMax = mesh.getHierarchyBoundingVectors();
  101465. boundingMinMax.max.subtractToRef(boundingMinMax.min, box.scaling);
  101466. box.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);
  101467. // Restore original positions
  101468. mesh.addChild(box);
  101469. mesh.rotationQuaternion.copyFrom(oldRot);
  101470. mesh.position.copyFrom(oldPos);
  101471. // Reverse parenting
  101472. mesh.removeChild(box);
  101473. box.addChild(mesh);
  101474. box.visibility = 0;
  101475. return box;
  101476. };
  101477. /**
  101478. * CustomMeshes are not supported by this gizmo
  101479. * @param mesh The mesh to replace the default mesh of the gizmo
  101480. */
  101481. BoundingBoxGizmo.prototype.setCustomMesh = function (mesh) {
  101482. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo");
  101483. };
  101484. // Stores the state of the pivot cache (_oldPivotPoint, _pivotTranslation)
  101485. // store/remove pivot point should only be applied during their outermost calls
  101486. BoundingBoxGizmo._PivotCached = 0;
  101487. BoundingBoxGizmo._OldPivotPoint = new BABYLON.Vector3();
  101488. BoundingBoxGizmo._PivotTranslation = new BABYLON.Vector3();
  101489. BoundingBoxGizmo._PivotTmpVector = new BABYLON.Vector3();
  101490. return BoundingBoxGizmo;
  101491. }(BABYLON.Gizmo));
  101492. BABYLON.BoundingBoxGizmo = BoundingBoxGizmo;
  101493. })(BABYLON || (BABYLON = {}));
  101494. //# sourceMappingURL=babylon.boundingBoxGizmo.js.map
  101495. var BABYLON;
  101496. (function (BABYLON) {
  101497. /**
  101498. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  101499. */
  101500. var GizmoManager = /** @class */ (function () {
  101501. /**
  101502. * Instatiates a gizmo manager
  101503. * @param scene the scene to overlay the gizmos on top of
  101504. */
  101505. function GizmoManager(scene) {
  101506. var _this = this;
  101507. this.scene = scene;
  101508. this._gizmosEnabled = { positionGizmo: false, rotationGizmo: false, scaleGizmo: false, boundingBoxGizmo: false };
  101509. this._pointerObserver = null;
  101510. this._attachedMesh = null;
  101511. this._boundingBoxColor = BABYLON.Color3.FromHexString("#0984e3");
  101512. /**
  101513. * When bounding box gizmo is enabled, this can be used to track drag/end events
  101514. */
  101515. this.boundingBoxDragBehavior = new BABYLON.SixDofDragBehavior();
  101516. /**
  101517. * Array of meshes which will have the gizmo attached when a pointer selected them. If null, all meshes are attachable. (Default: null)
  101518. */
  101519. this.attachableMeshes = null;
  101520. /**
  101521. * If pointer events should perform attaching/detaching a gizmo, if false this can be done manually via attachToMesh. (Default: true)
  101522. */
  101523. this.usePointerToAttachGizmos = true;
  101524. this.gizmos = { positionGizmo: null, rotationGizmo: null, scaleGizmo: null, boundingBoxGizmo: null };
  101525. // Instatiate/dispose gizmos based on pointer actions
  101526. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  101527. if (!_this.usePointerToAttachGizmos) {
  101528. return;
  101529. }
  101530. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  101531. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  101532. var node = pointerInfo.pickInfo.pickedMesh;
  101533. if (_this.attachableMeshes == null) {
  101534. // Attach to the most parent node
  101535. while (node && node.parent != null) {
  101536. node = node.parent;
  101537. }
  101538. }
  101539. else {
  101540. // Attach to the parent node that is an attachableMesh
  101541. var found = false;
  101542. _this.attachableMeshes.forEach(function (mesh) {
  101543. if (node && (node == mesh || node.isDescendantOf(mesh))) {
  101544. node = mesh;
  101545. found = true;
  101546. }
  101547. });
  101548. if (!found) {
  101549. node = null;
  101550. }
  101551. }
  101552. if (node instanceof BABYLON.AbstractMesh) {
  101553. _this.attachToMesh(node);
  101554. }
  101555. else {
  101556. _this.attachToMesh(null);
  101557. }
  101558. }
  101559. else {
  101560. _this.attachToMesh(null);
  101561. }
  101562. }
  101563. });
  101564. }
  101565. /**
  101566. * Attaches a set of gizmos to the specified mesh
  101567. * @param mesh The mesh the gizmo's should be attached to
  101568. */
  101569. GizmoManager.prototype.attachToMesh = function (mesh) {
  101570. if (this._attachedMesh) {
  101571. this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior);
  101572. }
  101573. this._attachedMesh = mesh;
  101574. for (var key in this.gizmos) {
  101575. var gizmo = (this.gizmos[key]);
  101576. if (gizmo && this._gizmosEnabled[key]) {
  101577. gizmo.attachedMesh = mesh;
  101578. }
  101579. }
  101580. if (this.boundingBoxGizmoEnabled && this._attachedMesh) {
  101581. this._attachedMesh.addBehavior(this.boundingBoxDragBehavior);
  101582. }
  101583. };
  101584. Object.defineProperty(GizmoManager.prototype, "positionGizmoEnabled", {
  101585. get: function () {
  101586. return this._gizmosEnabled.positionGizmo;
  101587. },
  101588. /**
  101589. * If the position gizmo is enabled
  101590. */
  101591. set: function (value) {
  101592. if (value) {
  101593. if (!this.gizmos.positionGizmo) {
  101594. this.gizmos.positionGizmo = new BABYLON.PositionGizmo();
  101595. this.gizmos.positionGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  101596. }
  101597. this.gizmos.positionGizmo.attachedMesh = this._attachedMesh;
  101598. }
  101599. else if (this.gizmos.positionGizmo) {
  101600. this.gizmos.positionGizmo.attachedMesh = null;
  101601. }
  101602. this._gizmosEnabled.positionGizmo = value;
  101603. },
  101604. enumerable: true,
  101605. configurable: true
  101606. });
  101607. Object.defineProperty(GizmoManager.prototype, "rotationGizmoEnabled", {
  101608. get: function () {
  101609. return this._gizmosEnabled.rotationGizmo;
  101610. },
  101611. /**
  101612. * If the rotation gizmo is enabled
  101613. */
  101614. set: function (value) {
  101615. if (value) {
  101616. if (!this.gizmos.rotationGizmo) {
  101617. this.gizmos.rotationGizmo = new BABYLON.RotationGizmo();
  101618. this.gizmos.rotationGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  101619. }
  101620. this.gizmos.rotationGizmo.attachedMesh = this._attachedMesh;
  101621. }
  101622. else if (this.gizmos.rotationGizmo) {
  101623. this.gizmos.rotationGizmo.attachedMesh = null;
  101624. }
  101625. this._gizmosEnabled.rotationGizmo = value;
  101626. },
  101627. enumerable: true,
  101628. configurable: true
  101629. });
  101630. Object.defineProperty(GizmoManager.prototype, "scaleGizmoEnabled", {
  101631. get: function () {
  101632. return this._gizmosEnabled.scaleGizmo;
  101633. },
  101634. /**
  101635. * If the scale gizmo is enabled
  101636. */
  101637. set: function (value) {
  101638. if (value) {
  101639. this.gizmos.scaleGizmo = this.gizmos.scaleGizmo || new BABYLON.ScaleGizmo();
  101640. this.gizmos.scaleGizmo.attachedMesh = this._attachedMesh;
  101641. }
  101642. else if (this.gizmos.scaleGizmo) {
  101643. this.gizmos.scaleGizmo.attachedMesh = null;
  101644. }
  101645. this._gizmosEnabled.scaleGizmo = value;
  101646. },
  101647. enumerable: true,
  101648. configurable: true
  101649. });
  101650. Object.defineProperty(GizmoManager.prototype, "boundingBoxGizmoEnabled", {
  101651. get: function () {
  101652. return this._gizmosEnabled.boundingBoxGizmo;
  101653. },
  101654. /**
  101655. * If the boundingBox gizmo is enabled
  101656. */
  101657. set: function (value) {
  101658. if (value) {
  101659. this.gizmos.boundingBoxGizmo = this.gizmos.boundingBoxGizmo || new BABYLON.BoundingBoxGizmo(this._boundingBoxColor);
  101660. this.gizmos.boundingBoxGizmo.attachedMesh = this._attachedMesh;
  101661. if (this._attachedMesh) {
  101662. this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior);
  101663. this._attachedMesh.addBehavior(this.boundingBoxDragBehavior);
  101664. }
  101665. }
  101666. else if (this.gizmos.boundingBoxGizmo) {
  101667. this.gizmos.boundingBoxGizmo.attachedMesh = null;
  101668. }
  101669. this._gizmosEnabled.boundingBoxGizmo = value;
  101670. },
  101671. enumerable: true,
  101672. configurable: true
  101673. });
  101674. /**
  101675. * Disposes of the gizmo manager
  101676. */
  101677. GizmoManager.prototype.dispose = function () {
  101678. this.scene.onPointerObservable.remove(this._pointerObserver);
  101679. for (var key in this.gizmos) {
  101680. var gizmo = (this.gizmos[key]);
  101681. if (gizmo) {
  101682. gizmo.dispose();
  101683. }
  101684. }
  101685. this.boundingBoxDragBehavior.detach();
  101686. };
  101687. return GizmoManager;
  101688. }());
  101689. BABYLON.GizmoManager = GizmoManager;
  101690. })(BABYLON || (BABYLON = {}));
  101691. //# sourceMappingURL=babylon.gizmoManager.js.map
  101692. var BABYLON;
  101693. (function (BABYLON) {
  101694. /**
  101695. * Defines a target to use with MorphTargetManager
  101696. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  101697. */
  101698. var MorphTarget = /** @class */ (function () {
  101699. /**
  101700. * Creates a new MorphTarget
  101701. * @param name defines the name of the target
  101702. * @param influence defines the influence to use
  101703. */
  101704. function MorphTarget(
  101705. /** defines the name of the target */
  101706. name, influence, scene) {
  101707. if (influence === void 0) { influence = 0; }
  101708. if (scene === void 0) { scene = null; }
  101709. this.name = name;
  101710. /**
  101711. * Gets or sets the list of animations
  101712. */
  101713. this.animations = new Array();
  101714. this._positions = null;
  101715. this._normals = null;
  101716. this._tangents = null;
  101717. /**
  101718. * Observable raised when the influence changes
  101719. */
  101720. this.onInfluenceChanged = new BABYLON.Observable();
  101721. this._animationPropertiesOverride = null;
  101722. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  101723. this.influence = influence;
  101724. }
  101725. Object.defineProperty(MorphTarget.prototype, "influence", {
  101726. /**
  101727. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  101728. */
  101729. get: function () {
  101730. return this._influence;
  101731. },
  101732. set: function (influence) {
  101733. if (this._influence === influence) {
  101734. return;
  101735. }
  101736. var previous = this._influence;
  101737. this._influence = influence;
  101738. if (this.onInfluenceChanged.hasObservers) {
  101739. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  101740. }
  101741. },
  101742. enumerable: true,
  101743. configurable: true
  101744. });
  101745. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  101746. /**
  101747. * Gets or sets the animation properties override
  101748. */
  101749. get: function () {
  101750. if (!this._animationPropertiesOverride && this._scene) {
  101751. return this._scene.animationPropertiesOverride;
  101752. }
  101753. return this._animationPropertiesOverride;
  101754. },
  101755. set: function (value) {
  101756. this._animationPropertiesOverride = value;
  101757. },
  101758. enumerable: true,
  101759. configurable: true
  101760. });
  101761. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  101762. /**
  101763. * Gets a boolean defining if the target contains position data
  101764. */
  101765. get: function () {
  101766. return !!this._positions;
  101767. },
  101768. enumerable: true,
  101769. configurable: true
  101770. });
  101771. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  101772. /**
  101773. * Gets a boolean defining if the target contains normal data
  101774. */
  101775. get: function () {
  101776. return !!this._normals;
  101777. },
  101778. enumerable: true,
  101779. configurable: true
  101780. });
  101781. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  101782. /**
  101783. * Gets a boolean defining if the target contains tangent data
  101784. */
  101785. get: function () {
  101786. return !!this._tangents;
  101787. },
  101788. enumerable: true,
  101789. configurable: true
  101790. });
  101791. /**
  101792. * Affects position data to this target
  101793. * @param data defines the position data to use
  101794. */
  101795. MorphTarget.prototype.setPositions = function (data) {
  101796. this._positions = data;
  101797. };
  101798. /**
  101799. * Gets the position data stored in this target
  101800. * @returns a FloatArray containing the position data (or null if not present)
  101801. */
  101802. MorphTarget.prototype.getPositions = function () {
  101803. return this._positions;
  101804. };
  101805. /**
  101806. * Affects normal data to this target
  101807. * @param data defines the normal data to use
  101808. */
  101809. MorphTarget.prototype.setNormals = function (data) {
  101810. this._normals = data;
  101811. };
  101812. /**
  101813. * Gets the normal data stored in this target
  101814. * @returns a FloatArray containing the normal data (or null if not present)
  101815. */
  101816. MorphTarget.prototype.getNormals = function () {
  101817. return this._normals;
  101818. };
  101819. /**
  101820. * Affects tangent data to this target
  101821. * @param data defines the tangent data to use
  101822. */
  101823. MorphTarget.prototype.setTangents = function (data) {
  101824. this._tangents = data;
  101825. };
  101826. /**
  101827. * Gets the tangent data stored in this target
  101828. * @returns a FloatArray containing the tangent data (or null if not present)
  101829. */
  101830. MorphTarget.prototype.getTangents = function () {
  101831. return this._tangents;
  101832. };
  101833. /**
  101834. * Serializes the current target into a Serialization object
  101835. * @returns the serialized object
  101836. */
  101837. MorphTarget.prototype.serialize = function () {
  101838. var serializationObject = {};
  101839. serializationObject.name = this.name;
  101840. serializationObject.influence = this.influence;
  101841. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  101842. if (this.hasNormals) {
  101843. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  101844. }
  101845. if (this.hasTangents) {
  101846. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  101847. }
  101848. // Animations
  101849. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  101850. return serializationObject;
  101851. };
  101852. // Statics
  101853. /**
  101854. * Creates a new target from serialized data
  101855. * @param serializationObject defines the serialized data to use
  101856. * @returns a new MorphTarget
  101857. */
  101858. MorphTarget.Parse = function (serializationObject) {
  101859. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  101860. result.setPositions(serializationObject.positions);
  101861. if (serializationObject.normals) {
  101862. result.setNormals(serializationObject.normals);
  101863. }
  101864. if (serializationObject.tangents) {
  101865. result.setTangents(serializationObject.tangents);
  101866. }
  101867. // Animations
  101868. if (serializationObject.animations) {
  101869. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  101870. var parsedAnimation = serializationObject.animations[animationIndex];
  101871. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  101872. }
  101873. }
  101874. return result;
  101875. };
  101876. /**
  101877. * Creates a MorphTarget from mesh data
  101878. * @param mesh defines the source mesh
  101879. * @param name defines the name to use for the new target
  101880. * @param influence defines the influence to attach to the target
  101881. * @returns a new MorphTarget
  101882. */
  101883. MorphTarget.FromMesh = function (mesh, name, influence) {
  101884. if (!name) {
  101885. name = mesh.name;
  101886. }
  101887. var result = new MorphTarget(name, influence, mesh.getScene());
  101888. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  101889. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  101890. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  101891. }
  101892. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  101893. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  101894. }
  101895. return result;
  101896. };
  101897. return MorphTarget;
  101898. }());
  101899. BABYLON.MorphTarget = MorphTarget;
  101900. })(BABYLON || (BABYLON = {}));
  101901. //# sourceMappingURL=babylon.morphTarget.js.map
  101902. var BABYLON;
  101903. (function (BABYLON) {
  101904. /**
  101905. * This class is used to deform meshes using morphing between different targets
  101906. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  101907. */
  101908. var MorphTargetManager = /** @class */ (function () {
  101909. /**
  101910. * Creates a new MorphTargetManager
  101911. * @param scene defines the current scene
  101912. */
  101913. function MorphTargetManager(scene) {
  101914. if (scene === void 0) { scene = null; }
  101915. this._targets = new Array();
  101916. this._targetObservable = new Array();
  101917. this._activeTargets = new BABYLON.SmartArray(16);
  101918. this._supportsNormals = false;
  101919. this._supportsTangents = false;
  101920. this._vertexCount = 0;
  101921. this._uniqueId = 0;
  101922. this._tempInfluences = new Array();
  101923. if (!scene) {
  101924. scene = BABYLON.Engine.LastCreatedScene;
  101925. }
  101926. this._scene = scene;
  101927. if (this._scene) {
  101928. this._scene.morphTargetManagers.push(this);
  101929. this._uniqueId = this._scene.getUniqueId();
  101930. }
  101931. }
  101932. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  101933. /**
  101934. * Gets the unique ID of this manager
  101935. */
  101936. get: function () {
  101937. return this._uniqueId;
  101938. },
  101939. enumerable: true,
  101940. configurable: true
  101941. });
  101942. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  101943. /**
  101944. * Gets the number of vertices handled by this manager
  101945. */
  101946. get: function () {
  101947. return this._vertexCount;
  101948. },
  101949. enumerable: true,
  101950. configurable: true
  101951. });
  101952. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  101953. /**
  101954. * Gets a boolean indicating if this manager supports morphing of normals
  101955. */
  101956. get: function () {
  101957. return this._supportsNormals;
  101958. },
  101959. enumerable: true,
  101960. configurable: true
  101961. });
  101962. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  101963. /**
  101964. * Gets a boolean indicating if this manager supports morphing of tangents
  101965. */
  101966. get: function () {
  101967. return this._supportsTangents;
  101968. },
  101969. enumerable: true,
  101970. configurable: true
  101971. });
  101972. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  101973. /**
  101974. * Gets the number of targets stored in this manager
  101975. */
  101976. get: function () {
  101977. return this._targets.length;
  101978. },
  101979. enumerable: true,
  101980. configurable: true
  101981. });
  101982. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  101983. /**
  101984. * Gets the number of influencers (ie. the number of targets with influences > 0)
  101985. */
  101986. get: function () {
  101987. return this._activeTargets.length;
  101988. },
  101989. enumerable: true,
  101990. configurable: true
  101991. });
  101992. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  101993. /**
  101994. * Gets the list of influences (one per target)
  101995. */
  101996. get: function () {
  101997. return this._influences;
  101998. },
  101999. enumerable: true,
  102000. configurable: true
  102001. });
  102002. /**
  102003. * Gets the active target at specified index. An active target is a target with an influence > 0
  102004. * @param index defines the index to check
  102005. * @returns the requested target
  102006. */
  102007. MorphTargetManager.prototype.getActiveTarget = function (index) {
  102008. return this._activeTargets.data[index];
  102009. };
  102010. /**
  102011. * Gets the target at specified index
  102012. * @param index defines the index to check
  102013. * @returns the requested target
  102014. */
  102015. MorphTargetManager.prototype.getTarget = function (index) {
  102016. return this._targets[index];
  102017. };
  102018. /**
  102019. * Add a new target to this manager
  102020. * @param target defines the target to add
  102021. */
  102022. MorphTargetManager.prototype.addTarget = function (target) {
  102023. var _this = this;
  102024. this._targets.push(target);
  102025. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  102026. _this._syncActiveTargets(needUpdate);
  102027. }));
  102028. this._syncActiveTargets(true);
  102029. };
  102030. /**
  102031. * Removes a target from the manager
  102032. * @param target defines the target to remove
  102033. */
  102034. MorphTargetManager.prototype.removeTarget = function (target) {
  102035. var index = this._targets.indexOf(target);
  102036. if (index >= 0) {
  102037. this._targets.splice(index, 1);
  102038. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  102039. this._syncActiveTargets(true);
  102040. }
  102041. };
  102042. /**
  102043. * Serializes the current manager into a Serialization object
  102044. * @returns the serialized object
  102045. */
  102046. MorphTargetManager.prototype.serialize = function () {
  102047. var serializationObject = {};
  102048. serializationObject.id = this.uniqueId;
  102049. serializationObject.targets = [];
  102050. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  102051. var target = _a[_i];
  102052. serializationObject.targets.push(target.serialize());
  102053. }
  102054. return serializationObject;
  102055. };
  102056. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  102057. var influenceCount = 0;
  102058. this._activeTargets.reset();
  102059. this._supportsNormals = true;
  102060. this._supportsTangents = true;
  102061. this._vertexCount = 0;
  102062. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  102063. var target = _a[_i];
  102064. this._activeTargets.push(target);
  102065. this._tempInfluences[influenceCount++] = target.influence;
  102066. var positions = target.getPositions();
  102067. if (positions) {
  102068. this._supportsNormals = this._supportsNormals && target.hasNormals;
  102069. this._supportsTangents = this._supportsTangents && target.hasTangents;
  102070. var vertexCount = positions.length / 3;
  102071. if (this._vertexCount === 0) {
  102072. this._vertexCount = vertexCount;
  102073. }
  102074. else if (this._vertexCount !== vertexCount) {
  102075. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  102076. return;
  102077. }
  102078. }
  102079. }
  102080. if (!this._influences || this._influences.length !== influenceCount) {
  102081. this._influences = new Float32Array(influenceCount);
  102082. }
  102083. for (var index = 0; index < influenceCount; index++) {
  102084. this._influences[index] = this._tempInfluences[index];
  102085. }
  102086. if (needUpdate) {
  102087. this.synchronize();
  102088. }
  102089. };
  102090. /**
  102091. * Syncrhonize the targets with all the meshes using this morph target manager
  102092. */
  102093. MorphTargetManager.prototype.synchronize = function () {
  102094. if (!this._scene) {
  102095. return;
  102096. }
  102097. // Flag meshes as dirty to resync with the active targets
  102098. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  102099. var mesh = _a[_i];
  102100. if (mesh.morphTargetManager === this) {
  102101. mesh._syncGeometryWithMorphTargetManager();
  102102. }
  102103. }
  102104. };
  102105. // Statics
  102106. /**
  102107. * Creates a new MorphTargetManager from serialized data
  102108. * @param serializationObject defines the serialized data
  102109. * @param scene defines the hosting scene
  102110. * @returns the new MorphTargetManager
  102111. */
  102112. MorphTargetManager.Parse = function (serializationObject, scene) {
  102113. var result = new MorphTargetManager(scene);
  102114. result._uniqueId = serializationObject.id;
  102115. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  102116. var targetData = _a[_i];
  102117. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  102118. }
  102119. return result;
  102120. };
  102121. return MorphTargetManager;
  102122. }());
  102123. BABYLON.MorphTargetManager = MorphTargetManager;
  102124. })(BABYLON || (BABYLON = {}));
  102125. //# sourceMappingURL=babylon.morphTargetManager.js.map
  102126. var BABYLON;
  102127. (function (BABYLON) {
  102128. /**
  102129. * Octrees are a really powerful data structure that can quickly select entities based on space coordinates.
  102130. * @see https://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  102131. */
  102132. var Octree = /** @class */ (function () {
  102133. /**
  102134. * Creates a octree
  102135. * @see https://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  102136. * @param creationFunc function to be used to instatiate the octree
  102137. * @param maxBlockCapacity defines the maximum number of meshes you want on your octree's leaves (default: 64)
  102138. * @param maxDepth defines the maximum depth (sub-levels) for your octree. Default value is 2, which means 8 8 8 = 512 blocks :) (This parameter takes precedence over capacity.)
  102139. */
  102140. function Octree(creationFunc, maxBlockCapacity,
  102141. /** Defines the maximum depth (sub-levels) for your octree. Default value is 2, which means 8 8 8 = 512 blocks :) (This parameter takes precedence over capacity.) */
  102142. maxDepth) {
  102143. if (maxDepth === void 0) { maxDepth = 2; }
  102144. this.maxDepth = maxDepth;
  102145. /**
  102146. * Content stored in the octree
  102147. */
  102148. this.dynamicContent = new Array();
  102149. this._maxBlockCapacity = maxBlockCapacity || 64;
  102150. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  102151. this._creationFunc = creationFunc;
  102152. }
  102153. // Methods
  102154. /**
  102155. * Updates the octree by adding blocks for the passed in meshes within the min and max world parameters
  102156. * @param worldMin worldMin for the octree blocks var blockSize = new Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  102157. * @param worldMax worldMax for the octree blocks var blockSize = new Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  102158. * @param entries meshes to be added to the octree blocks
  102159. */
  102160. Octree.prototype.update = function (worldMin, worldMax, entries) {
  102161. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  102162. };
  102163. /**
  102164. * Adds a mesh to the octree
  102165. * @param entry Mesh to add to the octree
  102166. */
  102167. Octree.prototype.addMesh = function (entry) {
  102168. for (var index = 0; index < this.blocks.length; index++) {
  102169. var block = this.blocks[index];
  102170. block.addEntry(entry);
  102171. }
  102172. };
  102173. /**
  102174. * Selects an array of meshes within the frustum
  102175. * @param frustumPlanes The frustum planes to use which will select all meshes within it
  102176. * @param allowDuplicate If duplicate objects are allowed in the resulting object array
  102177. * @returns array of meshes within the frustum
  102178. */
  102179. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  102180. this._selectionContent.reset();
  102181. for (var index = 0; index < this.blocks.length; index++) {
  102182. var block = this.blocks[index];
  102183. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  102184. }
  102185. if (allowDuplicate) {
  102186. this._selectionContent.concat(this.dynamicContent);
  102187. }
  102188. else {
  102189. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  102190. }
  102191. return this._selectionContent;
  102192. };
  102193. /**
  102194. * Test if the octree intersect with the given bounding sphere and if yes, then add its content to the selection array
  102195. * @param sphereCenter defines the bounding sphere center
  102196. * @param sphereRadius defines the bounding sphere radius
  102197. * @param allowDuplicate defines if the selection array can contains duplicated entries
  102198. * @returns an array of objects that intersect the sphere
  102199. */
  102200. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  102201. this._selectionContent.reset();
  102202. for (var index = 0; index < this.blocks.length; index++) {
  102203. var block = this.blocks[index];
  102204. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  102205. }
  102206. if (allowDuplicate) {
  102207. this._selectionContent.concat(this.dynamicContent);
  102208. }
  102209. else {
  102210. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  102211. }
  102212. return this._selectionContent;
  102213. };
  102214. /**
  102215. * Test if the octree intersect with the given ray and if yes, then add its content to resulting array
  102216. * @param ray defines the ray to test with
  102217. * @returns array of intersected objects
  102218. */
  102219. Octree.prototype.intersectsRay = function (ray) {
  102220. this._selectionContent.reset();
  102221. for (var index = 0; index < this.blocks.length; index++) {
  102222. var block = this.blocks[index];
  102223. block.intersectsRay(ray, this._selectionContent);
  102224. }
  102225. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  102226. return this._selectionContent;
  102227. };
  102228. /**
  102229. * @hidden
  102230. */
  102231. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  102232. target.blocks = new Array();
  102233. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  102234. // Segmenting space
  102235. for (var x = 0; x < 2; x++) {
  102236. for (var y = 0; y < 2; y++) {
  102237. for (var z = 0; z < 2; z++) {
  102238. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  102239. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  102240. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  102241. block.addEntries(entries);
  102242. target.blocks.push(block);
  102243. }
  102244. }
  102245. }
  102246. };
  102247. /**
  102248. * Adds a mesh into the octree block if it intersects the block
  102249. */
  102250. Octree.CreationFuncForMeshes = function (entry, block) {
  102251. var boundingInfo = entry.getBoundingInfo();
  102252. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  102253. block.entries.push(entry);
  102254. }
  102255. };
  102256. /**
  102257. * Adds a submesh into the octree block if it intersects the block
  102258. */
  102259. Octree.CreationFuncForSubMeshes = function (entry, block) {
  102260. var boundingInfo = entry.getBoundingInfo();
  102261. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  102262. block.entries.push(entry);
  102263. }
  102264. };
  102265. return Octree;
  102266. }());
  102267. BABYLON.Octree = Octree;
  102268. })(BABYLON || (BABYLON = {}));
  102269. //# sourceMappingURL=babylon.octree.js.map
  102270. var BABYLON;
  102271. (function (BABYLON) {
  102272. /**
  102273. * Class used to store a cell in an octree
  102274. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  102275. */
  102276. var OctreeBlock = /** @class */ (function () {
  102277. /**
  102278. * Creates a new block
  102279. * @param minPoint defines the minimum vector (in world space) of the block's bounding box
  102280. * @param maxPoint defines the maximum vector (in world space) of the block's bounding box
  102281. * @param capacity defines the maximum capacity of this block (if capacity is reached the block will be split into sub blocks)
  102282. * @param depth defines the current depth of this block in the octree
  102283. * @param maxDepth defines the maximal depth allowed (beyond this value, the capacity is ignored)
  102284. * @param creationFunc defines a callback to call when an element is added to the block
  102285. */
  102286. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  102287. /**
  102288. * Gets the content of the current block
  102289. */
  102290. this.entries = new Array();
  102291. this._boundingVectors = new Array();
  102292. this._capacity = capacity;
  102293. this._depth = depth;
  102294. this._maxDepth = maxDepth;
  102295. this._creationFunc = creationFunc;
  102296. this._minPoint = minPoint;
  102297. this._maxPoint = maxPoint;
  102298. this._boundingVectors.push(minPoint.clone());
  102299. this._boundingVectors.push(maxPoint.clone());
  102300. this._boundingVectors.push(minPoint.clone());
  102301. this._boundingVectors[2].x = maxPoint.x;
  102302. this._boundingVectors.push(minPoint.clone());
  102303. this._boundingVectors[3].y = maxPoint.y;
  102304. this._boundingVectors.push(minPoint.clone());
  102305. this._boundingVectors[4].z = maxPoint.z;
  102306. this._boundingVectors.push(maxPoint.clone());
  102307. this._boundingVectors[5].z = minPoint.z;
  102308. this._boundingVectors.push(maxPoint.clone());
  102309. this._boundingVectors[6].x = minPoint.x;
  102310. this._boundingVectors.push(maxPoint.clone());
  102311. this._boundingVectors[7].y = minPoint.y;
  102312. }
  102313. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  102314. // Property
  102315. /**
  102316. * Gets the maximum capacity of this block (if capacity is reached the block will be split into sub blocks)
  102317. */
  102318. get: function () {
  102319. return this._capacity;
  102320. },
  102321. enumerable: true,
  102322. configurable: true
  102323. });
  102324. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  102325. /**
  102326. * Gets the minimum vector (in world space) of the block's bounding box
  102327. */
  102328. get: function () {
  102329. return this._minPoint;
  102330. },
  102331. enumerable: true,
  102332. configurable: true
  102333. });
  102334. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  102335. /**
  102336. * Gets the maximum vector (in world space) of the block's bounding box
  102337. */
  102338. get: function () {
  102339. return this._maxPoint;
  102340. },
  102341. enumerable: true,
  102342. configurable: true
  102343. });
  102344. // Methods
  102345. /**
  102346. * Add a new element to this block
  102347. * @param entry defines the element to add
  102348. */
  102349. OctreeBlock.prototype.addEntry = function (entry) {
  102350. if (this.blocks) {
  102351. for (var index = 0; index < this.blocks.length; index++) {
  102352. var block = this.blocks[index];
  102353. block.addEntry(entry);
  102354. }
  102355. return;
  102356. }
  102357. this._creationFunc(entry, this);
  102358. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  102359. this.createInnerBlocks();
  102360. }
  102361. };
  102362. /**
  102363. * Add an array of elements to this block
  102364. * @param entries defines the array of elements to add
  102365. */
  102366. OctreeBlock.prototype.addEntries = function (entries) {
  102367. for (var index = 0; index < entries.length; index++) {
  102368. var mesh = entries[index];
  102369. this.addEntry(mesh);
  102370. }
  102371. };
  102372. /**
  102373. * Test if the current block intersects the furstum planes and if yes, then add its content to the selection array
  102374. * @param frustumPlanes defines the frustum planes to test
  102375. * @param selection defines the array to store current content if selection is positive
  102376. * @param allowDuplicate defines if the selection array can contains duplicated entries
  102377. */
  102378. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  102379. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  102380. if (this.blocks) {
  102381. for (var index = 0; index < this.blocks.length; index++) {
  102382. var block = this.blocks[index];
  102383. block.select(frustumPlanes, selection, allowDuplicate);
  102384. }
  102385. return;
  102386. }
  102387. if (allowDuplicate) {
  102388. selection.concat(this.entries);
  102389. }
  102390. else {
  102391. selection.concatWithNoDuplicate(this.entries);
  102392. }
  102393. }
  102394. };
  102395. /**
  102396. * Test if the current block intersect with the given bounding sphere and if yes, then add its content to the selection array
  102397. * @param sphereCenter defines the bounding sphere center
  102398. * @param sphereRadius defines the bounding sphere radius
  102399. * @param selection defines the array to store current content if selection is positive
  102400. * @param allowDuplicate defines if the selection array can contains duplicated entries
  102401. */
  102402. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  102403. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  102404. if (this.blocks) {
  102405. for (var index = 0; index < this.blocks.length; index++) {
  102406. var block = this.blocks[index];
  102407. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  102408. }
  102409. return;
  102410. }
  102411. if (allowDuplicate) {
  102412. selection.concat(this.entries);
  102413. }
  102414. else {
  102415. selection.concatWithNoDuplicate(this.entries);
  102416. }
  102417. }
  102418. };
  102419. /**
  102420. * Test if the current block intersect with the given ray and if yes, then add its content to the selection array
  102421. * @param ray defines the ray to test with
  102422. * @param selection defines the array to store current content if selection is positive
  102423. */
  102424. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  102425. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  102426. if (this.blocks) {
  102427. for (var index = 0; index < this.blocks.length; index++) {
  102428. var block = this.blocks[index];
  102429. block.intersectsRay(ray, selection);
  102430. }
  102431. return;
  102432. }
  102433. selection.concatWithNoDuplicate(this.entries);
  102434. }
  102435. };
  102436. /**
  102437. * Subdivide the content into child blocks (this block will then be empty)
  102438. */
  102439. OctreeBlock.prototype.createInnerBlocks = function () {
  102440. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  102441. };
  102442. return OctreeBlock;
  102443. }());
  102444. BABYLON.OctreeBlock = OctreeBlock;
  102445. })(BABYLON || (BABYLON = {}));
  102446. //# sourceMappingURL=babylon.octreeBlock.js.map
  102447. var BABYLON;
  102448. (function (BABYLON) {
  102449. BABYLON.Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  102450. if (maxCapacity === void 0) { maxCapacity = 64; }
  102451. if (maxDepth === void 0) { maxDepth = 2; }
  102452. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_OCTREE);
  102453. if (!component) {
  102454. component = new OctreeSceneComponent(this);
  102455. this._addComponent(component);
  102456. }
  102457. if (!this._selectionOctree) {
  102458. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  102459. }
  102460. var worldExtends = this.getWorldExtends();
  102461. // Update octree
  102462. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  102463. return this._selectionOctree;
  102464. };
  102465. Object.defineProperty(BABYLON.Scene.prototype, "selectionOctree", {
  102466. get: function () {
  102467. return this._selectionOctree;
  102468. },
  102469. enumerable: true,
  102470. configurable: true
  102471. });
  102472. /**
  102473. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  102474. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  102475. * @param maxCapacity defines the maximum size of each block (64 by default)
  102476. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  102477. * @returns the new octree
  102478. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  102479. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  102480. */
  102481. BABYLON.AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  102482. if (maxCapacity === void 0) { maxCapacity = 64; }
  102483. if (maxDepth === void 0) { maxDepth = 2; }
  102484. var scene = this.getScene();
  102485. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_OCTREE);
  102486. if (!component) {
  102487. component = new OctreeSceneComponent(scene);
  102488. scene._addComponent(component);
  102489. }
  102490. if (!this._submeshesOctree) {
  102491. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  102492. }
  102493. this.computeWorldMatrix(true);
  102494. var boundingInfo = this.getBoundingInfo();
  102495. // Update octree
  102496. var bbox = boundingInfo.boundingBox;
  102497. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  102498. return this._submeshesOctree;
  102499. };
  102500. /**
  102501. * Defines the octree scene component responsible to manage any octrees
  102502. * in a given scene.
  102503. */
  102504. var OctreeSceneComponent = /** @class */ (function () {
  102505. /**
  102506. * Creates a new instance of the component for the given scene
  102507. * @param scene Defines the scene to register the component in
  102508. */
  102509. function OctreeSceneComponent(scene) {
  102510. /**
  102511. * The component name helpfull to identify the component in the list of scene components.
  102512. */
  102513. this.name = BABYLON.SceneComponentConstants.NAME_OCTREE;
  102514. /**
  102515. * Indicates if the meshes have been checked to make sure they are isEnabled()
  102516. */
  102517. this.checksIsEnabled = true;
  102518. this._tempRay = new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(1, 1, 1));
  102519. this.scene = scene;
  102520. this.scene.getActiveMeshCandidates = this.getActiveMeshCandidates.bind(this);
  102521. this.scene.getActiveSubMeshCandidates = this.getActiveSubMeshCandidates.bind(this);
  102522. this.scene.getCollidingSubMeshCandidates = this.getCollidingSubMeshCandidates.bind(this);
  102523. this.scene.getIntersectingSubMeshCandidates = this.getIntersectingSubMeshCandidates.bind(this);
  102524. }
  102525. /**
  102526. * Registers the component in a given scene
  102527. */
  102528. OctreeSceneComponent.prototype.register = function () {
  102529. var _this = this;
  102530. this.scene.onMeshRemovedObservable.add(function (mesh) {
  102531. var sceneOctree = _this.scene.selectionOctree;
  102532. if (sceneOctree !== undefined && sceneOctree !== null) {
  102533. var index = sceneOctree.dynamicContent.indexOf(mesh);
  102534. if (index !== -1) {
  102535. sceneOctree.dynamicContent.splice(index, 1);
  102536. }
  102537. }
  102538. });
  102539. this.scene.onMeshImportedObservable.add(function (mesh) {
  102540. var sceneOctree = _this.scene.selectionOctree;
  102541. if (sceneOctree !== undefined && sceneOctree !== null) {
  102542. sceneOctree.addMesh(mesh);
  102543. }
  102544. });
  102545. };
  102546. /**
  102547. * Return the list of active meshes
  102548. * @returns the list of active meshes
  102549. */
  102550. OctreeSceneComponent.prototype.getActiveMeshCandidates = function () {
  102551. if (this.scene._selectionOctree) {
  102552. var selection = this.scene._selectionOctree.select(this.scene.frustumPlanes);
  102553. return selection;
  102554. }
  102555. return this.scene._getDefaultMeshCandidates();
  102556. };
  102557. /**
  102558. * Return the list of active sub meshes
  102559. * @param mesh The mesh to get the candidates sub meshes from
  102560. * @returns the list of active sub meshes
  102561. */
  102562. OctreeSceneComponent.prototype.getActiveSubMeshCandidates = function (mesh) {
  102563. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  102564. var intersections = mesh._submeshesOctree.select(this.scene.frustumPlanes);
  102565. return intersections;
  102566. }
  102567. return this.scene._getDefaultSubMeshCandidates(mesh);
  102568. };
  102569. /**
  102570. * Return the list of sub meshes intersecting with a given local ray
  102571. * @param mesh defines the mesh to find the submesh for
  102572. * @param localRay defines the ray in local space
  102573. * @returns the list of intersecting sub meshes
  102574. */
  102575. OctreeSceneComponent.prototype.getIntersectingSubMeshCandidates = function (mesh, localRay) {
  102576. if (mesh._submeshesOctree && mesh.useOctreeForPicking) {
  102577. BABYLON.Ray.TransformToRef(localRay, mesh.getWorldMatrix(), this._tempRay);
  102578. var intersections = mesh._submeshesOctree.intersectsRay(this._tempRay);
  102579. return intersections;
  102580. }
  102581. return this.scene._getDefaultSubMeshCandidates(mesh);
  102582. };
  102583. /**
  102584. * Return the list of sub meshes colliding with a collider
  102585. * @param mesh defines the mesh to find the submesh for
  102586. * @param collider defines the collider to evaluate the collision against
  102587. * @returns the list of colliding sub meshes
  102588. */
  102589. OctreeSceneComponent.prototype.getCollidingSubMeshCandidates = function (mesh, collider) {
  102590. if (mesh._submeshesOctree && mesh.useOctreeForCollisions) {
  102591. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  102592. var intersections = mesh._submeshesOctree.intersects(collider._basePointWorld, radius);
  102593. return intersections;
  102594. }
  102595. return this.scene._getDefaultSubMeshCandidates(mesh);
  102596. };
  102597. /**
  102598. * Rebuilds the elements related to this component in case of
  102599. * context lost for instance.
  102600. */
  102601. OctreeSceneComponent.prototype.rebuild = function () {
  102602. // Nothing to do here.
  102603. };
  102604. /**
  102605. * Disposes the component and the associated ressources.
  102606. */
  102607. OctreeSceneComponent.prototype.dispose = function () {
  102608. // Nothing to do here.
  102609. };
  102610. return OctreeSceneComponent;
  102611. }());
  102612. BABYLON.OctreeSceneComponent = OctreeSceneComponent;
  102613. })(BABYLON || (BABYLON = {}));
  102614. //# sourceMappingURL=babylon.octreeSceneComponent.js.map
  102615. var BABYLON;
  102616. (function (BABYLON) {
  102617. /**
  102618. * Postprocess used to generate anaglyphic rendering
  102619. */
  102620. var AnaglyphPostProcess = /** @class */ (function (_super) {
  102621. __extends(AnaglyphPostProcess, _super);
  102622. /**
  102623. * Creates a new AnaglyphPostProcess
  102624. * @param name defines postprocess name
  102625. * @param options defines creation options or target ratio scale
  102626. * @param rigCameras defines cameras using this postprocess
  102627. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  102628. * @param engine defines hosting engine
  102629. * @param reusable defines if the postprocess will be reused multiple times per frame
  102630. */
  102631. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  102632. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  102633. _this._passedProcess = rigCameras[0]._rigPostProcess;
  102634. _this.onApplyObservable.add(function (effect) {
  102635. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  102636. });
  102637. return _this;
  102638. }
  102639. return AnaglyphPostProcess;
  102640. }(BABYLON.PostProcess));
  102641. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  102642. })(BABYLON || (BABYLON = {}));
  102643. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  102644. var BABYLON;
  102645. (function (BABYLON) {
  102646. BABYLON.Node.AddNodeConstructor("AnaglyphArcRotateCamera", function (name, scene, options) {
  102647. return function () { return new AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  102648. });
  102649. /**
  102650. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  102651. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  102652. */
  102653. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  102654. __extends(AnaglyphArcRotateCamera, _super);
  102655. /**
  102656. * Creates a new AnaglyphArcRotateCamera
  102657. * @param name defines camera name
  102658. * @param alpha defines alpha angle (in radians)
  102659. * @param beta defines beta angle (in radians)
  102660. * @param radius defines radius
  102661. * @param target defines camera target
  102662. * @param interaxialDistance defines distance between each color axis
  102663. * @param scene defines the hosting scene
  102664. */
  102665. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  102666. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  102667. _this.interaxialDistance = interaxialDistance;
  102668. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  102669. return _this;
  102670. }
  102671. /**
  102672. * Gets camera class name
  102673. * @returns AnaglyphArcRotateCamera
  102674. */
  102675. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  102676. return "AnaglyphArcRotateCamera";
  102677. };
  102678. return AnaglyphArcRotateCamera;
  102679. }(BABYLON.ArcRotateCamera));
  102680. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  102681. })(BABYLON || (BABYLON = {}));
  102682. //# sourceMappingURL=babylon.anaglyphArcRotateCamera.js.map
  102683. var BABYLON;
  102684. (function (BABYLON) {
  102685. BABYLON.Node.AddNodeConstructor("AnaglyphFreeCamera", function (name, scene, options) {
  102686. return function () { return new AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  102687. });
  102688. /**
  102689. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  102690. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  102691. */
  102692. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  102693. __extends(AnaglyphFreeCamera, _super);
  102694. /**
  102695. * Creates a new AnaglyphFreeCamera
  102696. * @param name defines camera name
  102697. * @param position defines initial position
  102698. * @param interaxialDistance defines distance between each color axis
  102699. * @param scene defines the hosting scene
  102700. */
  102701. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  102702. var _this = _super.call(this, name, position, scene) || this;
  102703. _this.interaxialDistance = interaxialDistance;
  102704. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  102705. return _this;
  102706. }
  102707. /**
  102708. * Gets camera class name
  102709. * @returns AnaglyphFreeCamera
  102710. */
  102711. AnaglyphFreeCamera.prototype.getClassName = function () {
  102712. return "AnaglyphFreeCamera";
  102713. };
  102714. return AnaglyphFreeCamera;
  102715. }(BABYLON.FreeCamera));
  102716. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  102717. })(BABYLON || (BABYLON = {}));
  102718. //# sourceMappingURL=babylon.anaglyphFreeCamera.js.map
  102719. var BABYLON;
  102720. (function (BABYLON) {
  102721. BABYLON.Node.AddNodeConstructor("AnaglyphGamepadCamera", function (name, scene, options) {
  102722. return function () { return new AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  102723. });
  102724. /**
  102725. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  102726. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  102727. */
  102728. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  102729. __extends(AnaglyphGamepadCamera, _super);
  102730. /**
  102731. * Creates a new AnaglyphGamepadCamera
  102732. * @param name defines camera name
  102733. * @param position defines initial position
  102734. * @param interaxialDistance defines distance between each color axis
  102735. * @param scene defines the hosting scene
  102736. */
  102737. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  102738. var _this = _super.call(this, name, position, scene) || this;
  102739. _this.interaxialDistance = interaxialDistance;
  102740. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  102741. return _this;
  102742. }
  102743. /**
  102744. * Gets camera class name
  102745. * @returns AnaglyphGamepadCamera
  102746. */
  102747. AnaglyphGamepadCamera.prototype.getClassName = function () {
  102748. return "AnaglyphGamepadCamera";
  102749. };
  102750. return AnaglyphGamepadCamera;
  102751. }(BABYLON.GamepadCamera));
  102752. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  102753. })(BABYLON || (BABYLON = {}));
  102754. //# sourceMappingURL=babylon.anaglyphGamepadCamera.js.map
  102755. var BABYLON;
  102756. (function (BABYLON) {
  102757. BABYLON.Node.AddNodeConstructor("AnaglyphUniversalCamera", function (name, scene, options) {
  102758. return function () { return new AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  102759. });
  102760. /**
  102761. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  102762. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  102763. */
  102764. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  102765. __extends(AnaglyphUniversalCamera, _super);
  102766. /**
  102767. * Creates a new AnaglyphUniversalCamera
  102768. * @param name defines camera name
  102769. * @param position defines initial position
  102770. * @param interaxialDistance defines distance between each color axis
  102771. * @param scene defines the hosting scene
  102772. */
  102773. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  102774. var _this = _super.call(this, name, position, scene) || this;
  102775. _this.interaxialDistance = interaxialDistance;
  102776. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  102777. return _this;
  102778. }
  102779. /**
  102780. * Gets camera class name
  102781. * @returns AnaglyphUniversalCamera
  102782. */
  102783. AnaglyphUniversalCamera.prototype.getClassName = function () {
  102784. return "AnaglyphUniversalCamera";
  102785. };
  102786. return AnaglyphUniversalCamera;
  102787. }(BABYLON.UniversalCamera));
  102788. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  102789. })(BABYLON || (BABYLON = {}));
  102790. //# sourceMappingURL=babylon.anaglyphUniversalCamera.js.map
  102791. var BABYLON;
  102792. (function (BABYLON) {
  102793. /**
  102794. * StereoscopicInterlacePostProcess used to render stereo views from a rigged camera
  102795. */
  102796. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  102797. __extends(StereoscopicInterlacePostProcess, _super);
  102798. /**
  102799. * Initializes a StereoscopicInterlacePostProcess
  102800. * @param name The name of the effect.
  102801. * @param rigCameras The rig cameras to be appled to the post process
  102802. * @param isStereoscopicHoriz If the rendered results are horizontal or verticle
  102803. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  102804. * @param engine The engine which the post process will be applied. (default: current engine)
  102805. * @param reusable If the post process can be reused on the same frame. (default: false)
  102806. */
  102807. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  102808. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  102809. _this._passedProcess = rigCameras[0]._rigPostProcess;
  102810. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  102811. _this.onSizeChangedObservable.add(function () {
  102812. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  102813. });
  102814. _this.onApplyObservable.add(function (effect) {
  102815. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  102816. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  102817. });
  102818. return _this;
  102819. }
  102820. return StereoscopicInterlacePostProcess;
  102821. }(BABYLON.PostProcess));
  102822. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  102823. })(BABYLON || (BABYLON = {}));
  102824. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  102825. var BABYLON;
  102826. (function (BABYLON) {
  102827. BABYLON.Node.AddNodeConstructor("StereoscopicArcRotateCamera", function (name, scene, options) {
  102828. return function () { return new StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  102829. });
  102830. /**
  102831. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  102832. * @see http://doc.babylonjs.com/features/cameras
  102833. */
  102834. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  102835. __extends(StereoscopicArcRotateCamera, _super);
  102836. /**
  102837. * Creates a new StereoscopicArcRotateCamera
  102838. * @param name defines camera name
  102839. * @param alpha defines alpha angle (in radians)
  102840. * @param beta defines beta angle (in radians)
  102841. * @param radius defines radius
  102842. * @param target defines camera target
  102843. * @param interaxialDistance defines distance between each color axis
  102844. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  102845. * @param scene defines the hosting scene
  102846. */
  102847. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  102848. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  102849. _this.interaxialDistance = interaxialDistance;
  102850. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  102851. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  102852. return _this;
  102853. }
  102854. /**
  102855. * Gets camera class name
  102856. * @returns StereoscopicArcRotateCamera
  102857. */
  102858. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  102859. return "StereoscopicArcRotateCamera";
  102860. };
  102861. return StereoscopicArcRotateCamera;
  102862. }(BABYLON.ArcRotateCamera));
  102863. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  102864. })(BABYLON || (BABYLON = {}));
  102865. //# sourceMappingURL=babylon.stereoscopicArcRotateCamera.js.map
  102866. var BABYLON;
  102867. (function (BABYLON) {
  102868. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  102869. return function () { return new StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  102870. });
  102871. /**
  102872. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  102873. * @see http://doc.babylonjs.com/features/cameras
  102874. */
  102875. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  102876. __extends(StereoscopicFreeCamera, _super);
  102877. /**
  102878. * Creates a new StereoscopicFreeCamera
  102879. * @param name defines camera name
  102880. * @param position defines initial position
  102881. * @param interaxialDistance defines distance between each color axis
  102882. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  102883. * @param scene defines the hosting scene
  102884. */
  102885. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  102886. var _this = _super.call(this, name, position, scene) || this;
  102887. _this.interaxialDistance = interaxialDistance;
  102888. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  102889. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  102890. return _this;
  102891. }
  102892. /**
  102893. * Gets camera class name
  102894. * @returns StereoscopicFreeCamera
  102895. */
  102896. StereoscopicFreeCamera.prototype.getClassName = function () {
  102897. return "StereoscopicFreeCamera";
  102898. };
  102899. return StereoscopicFreeCamera;
  102900. }(BABYLON.FreeCamera));
  102901. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  102902. })(BABYLON || (BABYLON = {}));
  102903. //# sourceMappingURL=babylon.stereoscopicFreeCamera.js.map
  102904. var BABYLON;
  102905. (function (BABYLON) {
  102906. BABYLON.Node.AddNodeConstructor("StereoscopicGamepadCamera", function (name, scene, options) {
  102907. return function () { return new StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  102908. });
  102909. /**
  102910. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  102911. * @see http://doc.babylonjs.com/features/cameras
  102912. */
  102913. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  102914. __extends(StereoscopicGamepadCamera, _super);
  102915. /**
  102916. * Creates a new StereoscopicGamepadCamera
  102917. * @param name defines camera name
  102918. * @param position defines initial position
  102919. * @param interaxialDistance defines distance between each color axis
  102920. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  102921. * @param scene defines the hosting scene
  102922. */
  102923. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  102924. var _this = _super.call(this, name, position, scene) || this;
  102925. _this.interaxialDistance = interaxialDistance;
  102926. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  102927. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  102928. return _this;
  102929. }
  102930. /**
  102931. * Gets camera class name
  102932. * @returns StereoscopicGamepadCamera
  102933. */
  102934. StereoscopicGamepadCamera.prototype.getClassName = function () {
  102935. return "StereoscopicGamepadCamera";
  102936. };
  102937. return StereoscopicGamepadCamera;
  102938. }(BABYLON.GamepadCamera));
  102939. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  102940. })(BABYLON || (BABYLON = {}));
  102941. //# sourceMappingURL=babylon.stereoscopicGamepadCamera.js.map
  102942. var BABYLON;
  102943. (function (BABYLON) {
  102944. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  102945. return function () { return new StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  102946. });
  102947. /**
  102948. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  102949. * @see http://doc.babylonjs.com/features/cameras
  102950. */
  102951. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  102952. __extends(StereoscopicUniversalCamera, _super);
  102953. /**
  102954. * Creates a new StereoscopicUniversalCamera
  102955. * @param name defines camera name
  102956. * @param position defines initial position
  102957. * @param interaxialDistance defines distance between each color axis
  102958. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  102959. * @param scene defines the hosting scene
  102960. */
  102961. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  102962. var _this = _super.call(this, name, position, scene) || this;
  102963. _this.interaxialDistance = interaxialDistance;
  102964. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  102965. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  102966. return _this;
  102967. }
  102968. /**
  102969. * Gets camera class name
  102970. * @returns StereoscopicUniversalCamera
  102971. */
  102972. StereoscopicUniversalCamera.prototype.getClassName = function () {
  102973. return "StereoscopicUniversalCamera";
  102974. };
  102975. return StereoscopicUniversalCamera;
  102976. }(BABYLON.UniversalCamera));
  102977. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  102978. })(BABYLON || (BABYLON = {}));
  102979. //# sourceMappingURL=babylon.stereoscopicUniversalCamera.js.map
  102980. var BABYLON;
  102981. (function (BABYLON) {
  102982. /**
  102983. * VRDistortionCorrectionPostProcess used for mobile VR
  102984. */
  102985. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  102986. __extends(VRDistortionCorrectionPostProcess, _super);
  102987. /**
  102988. * Initializes the VRDistortionCorrectionPostProcess
  102989. * @param name The name of the effect.
  102990. * @param camera The camera to apply the render pass to.
  102991. * @param isRightEye If this is for the right eye distortion
  102992. * @param vrMetrics All the required metrics for the VR camera
  102993. */
  102994. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  102995. var _this = _super.call(this, name, "vrDistortionCorrection", [
  102996. 'LensCenter',
  102997. 'Scale',
  102998. 'ScaleIn',
  102999. 'HmdWarpParam'
  103000. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  103001. _this._isRightEye = isRightEye;
  103002. _this._distortionFactors = vrMetrics.distortionK;
  103003. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  103004. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  103005. _this.adaptScaleToCurrentViewport = true;
  103006. _this.onSizeChangedObservable.add(function () {
  103007. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  103008. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  103009. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  103010. });
  103011. _this.onApplyObservable.add(function (effect) {
  103012. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  103013. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  103014. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  103015. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  103016. });
  103017. return _this;
  103018. }
  103019. return VRDistortionCorrectionPostProcess;
  103020. }(BABYLON.PostProcess));
  103021. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  103022. })(BABYLON || (BABYLON = {}));
  103023. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  103024. var BABYLON;
  103025. (function (BABYLON) {
  103026. /**
  103027. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  103028. * Screen rotation is taken into account.
  103029. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  103030. */
  103031. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  103032. /**
  103033. * Instantiates a new input
  103034. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  103035. */
  103036. function FreeCameraDeviceOrientationInput() {
  103037. var _this = this;
  103038. this._screenOrientationAngle = 0;
  103039. this._screenQuaternion = new BABYLON.Quaternion();
  103040. this._alpha = 0;
  103041. this._beta = 0;
  103042. this._gamma = 0;
  103043. this._orientationChanged = function () {
  103044. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  103045. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  103046. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  103047. };
  103048. this._deviceOrientation = function (evt) {
  103049. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  103050. _this._beta = evt.beta !== null ? evt.beta : 0;
  103051. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  103052. };
  103053. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  103054. this._orientationChanged();
  103055. }
  103056. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  103057. /**
  103058. * Define the camera controlled by the input.
  103059. */
  103060. get: function () {
  103061. return this._camera;
  103062. },
  103063. set: function (camera) {
  103064. this._camera = camera;
  103065. if (this._camera != null && !this._camera.rotationQuaternion) {
  103066. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  103067. }
  103068. },
  103069. enumerable: true,
  103070. configurable: true
  103071. });
  103072. /**
  103073. * Attach the input controls to a specific dom element to get the input from.
  103074. * @param element Defines the element the controls should be listened from
  103075. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  103076. */
  103077. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  103078. window.addEventListener("orientationchange", this._orientationChanged);
  103079. window.addEventListener("deviceorientation", this._deviceOrientation);
  103080. //In certain cases, the attach control is called AFTER orientation was changed,
  103081. //So this is needed.
  103082. this._orientationChanged();
  103083. };
  103084. /**
  103085. * Detach the current controls from the specified dom element.
  103086. * @param element Defines the element to stop listening the inputs from
  103087. */
  103088. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  103089. window.removeEventListener("orientationchange", this._orientationChanged);
  103090. window.removeEventListener("deviceorientation", this._deviceOrientation);
  103091. };
  103092. /**
  103093. * Update the current camera state depending on the inputs that have been used this frame.
  103094. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  103095. */
  103096. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  103097. //if no device orientation provided, don't update the rotation.
  103098. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  103099. if (!this._alpha)
  103100. return;
  103101. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  103102. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  103103. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  103104. //Mirror on XY Plane
  103105. this._camera.rotationQuaternion.z *= -1;
  103106. this._camera.rotationQuaternion.w *= -1;
  103107. };
  103108. /**
  103109. * Gets the class name of the current intput.
  103110. * @returns the class name
  103111. */
  103112. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  103113. return "FreeCameraDeviceOrientationInput";
  103114. };
  103115. /**
  103116. * Get the friendly name associated with the input class.
  103117. * @returns the input friendly name
  103118. */
  103119. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  103120. return "deviceOrientation";
  103121. };
  103122. return FreeCameraDeviceOrientationInput;
  103123. }());
  103124. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  103125. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  103126. })(BABYLON || (BABYLON = {}));
  103127. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  103128. var BABYLON;
  103129. (function (BABYLON) {
  103130. /**
  103131. * Manage the device orientation inputs (gyroscope) to control an arc rotate camera.
  103132. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  103133. */
  103134. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  103135. /**
  103136. * Instantiate a new ArcRotateCameraVRDeviceOrientationInput.
  103137. */
  103138. function ArcRotateCameraVRDeviceOrientationInput() {
  103139. /**
  103140. * Defines a correction factor applied on the alpha value retrieved from the orientation events.
  103141. */
  103142. this.alphaCorrection = 1;
  103143. /**
  103144. * Defines a correction factor applied on the beta value retrieved from the orientation events.
  103145. */
  103146. this.betaCorrection = 1;
  103147. /**
  103148. * Defines a correction factor applied on the gamma value retrieved from the orientation events.
  103149. */
  103150. this.gammaCorrection = 1;
  103151. this._alpha = 0;
  103152. this._gamma = 0;
  103153. this._dirty = false;
  103154. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  103155. }
  103156. /**
  103157. * Attach the input controls to a specific dom element to get the input from.
  103158. * @param element Defines the element the controls should be listened from
  103159. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  103160. */
  103161. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  103162. this.camera.attachControl(element, noPreventDefault);
  103163. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  103164. };
  103165. /** @hidden */
  103166. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  103167. if (evt.alpha !== null) {
  103168. this._alpha = +evt.alpha | 0;
  103169. }
  103170. if (evt.gamma !== null) {
  103171. this._gamma = +evt.gamma | 0;
  103172. }
  103173. this._dirty = true;
  103174. };
  103175. /**
  103176. * Update the current camera state depending on the inputs that have been used this frame.
  103177. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  103178. */
  103179. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  103180. if (this._dirty) {
  103181. this._dirty = false;
  103182. if (this._gamma < 0) {
  103183. this._gamma = 180 + this._gamma;
  103184. }
  103185. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  103186. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  103187. }
  103188. };
  103189. /**
  103190. * Detach the current controls from the specified dom element.
  103191. * @param element Defines the element to stop listening the inputs from
  103192. */
  103193. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  103194. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  103195. };
  103196. /**
  103197. * Gets the class name of the current intput.
  103198. * @returns the class name
  103199. */
  103200. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  103201. return "ArcRotateCameraVRDeviceOrientationInput";
  103202. };
  103203. /**
  103204. * Get the friendly name associated with the input class.
  103205. * @returns the input friendly name
  103206. */
  103207. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  103208. return "VRDeviceOrientation";
  103209. };
  103210. return ArcRotateCameraVRDeviceOrientationInput;
  103211. }());
  103212. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  103213. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  103214. })(BABYLON || (BABYLON = {}));
  103215. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  103216. var BABYLON;
  103217. (function (BABYLON) {
  103218. /**
  103219. * This represents all the required metrics to create a VR camera.
  103220. * @see http://doc.babylonjs.com/babylon101/cameras#device-orientation-camera
  103221. */
  103222. var VRCameraMetrics = /** @class */ (function () {
  103223. function VRCameraMetrics() {
  103224. /**
  103225. * Define if the current vr camera should compensate the distortion of the lense or not.
  103226. */
  103227. this.compensateDistortion = true;
  103228. }
  103229. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  103230. /**
  103231. * Gets the rendering aspect ratio based on the provided resolutions.
  103232. */
  103233. get: function () {
  103234. return this.hResolution / (2 * this.vResolution);
  103235. },
  103236. enumerable: true,
  103237. configurable: true
  103238. });
  103239. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  103240. /**
  103241. * Gets the aspect ratio based on the FOV, scale factors, and real screen sizes.
  103242. */
  103243. get: function () {
  103244. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  103245. },
  103246. enumerable: true,
  103247. configurable: true
  103248. });
  103249. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  103250. /**
  103251. * @hidden
  103252. */
  103253. get: function () {
  103254. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  103255. var h = (4 * meters) / this.hScreenSize;
  103256. return BABYLON.Matrix.Translation(h, 0, 0);
  103257. },
  103258. enumerable: true,
  103259. configurable: true
  103260. });
  103261. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  103262. /**
  103263. * @hidden
  103264. */
  103265. get: function () {
  103266. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  103267. var h = (4 * meters) / this.hScreenSize;
  103268. return BABYLON.Matrix.Translation(-h, 0, 0);
  103269. },
  103270. enumerable: true,
  103271. configurable: true
  103272. });
  103273. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  103274. /**
  103275. * @hidden
  103276. */
  103277. get: function () {
  103278. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  103279. },
  103280. enumerable: true,
  103281. configurable: true
  103282. });
  103283. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  103284. /**
  103285. * @hidden
  103286. */
  103287. get: function () {
  103288. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  103289. },
  103290. enumerable: true,
  103291. configurable: true
  103292. });
  103293. /**
  103294. * Get the default VRMetrics based on the most generic setup.
  103295. * @returns the default vr metrics
  103296. */
  103297. VRCameraMetrics.GetDefault = function () {
  103298. var result = new VRCameraMetrics();
  103299. result.hResolution = 1280;
  103300. result.vResolution = 800;
  103301. result.hScreenSize = 0.149759993;
  103302. result.vScreenSize = 0.0935999975;
  103303. result.vScreenCenter = 0.0467999987;
  103304. result.eyeToScreenDistance = 0.0410000011;
  103305. result.lensSeparationDistance = 0.0635000020;
  103306. result.interpupillaryDistance = 0.0640000030;
  103307. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  103308. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  103309. result.postProcessScaleFactor = 1.714605507808412;
  103310. result.lensCenterOffset = 0.151976421;
  103311. return result;
  103312. };
  103313. return VRCameraMetrics;
  103314. }());
  103315. BABYLON.VRCameraMetrics = VRCameraMetrics;
  103316. })(BABYLON || (BABYLON = {}));
  103317. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  103318. var BABYLON;
  103319. (function (BABYLON) {
  103320. BABYLON.Node.AddNodeConstructor("WebVRFreeCamera", function (name, scene) {
  103321. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  103322. });
  103323. BABYLON.Node.AddNodeConstructor("WebVRGamepadCamera", function (name, scene) {
  103324. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  103325. });
  103326. /**
  103327. * This represents a WebVR camera.
  103328. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  103329. * @example http://doc.babylonjs.com/how_to/webvr_camera
  103330. */
  103331. var WebVRFreeCamera = /** @class */ (function (_super) {
  103332. __extends(WebVRFreeCamera, _super);
  103333. /**
  103334. * Instantiates a WebVRFreeCamera.
  103335. * @param name The name of the WebVRFreeCamera
  103336. * @param position The starting anchor position for the camera
  103337. * @param scene The scene the camera belongs to
  103338. * @param webVROptions a set of customizable options for the webVRCamera
  103339. */
  103340. function WebVRFreeCamera(name, position, scene, webVROptions) {
  103341. if (webVROptions === void 0) { webVROptions = {}; }
  103342. var _this = _super.call(this, name, position, scene) || this;
  103343. _this.webVROptions = webVROptions;
  103344. /**
  103345. * @hidden
  103346. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  103347. */
  103348. _this._vrDevice = null;
  103349. /**
  103350. * The rawPose of the vrDevice.
  103351. */
  103352. _this.rawPose = null;
  103353. _this._specsVersion = "1.1";
  103354. _this._attached = false;
  103355. _this._descendants = [];
  103356. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  103357. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  103358. /** @hidden */
  103359. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  103360. _this._standingMatrix = null;
  103361. /**
  103362. * Represents device position in babylon space.
  103363. */
  103364. _this.devicePosition = BABYLON.Vector3.Zero();
  103365. /**
  103366. * Represents device rotation in babylon space.
  103367. */
  103368. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  103369. /**
  103370. * The scale of the device to be used when translating from device space to babylon space.
  103371. */
  103372. _this.deviceScaleFactor = 1;
  103373. _this._deviceToWorld = BABYLON.Matrix.Identity();
  103374. _this._worldToDevice = BABYLON.Matrix.Identity();
  103375. /**
  103376. * References to the webVR controllers for the vrDevice.
  103377. */
  103378. _this.controllers = [];
  103379. /**
  103380. * Emits an event when a controller is attached.
  103381. */
  103382. _this.onControllersAttachedObservable = new BABYLON.Observable();
  103383. /**
  103384. * Emits an event when a controller's mesh has been loaded;
  103385. */
  103386. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  103387. /**
  103388. * Emits an event when the HMD's pose has been updated.
  103389. */
  103390. _this.onPoseUpdatedFromDeviceObservable = new BABYLON.Observable();
  103391. _this._poseSet = false;
  103392. /**
  103393. * If the rig cameras be used as parent instead of this camera.
  103394. */
  103395. _this.rigParenting = true;
  103396. _this._defaultHeight = undefined;
  103397. _this._htmlElementAttached = null;
  103398. _this._detachIfAttached = function () {
  103399. var vrDisplay = _this.getEngine().getVRDevice();
  103400. if (vrDisplay && !vrDisplay.isPresenting && _this._htmlElementAttached) {
  103401. _this.detachControl(_this._htmlElementAttached);
  103402. }
  103403. };
  103404. _this._workingVector = BABYLON.Vector3.Zero();
  103405. _this._oneVector = BABYLON.Vector3.One();
  103406. _this._workingMatrix = BABYLON.Matrix.Identity();
  103407. _this._tmpMatrix = new BABYLON.Matrix();
  103408. _this._cache.position = BABYLON.Vector3.Zero();
  103409. if (webVROptions.defaultHeight) {
  103410. _this._defaultHeight = webVROptions.defaultHeight;
  103411. _this.position.y = _this._defaultHeight;
  103412. }
  103413. _this.minZ = 0.1;
  103414. //legacy support - the compensation boolean was removed.
  103415. if (arguments.length === 5) {
  103416. _this.webVROptions = arguments[4];
  103417. }
  103418. // default webVR options
  103419. if (_this.webVROptions.trackPosition == undefined) {
  103420. _this.webVROptions.trackPosition = true;
  103421. }
  103422. if (_this.webVROptions.controllerMeshes == undefined) {
  103423. _this.webVROptions.controllerMeshes = true;
  103424. }
  103425. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  103426. _this.webVROptions.defaultLightingOnControllers = true;
  103427. }
  103428. _this.rotationQuaternion = new BABYLON.Quaternion();
  103429. if (_this.webVROptions && _this.webVROptions.positionScale) {
  103430. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  103431. }
  103432. //enable VR
  103433. var engine = _this.getEngine();
  103434. _this._onVREnabled = function (success) { if (success) {
  103435. _this.initControllers();
  103436. } };
  103437. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  103438. engine.initWebVR().add(function (event) {
  103439. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  103440. return;
  103441. }
  103442. _this._vrDevice = event.vrDisplay;
  103443. //reset the rig parameters.
  103444. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  103445. if (_this._attached) {
  103446. _this.getEngine().enableVR();
  103447. }
  103448. });
  103449. if (typeof (VRFrameData) !== "undefined")
  103450. _this._frameData = new VRFrameData();
  103451. /**
  103452. * The idea behind the following lines:
  103453. * objects that have the camera as parent should actually have the rig cameras as a parent.
  103454. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  103455. * the second will not show it correctly.
  103456. *
  103457. * To solve this - each object that has the camera as parent will be added to a protected array.
  103458. * When the rig camera renders, it will take this array and set all of those to be its children.
  103459. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  103460. * Amazing!
  103461. */
  103462. scene.onBeforeCameraRenderObservable.add(function (camera) {
  103463. if (camera.parent === _this && _this.rigParenting) {
  103464. _this._descendants = _this.getDescendants(true, function (n) {
  103465. // don't take the cameras or the controllers!
  103466. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  103467. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  103468. return !isController && !isRigCamera;
  103469. });
  103470. _this._descendants.forEach(function (node) {
  103471. node.parent = camera;
  103472. });
  103473. }
  103474. });
  103475. scene.onAfterCameraRenderObservable.add(function (camera) {
  103476. if (camera.parent === _this && _this.rigParenting) {
  103477. _this._descendants.forEach(function (node) {
  103478. node.parent = _this;
  103479. });
  103480. }
  103481. });
  103482. return _this;
  103483. }
  103484. /**
  103485. * Gets the device distance from the ground in meters.
  103486. * @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.
  103487. */
  103488. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  103489. if (this._standingMatrix) {
  103490. // Add standing matrix offset to get real offset from ground in room
  103491. this._standingMatrix.getTranslationToRef(this._workingVector);
  103492. return this._deviceRoomPosition.y + this._workingVector.y;
  103493. }
  103494. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  103495. return this._defaultHeight || 0;
  103496. };
  103497. /**
  103498. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  103499. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  103500. */
  103501. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  103502. var _this = this;
  103503. if (callback === void 0) { callback = function (bool) { }; }
  103504. // Use standing matrix if available
  103505. this.getEngine().initWebVRAsync().then(function (result) {
  103506. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform || !_this.webVROptions.trackPosition) {
  103507. callback(false);
  103508. }
  103509. else {
  103510. _this._standingMatrix = new BABYLON.Matrix();
  103511. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  103512. if (!_this.getScene().useRightHandedSystem) {
  103513. [2, 6, 8, 9, 14].forEach(function (num) {
  103514. if (_this._standingMatrix) {
  103515. _this._standingMatrix.m[num] *= -1;
  103516. }
  103517. });
  103518. }
  103519. callback(true);
  103520. }
  103521. });
  103522. };
  103523. /**
  103524. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  103525. * @returns A promise with a boolean set to if the standing matrix is supported.
  103526. */
  103527. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  103528. var _this = this;
  103529. return new Promise(function (res, rej) {
  103530. _this.useStandingMatrix(function (supported) {
  103531. res(supported);
  103532. });
  103533. });
  103534. };
  103535. /**
  103536. * Disposes the camera
  103537. */
  103538. WebVRFreeCamera.prototype.dispose = function () {
  103539. this._detachIfAttached();
  103540. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  103541. if (this._updateCacheWhenTrackingDisabledObserver) {
  103542. this._scene.onBeforeRenderObservable.remove(this._updateCacheWhenTrackingDisabledObserver);
  103543. }
  103544. _super.prototype.dispose.call(this);
  103545. };
  103546. /**
  103547. * Gets a vrController by name.
  103548. * @param name The name of the controller to retreive
  103549. * @returns the controller matching the name specified or null if not found
  103550. */
  103551. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  103552. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  103553. var gp = _a[_i];
  103554. if (gp.hand === name) {
  103555. return gp;
  103556. }
  103557. }
  103558. return null;
  103559. };
  103560. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  103561. /**
  103562. * The controller corrisponding to the users left hand.
  103563. */
  103564. get: function () {
  103565. if (!this._leftController) {
  103566. this._leftController = this.getControllerByName("left");
  103567. }
  103568. return this._leftController;
  103569. },
  103570. enumerable: true,
  103571. configurable: true
  103572. });
  103573. ;
  103574. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  103575. /**
  103576. * The controller corrisponding to the users right hand.
  103577. */
  103578. get: function () {
  103579. if (!this._rightController) {
  103580. this._rightController = this.getControllerByName("right");
  103581. }
  103582. return this._rightController;
  103583. },
  103584. enumerable: true,
  103585. configurable: true
  103586. });
  103587. ;
  103588. /**
  103589. * Casts a ray forward from the vrCamera's gaze.
  103590. * @param length Length of the ray (default: 100)
  103591. * @returns the ray corrisponding to the gaze
  103592. */
  103593. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  103594. if (length === void 0) { length = 100; }
  103595. if (this.leftCamera) {
  103596. // Use left eye to avoid computation to compute center on every call
  103597. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  103598. }
  103599. else {
  103600. return _super.prototype.getForwardRay.call(this, length);
  103601. }
  103602. };
  103603. /**
  103604. * @hidden
  103605. * Updates the camera based on device's frame data
  103606. */
  103607. WebVRFreeCamera.prototype._checkInputs = function () {
  103608. if (this._vrDevice && this._vrDevice.isPresenting) {
  103609. this._vrDevice.getFrameData(this._frameData);
  103610. this.updateFromDevice(this._frameData.pose);
  103611. }
  103612. _super.prototype._checkInputs.call(this);
  103613. };
  103614. /**
  103615. * Updates the poseControlled values based on the input device pose.
  103616. * @param poseData Pose coming from the device
  103617. */
  103618. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  103619. if (poseData && poseData.orientation) {
  103620. this.rawPose = poseData;
  103621. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  103622. if (this.getScene().useRightHandedSystem) {
  103623. this._deviceRoomRotationQuaternion.z *= -1;
  103624. this._deviceRoomRotationQuaternion.w *= -1;
  103625. }
  103626. if (this.webVROptions.trackPosition && this.rawPose.position) {
  103627. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  103628. if (this.getScene().useRightHandedSystem) {
  103629. this._deviceRoomPosition.z *= -1;
  103630. }
  103631. }
  103632. this._poseSet = true;
  103633. }
  103634. };
  103635. /**
  103636. * WebVR's attach control will start broadcasting frames to the device.
  103637. * Note that in certain browsers (chrome for example) this function must be called
  103638. * within a user-interaction callback. Example:
  103639. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  103640. *
  103641. * @param element html element to attach the vrDevice to
  103642. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  103643. */
  103644. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  103645. _super.prototype.attachControl.call(this, element, noPreventDefault);
  103646. this._attached = true;
  103647. this._htmlElementAttached = element;
  103648. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  103649. if (this._vrDevice) {
  103650. this.getEngine().enableVR();
  103651. }
  103652. window.addEventListener('vrdisplaypresentchange', this._detachIfAttached);
  103653. };
  103654. /**
  103655. * Detaches the camera from the html element and disables VR
  103656. *
  103657. * @param element html element to detach from
  103658. */
  103659. WebVRFreeCamera.prototype.detachControl = function (element) {
  103660. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  103661. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  103662. _super.prototype.detachControl.call(this, element);
  103663. this._attached = false;
  103664. this.getEngine().disableVR();
  103665. window.removeEventListener('vrdisplaypresentchange', this._detachIfAttached);
  103666. };
  103667. /**
  103668. * @returns the name of this class
  103669. */
  103670. WebVRFreeCamera.prototype.getClassName = function () {
  103671. return "WebVRFreeCamera";
  103672. };
  103673. /**
  103674. * Calls resetPose on the vrDisplay
  103675. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  103676. */
  103677. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  103678. //uses the vrDisplay's "resetPose()".
  103679. //pitch and roll won't be affected.
  103680. this._vrDevice.resetPose();
  103681. };
  103682. /**
  103683. * @hidden
  103684. * Updates the rig cameras (left and right eye)
  103685. */
  103686. WebVRFreeCamera.prototype._updateRigCameras = function () {
  103687. var camLeft = this._rigCameras[0];
  103688. var camRight = this._rigCameras[1];
  103689. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  103690. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  103691. camLeft.position.copyFrom(this._deviceRoomPosition);
  103692. camRight.position.copyFrom(this._deviceRoomPosition);
  103693. };
  103694. // Remove translation from 6dof headset if trackposition is set to false
  103695. WebVRFreeCamera.prototype._correctPositionIfNotTrackPosition = function (matrix, isViewMatrix) {
  103696. if (isViewMatrix === void 0) { isViewMatrix = false; }
  103697. if (this.rawPose && this.rawPose.position && !this.webVROptions.trackPosition) {
  103698. BABYLON.Matrix.TranslationToRef(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2], this._tmpMatrix);
  103699. if (!isViewMatrix) {
  103700. this._tmpMatrix.invert();
  103701. }
  103702. this._tmpMatrix.multiplyToRef(matrix, matrix);
  103703. }
  103704. };
  103705. /**
  103706. * @hidden
  103707. * Updates the cached values of the camera
  103708. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  103709. */
  103710. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  103711. var _this = this;
  103712. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  103713. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  103714. if (!this.updateCacheCalled) {
  103715. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  103716. this.updateCacheCalled = true;
  103717. this.update();
  103718. }
  103719. // Set working vector to the device position in room space rotated by the new rotation
  103720. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  103721. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  103722. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  103723. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  103724. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  103725. // Add translation from anchor position
  103726. this._deviceToWorld.getTranslationToRef(this._workingVector);
  103727. this._workingVector.addInPlace(this.position);
  103728. this._workingVector.subtractInPlace(this._cache.position);
  103729. this._deviceToWorld.setTranslation(this._workingVector);
  103730. // Set an inverted matrix to be used when updating the camera
  103731. this._deviceToWorld.invertToRef(this._worldToDevice);
  103732. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  103733. this.controllers.forEach(function (controller) {
  103734. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  103735. _this._correctPositionIfNotTrackPosition(controller._deviceToWorld);
  103736. controller.update();
  103737. });
  103738. }
  103739. if (!ignoreParentClass) {
  103740. _super.prototype._updateCache.call(this);
  103741. }
  103742. this.updateCacheCalled = false;
  103743. };
  103744. /**
  103745. * @hidden
  103746. * Get current device position in babylon world
  103747. */
  103748. WebVRFreeCamera.prototype._computeDevicePosition = function () {
  103749. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  103750. };
  103751. /**
  103752. * Updates the current device position and rotation in the babylon world
  103753. */
  103754. WebVRFreeCamera.prototype.update = function () {
  103755. this._computeDevicePosition();
  103756. // Get current device rotation in babylon world
  103757. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  103758. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  103759. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  103760. if (this._poseSet) {
  103761. this.onPoseUpdatedFromDeviceObservable.notifyObservers(null);
  103762. }
  103763. _super.prototype.update.call(this);
  103764. };
  103765. /**
  103766. * @hidden
  103767. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  103768. * @returns an identity matrix
  103769. */
  103770. WebVRFreeCamera.prototype._getViewMatrix = function () {
  103771. return BABYLON.Matrix.Identity();
  103772. };
  103773. /**
  103774. * This function is called by the two RIG cameras.
  103775. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  103776. */
  103777. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  103778. var _this = this;
  103779. // Update the parent camera prior to using a child camera to avoid desynchronization
  103780. var parentCamera = this._cameraRigParams["parentCamera"];
  103781. parentCamera._updateCache();
  103782. //WebVR 1.1
  103783. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  103784. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  103785. if (!this.getScene().useRightHandedSystem) {
  103786. [2, 6, 8, 9, 14].forEach(function (num) {
  103787. _this._webvrViewMatrix.m[num] *= -1;
  103788. });
  103789. }
  103790. // update the camera rotation matrix
  103791. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  103792. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  103793. // Computing target and final matrix
  103794. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  103795. // should the view matrix be updated with scale and position offset?
  103796. if (parentCamera.deviceScaleFactor !== 1) {
  103797. this._webvrViewMatrix.invert();
  103798. // scale the position, if set
  103799. if (parentCamera.deviceScaleFactor) {
  103800. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  103801. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  103802. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  103803. }
  103804. this._webvrViewMatrix.invert();
  103805. }
  103806. // Remove translation from 6dof headset if trackposition is set to false
  103807. parentCamera._correctPositionIfNotTrackPosition(this._webvrViewMatrix, true);
  103808. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  103809. // Compute global position
  103810. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  103811. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  103812. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  103813. this._workingMatrix.getTranslationToRef(this._globalPosition);
  103814. this._markSyncedWithParent();
  103815. return this._webvrViewMatrix;
  103816. };
  103817. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  103818. var _this = this;
  103819. var parentCamera = this.parent;
  103820. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  103821. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  103822. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  103823. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  103824. //babylon compatible matrix
  103825. if (!this.getScene().useRightHandedSystem) {
  103826. [8, 9, 10, 11].forEach(function (num) {
  103827. _this._projectionMatrix.m[num] *= -1;
  103828. });
  103829. }
  103830. return this._projectionMatrix;
  103831. };
  103832. /**
  103833. * Initializes the controllers and their meshes
  103834. */
  103835. WebVRFreeCamera.prototype.initControllers = function () {
  103836. var _this = this;
  103837. this.controllers = [];
  103838. var manager = this.getScene().gamepadManager;
  103839. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  103840. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  103841. var webVrController = gamepad;
  103842. if (webVrController.defaultModel) {
  103843. webVrController.defaultModel.setEnabled(false);
  103844. }
  103845. if (webVrController.hand === "right") {
  103846. _this._rightController = null;
  103847. }
  103848. if (webVrController.hand === "left") {
  103849. _this._leftController = null;
  103850. }
  103851. var controllerIndex = _this.controllers.indexOf(webVrController);
  103852. if (controllerIndex !== -1) {
  103853. _this.controllers.splice(controllerIndex, 1);
  103854. }
  103855. }
  103856. });
  103857. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  103858. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  103859. var webVrController_1 = gamepad;
  103860. if (!_this.webVROptions.trackPosition) {
  103861. webVrController_1._disableTrackPosition(new BABYLON.Vector3(webVrController_1.hand == "left" ? -0.15 : 0.15, -0.5, 0.25));
  103862. // Cache must be updated before rendering controllers to avoid them being one frame behind
  103863. if (!_this._updateCacheWhenTrackingDisabledObserver) {
  103864. _this._updateCacheWhenTrackingDisabledObserver = _this._scene.onBeforeRenderObservable.add(function () {
  103865. _this._updateCache();
  103866. });
  103867. }
  103868. }
  103869. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  103870. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  103871. _this._correctPositionIfNotTrackPosition(webVrController_1._deviceToWorld);
  103872. if (_this.webVROptions.controllerMeshes) {
  103873. if (webVrController_1.defaultModel) {
  103874. webVrController_1.defaultModel.setEnabled(true);
  103875. }
  103876. else {
  103877. // Load the meshes
  103878. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  103879. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  103880. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  103881. if (_this.webVROptions.defaultLightingOnControllers) {
  103882. if (!_this._lightOnControllers) {
  103883. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  103884. }
  103885. var activateLightOnSubMeshes_1 = function (mesh, light) {
  103886. var children = mesh.getChildren();
  103887. if (children && children.length !== 0) {
  103888. children.forEach(function (mesh) {
  103889. light.includedOnlyMeshes.push(mesh);
  103890. activateLightOnSubMeshes_1(mesh, light);
  103891. });
  103892. }
  103893. };
  103894. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  103895. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  103896. }
  103897. });
  103898. }
  103899. }
  103900. webVrController_1.attachToPoseControlledCamera(_this);
  103901. // since this is async - sanity check. Is the controller already stored?
  103902. if (_this.controllers.indexOf(webVrController_1) === -1) {
  103903. //add to the controllers array
  103904. _this.controllers.push(webVrController_1);
  103905. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  103906. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  103907. // So we're overriding setting left & right manually to be sure
  103908. var firstViveWandDetected = false;
  103909. for (var i = 0; i < _this.controllers.length; i++) {
  103910. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  103911. if (!firstViveWandDetected) {
  103912. firstViveWandDetected = true;
  103913. _this.controllers[i].hand = "left";
  103914. }
  103915. else {
  103916. _this.controllers[i].hand = "right";
  103917. }
  103918. }
  103919. }
  103920. //did we find enough controllers? Great! let the developer know.
  103921. if (_this.controllers.length >= 2) {
  103922. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  103923. }
  103924. }
  103925. }
  103926. });
  103927. };
  103928. return WebVRFreeCamera;
  103929. }(BABYLON.FreeCamera));
  103930. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  103931. })(BABYLON || (BABYLON = {}));
  103932. //# sourceMappingURL=babylon.webVRCamera.js.map
  103933. var BABYLON;
  103934. (function (BABYLON) {
  103935. BABYLON.Node.AddNodeConstructor("DeviceOrientationCamera", function (name, scene) {
  103936. return function () { return new DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  103937. });
  103938. // We're mainly based on the logic defined into the FreeCamera code
  103939. /**
  103940. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  103941. * being tilted forward or back and left or right.
  103942. */
  103943. var DeviceOrientationCamera = /** @class */ (function (_super) {
  103944. __extends(DeviceOrientationCamera, _super);
  103945. /**
  103946. * Creates a new device orientation camera
  103947. * @param name The name of the camera
  103948. * @param position The start position camera
  103949. * @param scene The scene the camera belongs to
  103950. */
  103951. function DeviceOrientationCamera(name, position, scene) {
  103952. var _this = _super.call(this, name, position, scene) || this;
  103953. _this._quaternionCache = new BABYLON.Quaternion();
  103954. _this.inputs.addDeviceOrientation();
  103955. return _this;
  103956. }
  103957. /**
  103958. * Gets the current instance class name ("DeviceOrientationCamera").
  103959. * This helps avoiding instanceof at run time.
  103960. * @returns the class name
  103961. */
  103962. DeviceOrientationCamera.prototype.getClassName = function () {
  103963. return "DeviceOrientationCamera";
  103964. };
  103965. /**
  103966. * @hidden
  103967. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  103968. */
  103969. DeviceOrientationCamera.prototype._checkInputs = function () {
  103970. _super.prototype._checkInputs.call(this);
  103971. this._quaternionCache.copyFrom(this.rotationQuaternion);
  103972. if (this._initialQuaternion) {
  103973. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  103974. }
  103975. };
  103976. /**
  103977. * Reset the camera to its default orientation on the specified axis only.
  103978. * @param axis The axis to reset
  103979. */
  103980. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  103981. var _this = this;
  103982. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  103983. //can only work if this camera has a rotation quaternion already.
  103984. if (!this.rotationQuaternion)
  103985. return;
  103986. if (!this._initialQuaternion) {
  103987. this._initialQuaternion = new BABYLON.Quaternion();
  103988. }
  103989. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  103990. ['x', 'y', 'z'].forEach(function (axisName) {
  103991. if (!axis[axisName]) {
  103992. _this._initialQuaternion[axisName] = 0;
  103993. }
  103994. else {
  103995. _this._initialQuaternion[axisName] *= -1;
  103996. }
  103997. });
  103998. this._initialQuaternion.normalize();
  103999. //force rotation update
  104000. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  104001. };
  104002. return DeviceOrientationCamera;
  104003. }(BABYLON.FreeCamera));
  104004. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  104005. })(BABYLON || (BABYLON = {}));
  104006. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  104007. var BABYLON;
  104008. (function (BABYLON) {
  104009. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  104010. return function () { return new VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  104011. });
  104012. /**
  104013. * Camera used to simulate VR rendering (based on FreeCamera)
  104014. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  104015. */
  104016. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  104017. __extends(VRDeviceOrientationFreeCamera, _super);
  104018. /**
  104019. * Creates a new VRDeviceOrientationFreeCamera
  104020. * @param name defines camera name
  104021. * @param position defines the start position of the camera
  104022. * @param scene defines the scene the camera belongs to
  104023. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  104024. * @param vrCameraMetrics defines the vr metrics associated to the camera
  104025. */
  104026. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  104027. if (compensateDistortion === void 0) { compensateDistortion = true; }
  104028. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  104029. var _this = _super.call(this, name, position, scene) || this;
  104030. vrCameraMetrics.compensateDistortion = compensateDistortion;
  104031. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  104032. return _this;
  104033. }
  104034. /**
  104035. * Gets camera class name
  104036. * @returns VRDeviceOrientationFreeCamera
  104037. */
  104038. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  104039. return "VRDeviceOrientationFreeCamera";
  104040. };
  104041. return VRDeviceOrientationFreeCamera;
  104042. }(BABYLON.DeviceOrientationCamera));
  104043. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  104044. })(BABYLON || (BABYLON = {}));
  104045. //# sourceMappingURL=babylon.vrDeviceOrientationFreeCamera.js.map
  104046. var BABYLON;
  104047. (function (BABYLON) {
  104048. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  104049. return function () { return new VRDeviceOrientationArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  104050. });
  104051. /**
  104052. * Camera used to simulate VR rendering (based on ArcRotateCamera)
  104053. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  104054. */
  104055. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  104056. __extends(VRDeviceOrientationArcRotateCamera, _super);
  104057. /**
  104058. * Creates a new VRDeviceOrientationArcRotateCamera
  104059. * @param name defines camera name
  104060. * @param alpha defines the camera rotation along the logitudinal axis
  104061. * @param beta defines the camera rotation along the latitudinal axis
  104062. * @param radius defines the camera distance from its target
  104063. * @param target defines the camera target
  104064. * @param scene defines the scene the camera belongs to
  104065. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  104066. * @param vrCameraMetrics defines the vr metrics associated to the camera
  104067. */
  104068. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  104069. if (compensateDistortion === void 0) { compensateDistortion = true; }
  104070. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  104071. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  104072. vrCameraMetrics.compensateDistortion = compensateDistortion;
  104073. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  104074. _this.inputs.addVRDeviceOrientation();
  104075. return _this;
  104076. }
  104077. /**
  104078. * Gets camera class name
  104079. * @returns VRDeviceOrientationArcRotateCamera
  104080. */
  104081. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  104082. return "VRDeviceOrientationArcRotateCamera";
  104083. };
  104084. return VRDeviceOrientationArcRotateCamera;
  104085. }(BABYLON.ArcRotateCamera));
  104086. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  104087. })(BABYLON || (BABYLON = {}));
  104088. //# sourceMappingURL=babylon.vrDeviceOrientationArcRotateCamera.js.map
  104089. var BABYLON;
  104090. (function (BABYLON) {
  104091. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationGamepadCamera", function (name, scene) {
  104092. return function () { return new VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  104093. });
  104094. /**
  104095. * Camera used to simulate VR rendering (based on VRDeviceOrientationFreeCamera)
  104096. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  104097. */
  104098. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  104099. __extends(VRDeviceOrientationGamepadCamera, _super);
  104100. /**
  104101. * Creates a new VRDeviceOrientationGamepadCamera
  104102. * @param name defines camera name
  104103. * @param position defines the start position of the camera
  104104. * @param scene defines the scene the camera belongs to
  104105. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  104106. * @param vrCameraMetrics defines the vr metrics associated to the camera
  104107. */
  104108. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  104109. if (compensateDistortion === void 0) { compensateDistortion = true; }
  104110. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  104111. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  104112. _this.inputs.addGamepad();
  104113. return _this;
  104114. }
  104115. /**
  104116. * Gets camera class name
  104117. * @returns VRDeviceOrientationGamepadCamera
  104118. */
  104119. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  104120. return "VRDeviceOrientationGamepadCamera";
  104121. };
  104122. return VRDeviceOrientationGamepadCamera;
  104123. }(BABYLON.VRDeviceOrientationFreeCamera));
  104124. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  104125. })(BABYLON || (BABYLON = {}));
  104126. //# sourceMappingURL=babylon.vrDeviceOrientationGamepadCamera.js.map
  104127. var BABYLON;
  104128. (function (BABYLON) {
  104129. var VRExperienceHelperGazer = /** @class */ (function () {
  104130. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  104131. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  104132. this.scene = scene;
  104133. /** @hidden */
  104134. this._pointerDownOnMeshAsked = false;
  104135. /** @hidden */
  104136. this._isActionableMesh = false;
  104137. /** @hidden */
  104138. this._teleportationRequestInitiated = false;
  104139. /** @hidden */
  104140. this._teleportationBackRequestInitiated = false;
  104141. /** @hidden */
  104142. this._rotationRightAsked = false;
  104143. /** @hidden */
  104144. this._rotationLeftAsked = false;
  104145. /** @hidden */
  104146. this._dpadPressed = true;
  104147. /** @hidden */
  104148. this._activePointer = false;
  104149. this._id = VRExperienceHelperGazer._idCounter++;
  104150. // Gaze tracker
  104151. if (!gazeTrackerToClone) {
  104152. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  104153. this._gazeTracker.bakeCurrentTransformIntoVertices();
  104154. this._gazeTracker.isPickable = false;
  104155. this._gazeTracker.isVisible = false;
  104156. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  104157. targetMat.specularColor = BABYLON.Color3.Black();
  104158. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  104159. targetMat.backFaceCulling = false;
  104160. this._gazeTracker.material = targetMat;
  104161. }
  104162. else {
  104163. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  104164. }
  104165. }
  104166. /** @hidden */
  104167. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  104168. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  104169. };
  104170. /** @hidden */
  104171. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  104172. this._pointerDownOnMeshAsked = true;
  104173. if (this._currentHit) {
  104174. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  104175. }
  104176. };
  104177. /** @hidden */
  104178. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  104179. if (this._currentHit) {
  104180. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  104181. }
  104182. this._pointerDownOnMeshAsked = false;
  104183. };
  104184. /** @hidden */
  104185. VRExperienceHelperGazer.prototype._activatePointer = function () {
  104186. this._activePointer = true;
  104187. };
  104188. /** @hidden */
  104189. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  104190. this._activePointer = false;
  104191. };
  104192. /** @hidden */
  104193. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  104194. if (distance === void 0) { distance = 100; }
  104195. };
  104196. VRExperienceHelperGazer.prototype.dispose = function () {
  104197. this._interactionsEnabled = false;
  104198. this._teleportationEnabled = false;
  104199. if (this._gazeTracker) {
  104200. this._gazeTracker.dispose();
  104201. }
  104202. };
  104203. VRExperienceHelperGazer._idCounter = 0;
  104204. return VRExperienceHelperGazer;
  104205. }());
  104206. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  104207. __extends(VRExperienceHelperControllerGazer, _super);
  104208. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  104209. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  104210. _this.webVRController = webVRController;
  104211. // Laser pointer
  104212. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  104213. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  104214. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  104215. laserPointerMaterial.alpha = 0.6;
  104216. _this._laserPointer.material = laserPointerMaterial;
  104217. _this._laserPointer.rotation.x = Math.PI / 2;
  104218. _this._laserPointer.position.z = -0.5;
  104219. _this._laserPointer.isVisible = false;
  104220. _this._laserPointer.isPickable = false;
  104221. if (!webVRController.mesh) {
  104222. // Create an empty mesh that is used prior to loading the high quality model
  104223. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  104224. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  104225. preloadPointerPose.rotation.x = -0.7;
  104226. preloadMesh.addChild(preloadPointerPose);
  104227. webVRController.attachToMesh(preloadMesh);
  104228. }
  104229. _this._setLaserPointerParent(webVRController.mesh);
  104230. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  104231. _this._setLaserPointerParent(mesh);
  104232. });
  104233. return _this;
  104234. }
  104235. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  104236. return this.webVRController.getForwardRay(length);
  104237. };
  104238. /** @hidden */
  104239. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  104240. _super.prototype._activatePointer.call(this);
  104241. this._laserPointer.isVisible = true;
  104242. };
  104243. /** @hidden */
  104244. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  104245. _super.prototype._deactivatePointer.call(this);
  104246. this._laserPointer.isVisible = false;
  104247. };
  104248. /** @hidden */
  104249. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  104250. this._laserPointer.material.emissiveColor = color;
  104251. };
  104252. /** @hidden */
  104253. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  104254. var makeNotPick = function (root) {
  104255. root.isPickable = false;
  104256. root.getChildMeshes().forEach(function (c) {
  104257. makeNotPick(c);
  104258. });
  104259. };
  104260. makeNotPick(mesh);
  104261. var childMeshes = mesh.getChildMeshes();
  104262. this.webVRController._pointingPoseNode = null;
  104263. for (var i = 0; i < childMeshes.length; i++) {
  104264. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  104265. mesh = childMeshes[i];
  104266. this.webVRController._pointingPoseNode = mesh;
  104267. break;
  104268. }
  104269. }
  104270. this._laserPointer.parent = mesh;
  104271. };
  104272. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  104273. if (distance === void 0) { distance = 100; }
  104274. this._laserPointer.scaling.y = distance;
  104275. this._laserPointer.position.z = -distance / 2;
  104276. };
  104277. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  104278. _super.prototype.dispose.call(this);
  104279. this._laserPointer.dispose();
  104280. if (this._meshAttachedObserver) {
  104281. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  104282. }
  104283. };
  104284. return VRExperienceHelperControllerGazer;
  104285. }(VRExperienceHelperGazer));
  104286. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  104287. __extends(VRExperienceHelperCameraGazer, _super);
  104288. function VRExperienceHelperCameraGazer(getCamera, scene) {
  104289. var _this = _super.call(this, scene) || this;
  104290. _this.getCamera = getCamera;
  104291. return _this;
  104292. }
  104293. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  104294. var camera = this.getCamera();
  104295. if (camera) {
  104296. return camera.getForwardRay(length);
  104297. }
  104298. else {
  104299. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  104300. }
  104301. };
  104302. return VRExperienceHelperCameraGazer;
  104303. }(VRExperienceHelperGazer));
  104304. /**
  104305. * Helps to quickly add VR support to an existing scene.
  104306. * See http://doc.babylonjs.com/how_to/webvr_helper
  104307. */
  104308. var VRExperienceHelper = /** @class */ (function () {
  104309. /**
  104310. * Instantiates a VRExperienceHelper.
  104311. * Helps to quickly add VR support to an existing scene.
  104312. * @param scene The scene the VRExperienceHelper belongs to.
  104313. * @param webVROptions Options to modify the vr experience helper's behavior.
  104314. */
  104315. function VRExperienceHelper(scene,
  104316. /** Options to modify the vr experience helper's behavior. */
  104317. webVROptions) {
  104318. if (webVROptions === void 0) { webVROptions = {}; }
  104319. var _this = this;
  104320. this.webVROptions = webVROptions;
  104321. // Can the system support WebVR, even if a headset isn't plugged in?
  104322. this._webVRsupported = false;
  104323. // If WebVR is supported, is a headset plugged in and are we ready to present?
  104324. this._webVRready = false;
  104325. // Are we waiting for the requestPresent callback to complete?
  104326. this._webVRrequesting = false;
  104327. // Are we presenting to the headset right now? (this is the vrDevice state)
  104328. this._webVRpresenting = false;
  104329. // Are we presenting in the fullscreen fallback?
  104330. this._fullscreenVRpresenting = false;
  104331. /**
  104332. * Observable raised when entering VR.
  104333. */
  104334. this.onEnteringVRObservable = new BABYLON.Observable();
  104335. /**
  104336. * Observable raised when exiting VR.
  104337. */
  104338. this.onExitingVRObservable = new BABYLON.Observable();
  104339. /**
  104340. * Observable raised when controller mesh is loaded.
  104341. */
  104342. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  104343. this._useCustomVRButton = false;
  104344. this._teleportationRequested = false;
  104345. this._teleportActive = false;
  104346. this._floorMeshesCollection = [];
  104347. this._rotationAllowed = true;
  104348. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  104349. this._isDefaultTeleportationTarget = true;
  104350. this._teleportationFillColor = "#444444";
  104351. this._teleportationBorderColor = "#FFFFFF";
  104352. this._rotationAngle = 0;
  104353. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  104354. this._padSensibilityUp = 0.65;
  104355. this._padSensibilityDown = 0.35;
  104356. this._leftController = null;
  104357. this._rightController = null;
  104358. /**
  104359. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  104360. */
  104361. this.onNewMeshSelected = new BABYLON.Observable();
  104362. /**
  104363. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  104364. */
  104365. this.onNewMeshPicked = new BABYLON.Observable();
  104366. /**
  104367. * Observable raised before camera teleportation
  104368. */
  104369. this.onBeforeCameraTeleport = new BABYLON.Observable();
  104370. /**
  104371. * Observable raised after camera teleportation
  104372. */
  104373. this.onAfterCameraTeleport = new BABYLON.Observable();
  104374. /**
  104375. * Observable raised when current selected mesh gets unselected
  104376. */
  104377. this.onSelectedMeshUnselected = new BABYLON.Observable();
  104378. /**
  104379. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  104380. */
  104381. this.teleportationEnabled = true;
  104382. this._teleportationInitialized = false;
  104383. this._interactionsEnabled = false;
  104384. this._interactionsRequested = false;
  104385. this._displayGaze = true;
  104386. this._displayLaserPointer = true;
  104387. /**
  104388. * If the gaze trackers scale should be updated to be constant size when pointing at near/far meshes
  104389. */
  104390. this.updateGazeTrackerScale = true;
  104391. this._onResize = function () {
  104392. _this.moveButtonToBottomRight();
  104393. if (_this._fullscreenVRpresenting && _this._webVRready) {
  104394. _this.exitVR();
  104395. }
  104396. };
  104397. this._onFullscreenChange = function () {
  104398. if (document.fullscreen !== undefined) {
  104399. _this._fullscreenVRpresenting = document.fullscreen;
  104400. }
  104401. else if (document.mozFullScreen !== undefined) {
  104402. _this._fullscreenVRpresenting = document.mozFullScreen;
  104403. }
  104404. else if (document.webkitIsFullScreen !== undefined) {
  104405. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  104406. }
  104407. else if (document.msIsFullScreen !== undefined) {
  104408. _this._fullscreenVRpresenting = document.msIsFullScreen;
  104409. }
  104410. else if (document.msFullscreenElement !== undefined) {
  104411. _this._fullscreenVRpresenting = document.msFullscreenElement;
  104412. }
  104413. if (!_this._fullscreenVRpresenting && _this._canvas) {
  104414. _this.exitVR();
  104415. if (!_this._useCustomVRButton) {
  104416. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  104417. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  104418. }
  104419. }
  104420. };
  104421. this.beforeRender = function () {
  104422. if (_this._leftController && _this._leftController._activePointer) {
  104423. _this._castRayAndSelectObject(_this._leftController);
  104424. }
  104425. if (_this._rightController && _this._rightController._activePointer) {
  104426. _this._castRayAndSelectObject(_this._rightController);
  104427. }
  104428. if (_this._noControllerIsActive) {
  104429. _this._castRayAndSelectObject(_this._cameraGazer);
  104430. }
  104431. else {
  104432. _this._cameraGazer._gazeTracker.isVisible = false;
  104433. }
  104434. };
  104435. this._onNewGamepadConnected = function (gamepad) {
  104436. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  104437. if (gamepad.leftStick) {
  104438. gamepad.onleftstickchanged(function (stickValues) {
  104439. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  104440. // Listening to classic/xbox gamepad only if no VR controller is active
  104441. if ((!_this._leftController && !_this._rightController) ||
  104442. ((_this._leftController && !_this._leftController._activePointer) &&
  104443. (_this._rightController && !_this._rightController._activePointer))) {
  104444. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  104445. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  104446. }
  104447. }
  104448. });
  104449. }
  104450. if (gamepad.rightStick) {
  104451. gamepad.onrightstickchanged(function (stickValues) {
  104452. if (_this._teleportationInitialized) {
  104453. _this._checkRotate(stickValues, _this._cameraGazer);
  104454. }
  104455. });
  104456. }
  104457. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  104458. gamepad.onbuttondown(function (buttonPressed) {
  104459. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  104460. _this._cameraGazer._selectionPointerDown();
  104461. }
  104462. });
  104463. gamepad.onbuttonup(function (buttonPressed) {
  104464. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  104465. _this._cameraGazer._selectionPointerUp();
  104466. }
  104467. });
  104468. }
  104469. }
  104470. else {
  104471. var webVRController = gamepad;
  104472. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  104473. if (webVRController.hand === "right" || (_this._leftController && _this._leftController.webVRController != webVRController)) {
  104474. _this._rightController = controller;
  104475. }
  104476. else {
  104477. _this._leftController = controller;
  104478. }
  104479. _this._tryEnableInteractionOnController(controller);
  104480. }
  104481. };
  104482. // 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
  104483. this._tryEnableInteractionOnController = function (controller) {
  104484. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  104485. _this._enableInteractionOnController(controller);
  104486. }
  104487. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  104488. _this._enableTeleportationOnController(controller);
  104489. }
  104490. };
  104491. this._onNewGamepadDisconnected = function (gamepad) {
  104492. if (gamepad instanceof BABYLON.WebVRController) {
  104493. if (gamepad.hand === "left" && _this._leftController != null) {
  104494. _this._leftController.dispose();
  104495. _this._leftController = null;
  104496. }
  104497. if (gamepad.hand === "right" && _this._rightController != null) {
  104498. _this._rightController.dispose();
  104499. _this._rightController = null;
  104500. }
  104501. }
  104502. };
  104503. this._workingVector = BABYLON.Vector3.Zero();
  104504. this._workingQuaternion = BABYLON.Quaternion.Identity();
  104505. this._workingMatrix = BABYLON.Matrix.Identity();
  104506. this._scene = scene;
  104507. this._canvas = scene.getEngine().getRenderingCanvas();
  104508. // Parse options
  104509. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  104510. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  104511. }
  104512. if (webVROptions.createDeviceOrientationCamera === undefined) {
  104513. webVROptions.createDeviceOrientationCamera = true;
  104514. }
  104515. if (webVROptions.laserToggle === undefined) {
  104516. webVROptions.laserToggle = true;
  104517. }
  104518. if (webVROptions.defaultHeight === undefined) {
  104519. webVROptions.defaultHeight = 1.7;
  104520. }
  104521. if (webVROptions.useCustomVRButton) {
  104522. this._useCustomVRButton = true;
  104523. if (webVROptions.customVRButton) {
  104524. this._btnVR = webVROptions.customVRButton;
  104525. }
  104526. }
  104527. if (webVROptions.rayLength) {
  104528. this._rayLength = webVROptions.rayLength;
  104529. }
  104530. this._defaultHeight = webVROptions.defaultHeight;
  104531. if (webVROptions.positionScale) {
  104532. this._rayLength *= webVROptions.positionScale;
  104533. this._defaultHeight *= webVROptions.positionScale;
  104534. }
  104535. this._hasEnteredVR = false;
  104536. // Set position
  104537. if (this._scene.activeCamera) {
  104538. this._position = this._scene.activeCamera.position.clone();
  104539. }
  104540. else {
  104541. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  104542. }
  104543. // Set non-vr camera
  104544. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  104545. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  104546. // Copy data from existing camera
  104547. if (this._scene.activeCamera) {
  104548. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  104549. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  104550. // Set rotation from previous camera
  104551. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  104552. var targetCamera = this._scene.activeCamera;
  104553. if (targetCamera.rotationQuaternion) {
  104554. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  104555. }
  104556. else {
  104557. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  104558. }
  104559. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  104560. }
  104561. }
  104562. this._scene.activeCamera = this._deviceOrientationCamera;
  104563. if (this._canvas) {
  104564. this._scene.activeCamera.attachControl(this._canvas);
  104565. }
  104566. }
  104567. else {
  104568. this._existingCamera = this._scene.activeCamera;
  104569. }
  104570. // Create VR cameras
  104571. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  104572. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  104573. }
  104574. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  104575. this._webVRCamera.useStandingMatrix();
  104576. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  104577. // Create default button
  104578. if (!this._useCustomVRButton) {
  104579. this._btnVR = document.createElement("BUTTON");
  104580. this._btnVR.className = "babylonVRicon";
  104581. this._btnVR.id = "babylonVRiconbtn";
  104582. this._btnVR.title = "Click to switch to VR";
  104583. 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) }";
  104584. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  104585. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  104586. // css += ".babylonVRicon.vrdisplaysupported { }";
  104587. // css += ".babylonVRicon.vrdisplayready { }";
  104588. // css += ".babylonVRicon.vrdisplayrequesting { }";
  104589. var style = document.createElement('style');
  104590. style.appendChild(document.createTextNode(css));
  104591. document.getElementsByTagName('head')[0].appendChild(style);
  104592. this.moveButtonToBottomRight();
  104593. }
  104594. // VR button click event
  104595. if (this._btnVR) {
  104596. this._btnVR.addEventListener("click", function () {
  104597. if (!_this.isInVRMode) {
  104598. _this.enterVR();
  104599. }
  104600. else {
  104601. _this.exitVR();
  104602. }
  104603. });
  104604. }
  104605. // Window events
  104606. window.addEventListener("resize", this._onResize);
  104607. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  104608. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  104609. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  104610. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  104611. document.onmsfullscreenchange = this._onFullscreenChange;
  104612. // Display vr button when headset is connected
  104613. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  104614. this.displayVRButton();
  104615. }
  104616. else {
  104617. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  104618. if (e.vrDisplay) {
  104619. _this.displayVRButton();
  104620. }
  104621. });
  104622. }
  104623. // Exiting VR mode using 'ESC' key on desktop
  104624. this._onKeyDown = function (event) {
  104625. if (event.keyCode === 27 && _this.isInVRMode) {
  104626. _this.exitVR();
  104627. }
  104628. };
  104629. document.addEventListener("keydown", this._onKeyDown);
  104630. // Exiting VR mode double tapping the touch screen
  104631. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  104632. if (_this.isInVRMode) {
  104633. _this.exitVR();
  104634. if (_this._fullscreenVRpresenting) {
  104635. _this._scene.getEngine().switchFullscreen(true);
  104636. }
  104637. }
  104638. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  104639. // Listen for WebVR display changes
  104640. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  104641. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  104642. this._onVRRequestPresentStart = function () {
  104643. _this._webVRrequesting = true;
  104644. _this.updateButtonVisibility();
  104645. };
  104646. this._onVRRequestPresentComplete = function (success) {
  104647. _this._webVRrequesting = false;
  104648. _this.updateButtonVisibility();
  104649. };
  104650. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  104651. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  104652. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  104653. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  104654. scene.onDisposeObservable.add(function () {
  104655. _this.dispose();
  104656. });
  104657. // Gamepad connection events
  104658. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  104659. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  104660. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  104661. this.updateButtonVisibility();
  104662. //create easing functions
  104663. this._circleEase = new BABYLON.CircleEase();
  104664. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  104665. if (this.webVROptions.floorMeshes) {
  104666. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  104667. }
  104668. }
  104669. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  104670. /** Return this.onEnteringVRObservable
  104671. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  104672. */
  104673. get: function () {
  104674. return this.onEnteringVRObservable;
  104675. },
  104676. enumerable: true,
  104677. configurable: true
  104678. });
  104679. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  104680. /** Return this.onExitingVRObservable
  104681. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  104682. */
  104683. get: function () {
  104684. return this.onExitingVRObservable;
  104685. },
  104686. enumerable: true,
  104687. configurable: true
  104688. });
  104689. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  104690. /** Return this.onControllerMeshLoadedObservable
  104691. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  104692. */
  104693. get: function () {
  104694. return this.onControllerMeshLoadedObservable;
  104695. },
  104696. enumerable: true,
  104697. configurable: true
  104698. });
  104699. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  104700. /**
  104701. * The mesh used to display where the user is going to teleport.
  104702. */
  104703. get: function () {
  104704. return this._teleportationTarget;
  104705. },
  104706. /**
  104707. * Sets the mesh to be used to display where the user is going to teleport.
  104708. */
  104709. set: function (value) {
  104710. if (value) {
  104711. value.name = "teleportationTarget";
  104712. this._isDefaultTeleportationTarget = false;
  104713. this._teleportationTarget = value;
  104714. }
  104715. },
  104716. enumerable: true,
  104717. configurable: true
  104718. });
  104719. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  104720. /**
  104721. * The mesh used to display where the user is selecting, this mesh will be cloned and set as the gazeTracker for the left and right controller
  104722. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  104723. * See http://doc.babylonjs.com/resources/baking_transformations
  104724. */
  104725. get: function () {
  104726. return this._cameraGazer._gazeTracker;
  104727. },
  104728. set: function (value) {
  104729. if (value) {
  104730. // Dispose of existing meshes
  104731. if (this._cameraGazer._gazeTracker) {
  104732. this._cameraGazer._gazeTracker.dispose();
  104733. }
  104734. if (this._leftController && this._leftController._gazeTracker) {
  104735. this._leftController._gazeTracker.dispose();
  104736. }
  104737. if (this._rightController && this._rightController._gazeTracker) {
  104738. this._rightController._gazeTracker.dispose();
  104739. }
  104740. // Set and create gaze trackers on head and controllers
  104741. this._cameraGazer._gazeTracker = value;
  104742. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  104743. this._cameraGazer._gazeTracker.isPickable = false;
  104744. this._cameraGazer._gazeTracker.isVisible = false;
  104745. this._cameraGazer._gazeTracker.name = "gazeTracker";
  104746. if (this._leftController) {
  104747. this._leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  104748. }
  104749. if (this._rightController) {
  104750. this._rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  104751. }
  104752. }
  104753. },
  104754. enumerable: true,
  104755. configurable: true
  104756. });
  104757. Object.defineProperty(VRExperienceHelper.prototype, "leftControllerGazeTrackerMesh", {
  104758. /**
  104759. * The gaze tracking mesh corresponding to the left controller
  104760. */
  104761. get: function () {
  104762. if (this._leftController) {
  104763. return this._leftController._gazeTracker;
  104764. }
  104765. return null;
  104766. },
  104767. enumerable: true,
  104768. configurable: true
  104769. });
  104770. Object.defineProperty(VRExperienceHelper.prototype, "rightControllerGazeTrackerMesh", {
  104771. /**
  104772. * The gaze tracking mesh corresponding to the right controller
  104773. */
  104774. get: function () {
  104775. if (this._rightController) {
  104776. return this._rightController._gazeTracker;
  104777. }
  104778. return null;
  104779. },
  104780. enumerable: true,
  104781. configurable: true
  104782. });
  104783. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  104784. /**
  104785. * If the ray of the gaze should be displayed.
  104786. */
  104787. get: function () {
  104788. return this._displayGaze;
  104789. },
  104790. /**
  104791. * Sets if the ray of the gaze should be displayed.
  104792. */
  104793. set: function (value) {
  104794. this._displayGaze = value;
  104795. if (!value) {
  104796. this._cameraGazer._gazeTracker.isVisible = false;
  104797. if (this._leftController) {
  104798. this._leftController._gazeTracker.isVisible = false;
  104799. }
  104800. if (this._rightController) {
  104801. this._rightController._gazeTracker.isVisible = false;
  104802. }
  104803. }
  104804. },
  104805. enumerable: true,
  104806. configurable: true
  104807. });
  104808. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  104809. /**
  104810. * If the ray of the LaserPointer should be displayed.
  104811. */
  104812. get: function () {
  104813. return this._displayLaserPointer;
  104814. },
  104815. /**
  104816. * Sets if the ray of the LaserPointer should be displayed.
  104817. */
  104818. set: function (value) {
  104819. this._displayLaserPointer = value;
  104820. if (!value) {
  104821. if (this._rightController) {
  104822. this._rightController._deactivatePointer();
  104823. this._rightController._gazeTracker.isVisible = false;
  104824. }
  104825. if (this._leftController) {
  104826. this._leftController._deactivatePointer();
  104827. this._leftController._gazeTracker.isVisible = false;
  104828. }
  104829. }
  104830. else {
  104831. if (this._rightController) {
  104832. this._rightController._activatePointer();
  104833. }
  104834. if (this._leftController) {
  104835. this._leftController._activatePointer();
  104836. }
  104837. }
  104838. },
  104839. enumerable: true,
  104840. configurable: true
  104841. });
  104842. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  104843. /**
  104844. * The deviceOrientationCamera used as the camera when not in VR.
  104845. */
  104846. get: function () {
  104847. return this._deviceOrientationCamera;
  104848. },
  104849. enumerable: true,
  104850. configurable: true
  104851. });
  104852. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  104853. /**
  104854. * Based on the current WebVR support, returns the current VR camera used.
  104855. */
  104856. get: function () {
  104857. if (this._webVRready) {
  104858. return this._webVRCamera;
  104859. }
  104860. else {
  104861. return this._scene.activeCamera;
  104862. }
  104863. },
  104864. enumerable: true,
  104865. configurable: true
  104866. });
  104867. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  104868. /**
  104869. * The webVRCamera which is used when in VR.
  104870. */
  104871. get: function () {
  104872. return this._webVRCamera;
  104873. },
  104874. enumerable: true,
  104875. configurable: true
  104876. });
  104877. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  104878. /**
  104879. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  104880. */
  104881. get: function () {
  104882. return this._vrDeviceOrientationCamera;
  104883. },
  104884. enumerable: true,
  104885. configurable: true
  104886. });
  104887. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  104888. get: function () {
  104889. var result = this._cameraGazer._teleportationRequestInitiated
  104890. || (this._leftController !== null && this._leftController._teleportationRequestInitiated)
  104891. || (this._rightController !== null && this._rightController._teleportationRequestInitiated);
  104892. return result;
  104893. },
  104894. enumerable: true,
  104895. configurable: true
  104896. });
  104897. // Raised when one of the controller has loaded successfully its associated default mesh
  104898. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  104899. if (this._leftController && this._leftController.webVRController == webVRController) {
  104900. if (webVRController.mesh) {
  104901. this._leftController._setLaserPointerParent(webVRController.mesh);
  104902. }
  104903. }
  104904. if (this._rightController && this._rightController.webVRController == webVRController) {
  104905. if (webVRController.mesh) {
  104906. this._rightController._setLaserPointerParent(webVRController.mesh);
  104907. }
  104908. }
  104909. try {
  104910. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  104911. }
  104912. catch (err) {
  104913. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  104914. }
  104915. };
  104916. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  104917. /**
  104918. * Gets a value indicating if we are currently in VR mode.
  104919. */
  104920. get: function () {
  104921. return this._webVRpresenting || this._fullscreenVRpresenting;
  104922. },
  104923. enumerable: true,
  104924. configurable: true
  104925. });
  104926. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  104927. var vrDisplay = this._scene.getEngine().getVRDevice();
  104928. if (vrDisplay) {
  104929. var wasPresenting = this._webVRpresenting;
  104930. this._webVRpresenting = vrDisplay.isPresenting;
  104931. if (wasPresenting && !this._webVRpresenting)
  104932. this.exitVR();
  104933. }
  104934. else {
  104935. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  104936. }
  104937. this.updateButtonVisibility();
  104938. };
  104939. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  104940. this._webVRsupported = eventArgs.vrSupported;
  104941. this._webVRready = !!eventArgs.vrDisplay;
  104942. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  104943. this.updateButtonVisibility();
  104944. };
  104945. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  104946. if (this._canvas && !this._useCustomVRButton) {
  104947. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  104948. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  104949. }
  104950. };
  104951. VRExperienceHelper.prototype.displayVRButton = function () {
  104952. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  104953. document.body.appendChild(this._btnVR);
  104954. this._btnVRDisplayed = true;
  104955. }
  104956. };
  104957. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  104958. if (!this._btnVR || this._useCustomVRButton) {
  104959. return;
  104960. }
  104961. this._btnVR.className = "babylonVRicon";
  104962. if (this.isInVRMode) {
  104963. this._btnVR.className += " vrdisplaypresenting";
  104964. }
  104965. else {
  104966. if (this._webVRready)
  104967. this._btnVR.className += " vrdisplayready";
  104968. if (this._webVRsupported)
  104969. this._btnVR.className += " vrdisplaysupported";
  104970. if (this._webVRrequesting)
  104971. this._btnVR.className += " vrdisplayrequesting";
  104972. }
  104973. };
  104974. /**
  104975. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  104976. * Otherwise, will use the fullscreen API.
  104977. */
  104978. VRExperienceHelper.prototype.enterVR = function () {
  104979. if (this.onEnteringVRObservable) {
  104980. try {
  104981. this.onEnteringVRObservable.notifyObservers(this);
  104982. }
  104983. catch (err) {
  104984. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  104985. }
  104986. }
  104987. if (this._scene.activeCamera) {
  104988. this._position = this._scene.activeCamera.position.clone();
  104989. // make sure that we return to the last active camera
  104990. this._existingCamera = this._scene.activeCamera;
  104991. }
  104992. if (this._webVRrequesting)
  104993. return;
  104994. // If WebVR is supported and a headset is connected
  104995. if (this._webVRready) {
  104996. if (!this._webVRpresenting) {
  104997. this._webVRCamera.position = this._position;
  104998. this._scene.activeCamera = this._webVRCamera;
  104999. }
  105000. }
  105001. else if (this._vrDeviceOrientationCamera) {
  105002. this._vrDeviceOrientationCamera.position = this._position;
  105003. if (this._scene.activeCamera) {
  105004. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  105005. }
  105006. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  105007. this._scene.getEngine().switchFullscreen(true);
  105008. this.updateButtonVisibility();
  105009. }
  105010. if (this._scene.activeCamera && this._canvas) {
  105011. this._scene.activeCamera.attachControl(this._canvas);
  105012. }
  105013. if (this._interactionsEnabled) {
  105014. this._scene.registerBeforeRender(this.beforeRender);
  105015. }
  105016. this._hasEnteredVR = true;
  105017. };
  105018. /**
  105019. * Attempt to exit VR, or fullscreen.
  105020. */
  105021. VRExperienceHelper.prototype.exitVR = function () {
  105022. if (this._hasEnteredVR) {
  105023. if (this.onExitingVRObservable) {
  105024. try {
  105025. this.onExitingVRObservable.notifyObservers(this);
  105026. }
  105027. catch (err) {
  105028. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  105029. }
  105030. }
  105031. if (this._webVRpresenting) {
  105032. this._scene.getEngine().disableVR();
  105033. }
  105034. if (this._scene.activeCamera) {
  105035. this._position = this._scene.activeCamera.position.clone();
  105036. }
  105037. if (this._deviceOrientationCamera) {
  105038. this._deviceOrientationCamera.position = this._position;
  105039. this._scene.activeCamera = this._deviceOrientationCamera;
  105040. if (this._canvas) {
  105041. this._scene.activeCamera.attachControl(this._canvas);
  105042. }
  105043. }
  105044. else if (this._existingCamera) {
  105045. this._existingCamera.position = this._position;
  105046. this._scene.activeCamera = this._existingCamera;
  105047. }
  105048. this.updateButtonVisibility();
  105049. if (this._interactionsEnabled) {
  105050. this._scene.unregisterBeforeRender(this.beforeRender);
  105051. this._cameraGazer._gazeTracker.isVisible = false;
  105052. if (this._leftController) {
  105053. this._leftController._gazeTracker.isVisible = false;
  105054. }
  105055. if (this._rightController) {
  105056. this._rightController._gazeTracker.isVisible = false;
  105057. }
  105058. }
  105059. // resize to update width and height when exiting vr exits fullscreen
  105060. this._scene.getEngine().resize();
  105061. this._hasEnteredVR = false;
  105062. }
  105063. };
  105064. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  105065. /**
  105066. * The position of the vr experience helper.
  105067. */
  105068. get: function () {
  105069. return this._position;
  105070. },
  105071. /**
  105072. * Sets the position of the vr experience helper.
  105073. */
  105074. set: function (value) {
  105075. this._position = value;
  105076. if (this._scene.activeCamera) {
  105077. this._scene.activeCamera.position = value;
  105078. }
  105079. },
  105080. enumerable: true,
  105081. configurable: true
  105082. });
  105083. /**
  105084. * Enables controllers and user interactions such as selecting and object or clicking on an object.
  105085. */
  105086. VRExperienceHelper.prototype.enableInteractions = function () {
  105087. var _this = this;
  105088. if (!this._interactionsEnabled) {
  105089. this._interactionsRequested = true;
  105090. if (this._leftController) {
  105091. this._enableInteractionOnController(this._leftController);
  105092. }
  105093. if (this._rightController) {
  105094. this._enableInteractionOnController(this._rightController);
  105095. }
  105096. this.raySelectionPredicate = function (mesh) {
  105097. return mesh.isVisible && (mesh.isPickable || mesh.name === _this._floorMeshName);
  105098. };
  105099. this.meshSelectionPredicate = function (mesh) {
  105100. return true;
  105101. };
  105102. this._raySelectionPredicate = function (mesh) {
  105103. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  105104. && mesh.name.indexOf("teleportationTarget") === -1
  105105. && mesh.name.indexOf("torusTeleportation") === -1)) {
  105106. return _this.raySelectionPredicate(mesh);
  105107. }
  105108. return false;
  105109. };
  105110. this._interactionsEnabled = true;
  105111. }
  105112. };
  105113. Object.defineProperty(VRExperienceHelper.prototype, "_noControllerIsActive", {
  105114. get: function () {
  105115. return !(this._leftController && this._leftController._activePointer) && !(this._rightController && this._rightController._activePointer);
  105116. },
  105117. enumerable: true,
  105118. configurable: true
  105119. });
  105120. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  105121. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  105122. if (this._floorMeshesCollection[i].id === mesh.id) {
  105123. return true;
  105124. }
  105125. }
  105126. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  105127. return true;
  105128. }
  105129. return false;
  105130. };
  105131. /**
  105132. * Adds a floor mesh to be used for teleportation.
  105133. * @param floorMesh the mesh to be used for teleportation.
  105134. */
  105135. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  105136. if (!this._floorMeshesCollection) {
  105137. return;
  105138. }
  105139. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  105140. return;
  105141. }
  105142. this._floorMeshesCollection.push(floorMesh);
  105143. };
  105144. /**
  105145. * Removes a floor mesh from being used for teleportation.
  105146. * @param floorMesh the mesh to be removed.
  105147. */
  105148. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  105149. if (!this._floorMeshesCollection) {
  105150. return;
  105151. }
  105152. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  105153. if (meshIndex !== -1) {
  105154. this._floorMeshesCollection.splice(meshIndex, 1);
  105155. }
  105156. };
  105157. /**
  105158. * Enables interactions and teleportation using the VR controllers and gaze.
  105159. * @param vrTeleportationOptions options to modify teleportation behavior.
  105160. */
  105161. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  105162. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  105163. if (!this._teleportationInitialized) {
  105164. this._teleportationRequested = true;
  105165. this.enableInteractions();
  105166. if (vrTeleportationOptions.floorMeshName) {
  105167. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  105168. }
  105169. if (vrTeleportationOptions.floorMeshes) {
  105170. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  105171. }
  105172. if (this._leftController != null) {
  105173. this._enableTeleportationOnController(this._leftController);
  105174. }
  105175. if (this._rightController != null) {
  105176. this._enableTeleportationOnController(this._rightController);
  105177. }
  105178. // Creates an image processing post process for the vignette not relying
  105179. // on the main scene configuration for image processing to reduce setup and spaces
  105180. // (gamma/linear) conflicts.
  105181. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  105182. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  105183. imageProcessingConfiguration.vignetteEnabled = true;
  105184. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  105185. this._webVRCamera.detachPostProcess(this._postProcessMove);
  105186. this._teleportationInitialized = true;
  105187. if (this._isDefaultTeleportationTarget) {
  105188. this._createTeleportationCircles();
  105189. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  105190. }
  105191. }
  105192. };
  105193. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  105194. var _this = this;
  105195. var controllerMesh = controller.webVRController.mesh;
  105196. if (controllerMesh) {
  105197. controller._interactionsEnabled = true;
  105198. controller._activatePointer();
  105199. if (this.webVROptions.laserToggle) {
  105200. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  105201. // Enabling / disabling laserPointer
  105202. if (_this._displayLaserPointer && stateObject.value === 1) {
  105203. if (controller._activePointer) {
  105204. controller._deactivatePointer();
  105205. }
  105206. else {
  105207. controller._activatePointer();
  105208. }
  105209. if (_this.displayGaze) {
  105210. controller._gazeTracker.isVisible = controller._activePointer;
  105211. }
  105212. }
  105213. });
  105214. }
  105215. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  105216. var gazer = controller;
  105217. if (_this._noControllerIsActive) {
  105218. gazer = _this._cameraGazer;
  105219. }
  105220. if (!gazer._pointerDownOnMeshAsked) {
  105221. if (stateObject.value > _this._padSensibilityUp) {
  105222. gazer._selectionPointerDown();
  105223. }
  105224. }
  105225. else if (stateObject.value < _this._padSensibilityDown) {
  105226. gazer._selectionPointerUp();
  105227. }
  105228. });
  105229. }
  105230. };
  105231. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  105232. // Dont teleport if another gaze already requested teleportation
  105233. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  105234. return;
  105235. }
  105236. if (!gazer._teleportationRequestInitiated) {
  105237. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  105238. gazer._activatePointer();
  105239. gazer._teleportationRequestInitiated = true;
  105240. }
  105241. }
  105242. else {
  105243. // Listening to the proper controller values changes to confirm teleportation
  105244. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  105245. if (this._teleportActive) {
  105246. this.teleportCamera(this._haloCenter);
  105247. }
  105248. gazer._teleportationRequestInitiated = false;
  105249. }
  105250. }
  105251. };
  105252. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  105253. // Only rotate when user is not currently selecting a teleportation location
  105254. if (gazer._teleportationRequestInitiated) {
  105255. return;
  105256. }
  105257. if (!gazer._rotationLeftAsked) {
  105258. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  105259. gazer._rotationLeftAsked = true;
  105260. if (this._rotationAllowed) {
  105261. this._rotateCamera(false);
  105262. }
  105263. }
  105264. }
  105265. else {
  105266. if (stateObject.x > -this._padSensibilityDown) {
  105267. gazer._rotationLeftAsked = false;
  105268. }
  105269. }
  105270. if (!gazer._rotationRightAsked) {
  105271. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  105272. gazer._rotationRightAsked = true;
  105273. if (this._rotationAllowed) {
  105274. this._rotateCamera(true);
  105275. }
  105276. }
  105277. }
  105278. else {
  105279. if (stateObject.x < this._padSensibilityDown) {
  105280. gazer._rotationRightAsked = false;
  105281. }
  105282. }
  105283. };
  105284. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  105285. // Only teleport backwards when user is not currently selecting a teleportation location
  105286. if (gazer._teleportationRequestInitiated) {
  105287. return;
  105288. }
  105289. // Teleport backwards
  105290. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  105291. if (!gazer._teleportationBackRequestInitiated) {
  105292. if (!this.currentVRCamera) {
  105293. return;
  105294. }
  105295. // Get rotation and position of the current camera
  105296. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  105297. var position = this.currentVRCamera.position;
  105298. // If the camera has device position, use that instead
  105299. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  105300. rotation = this.currentVRCamera.deviceRotationQuaternion;
  105301. position = this.currentVRCamera.devicePosition;
  105302. }
  105303. // Get matrix with only the y rotation of the device rotation
  105304. rotation.toEulerAnglesToRef(this._workingVector);
  105305. this._workingVector.z = 0;
  105306. this._workingVector.x = 0;
  105307. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  105308. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  105309. // Rotate backwards ray by device rotation to cast at the ground behind the user
  105310. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  105311. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  105312. var ray = new BABYLON.Ray(position, this._workingVector);
  105313. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  105314. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  105315. this.teleportCamera(hit.pickedPoint);
  105316. }
  105317. gazer._teleportationBackRequestInitiated = true;
  105318. }
  105319. }
  105320. else {
  105321. gazer._teleportationBackRequestInitiated = false;
  105322. }
  105323. };
  105324. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  105325. var _this = this;
  105326. var controllerMesh = controller.webVRController.mesh;
  105327. if (controllerMesh) {
  105328. if (!controller._interactionsEnabled) {
  105329. this._enableInteractionOnController(controller);
  105330. }
  105331. controller._interactionsEnabled = true;
  105332. controller._teleportationEnabled = true;
  105333. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  105334. controller._dpadPressed = false;
  105335. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  105336. controller._dpadPressed = stateObject.pressed;
  105337. if (!controller._dpadPressed) {
  105338. controller._rotationLeftAsked = false;
  105339. controller._rotationRightAsked = false;
  105340. controller._teleportationBackRequestInitiated = false;
  105341. }
  105342. });
  105343. }
  105344. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  105345. if (_this.teleportationEnabled) {
  105346. _this._checkTeleportBackwards(stateObject, controller);
  105347. _this._checkTeleportWithRay(stateObject, controller);
  105348. }
  105349. _this._checkRotate(stateObject, controller);
  105350. });
  105351. }
  105352. };
  105353. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  105354. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  105355. this._teleportationTarget.isPickable = false;
  105356. var length = 512;
  105357. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  105358. dynamicTexture.hasAlpha = true;
  105359. var context = dynamicTexture.getContext();
  105360. var centerX = length / 2;
  105361. var centerY = length / 2;
  105362. var radius = 200;
  105363. context.beginPath();
  105364. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  105365. context.fillStyle = this._teleportationFillColor;
  105366. context.fill();
  105367. context.lineWidth = 10;
  105368. context.strokeStyle = this._teleportationBorderColor;
  105369. context.stroke();
  105370. context.closePath();
  105371. dynamicTexture.update();
  105372. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  105373. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  105374. this._teleportationTarget.material = teleportationCircleMaterial;
  105375. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  105376. torus.isPickable = false;
  105377. torus.parent = this._teleportationTarget;
  105378. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  105379. var keys = [];
  105380. keys.push({
  105381. frame: 0,
  105382. value: 0
  105383. });
  105384. keys.push({
  105385. frame: 30,
  105386. value: 0.4
  105387. });
  105388. keys.push({
  105389. frame: 60,
  105390. value: 0
  105391. });
  105392. animationInnerCircle.setKeys(keys);
  105393. var easingFunction = new BABYLON.SineEase();
  105394. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  105395. animationInnerCircle.setEasingFunction(easingFunction);
  105396. torus.animations = [];
  105397. torus.animations.push(animationInnerCircle);
  105398. this._scene.beginAnimation(torus, 0, 60, true);
  105399. this._hideTeleportationTarget();
  105400. };
  105401. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  105402. this._teleportActive = true;
  105403. if (this._teleportationInitialized) {
  105404. this._teleportationTarget.isVisible = true;
  105405. if (this._isDefaultTeleportationTarget) {
  105406. this._teleportationTarget.getChildren()[0].isVisible = true;
  105407. }
  105408. }
  105409. };
  105410. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  105411. this._teleportActive = false;
  105412. if (this._teleportationInitialized) {
  105413. this._teleportationTarget.isVisible = false;
  105414. if (this._isDefaultTeleportationTarget) {
  105415. this._teleportationTarget.getChildren()[0].isVisible = false;
  105416. }
  105417. }
  105418. };
  105419. VRExperienceHelper.prototype._rotateCamera = function (right) {
  105420. var _this = this;
  105421. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  105422. return;
  105423. }
  105424. if (right) {
  105425. this._rotationAngle++;
  105426. }
  105427. else {
  105428. this._rotationAngle--;
  105429. }
  105430. this.currentVRCamera.animations = [];
  105431. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  105432. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  105433. var animationRotationKeys = [];
  105434. animationRotationKeys.push({
  105435. frame: 0,
  105436. value: this.currentVRCamera.rotationQuaternion
  105437. });
  105438. animationRotationKeys.push({
  105439. frame: 6,
  105440. value: target
  105441. });
  105442. animationRotation.setKeys(animationRotationKeys);
  105443. animationRotation.setEasingFunction(this._circleEase);
  105444. this.currentVRCamera.animations.push(animationRotation);
  105445. this._postProcessMove.animations = [];
  105446. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  105447. var vignetteWeightKeys = [];
  105448. vignetteWeightKeys.push({
  105449. frame: 0,
  105450. value: 0
  105451. });
  105452. vignetteWeightKeys.push({
  105453. frame: 3,
  105454. value: 4
  105455. });
  105456. vignetteWeightKeys.push({
  105457. frame: 6,
  105458. value: 0
  105459. });
  105460. animationPP.setKeys(vignetteWeightKeys);
  105461. animationPP.setEasingFunction(this._circleEase);
  105462. this._postProcessMove.animations.push(animationPP);
  105463. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  105464. var vignetteStretchKeys = [];
  105465. vignetteStretchKeys.push({
  105466. frame: 0,
  105467. value: 0
  105468. });
  105469. vignetteStretchKeys.push({
  105470. frame: 3,
  105471. value: 10
  105472. });
  105473. vignetteStretchKeys.push({
  105474. frame: 6,
  105475. value: 0
  105476. });
  105477. animationPP2.setKeys(vignetteStretchKeys);
  105478. animationPP2.setEasingFunction(this._circleEase);
  105479. this._postProcessMove.animations.push(animationPP2);
  105480. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  105481. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  105482. this._postProcessMove.samples = 4;
  105483. this._webVRCamera.attachPostProcess(this._postProcessMove);
  105484. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  105485. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  105486. });
  105487. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  105488. };
  105489. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  105490. if (hit.pickedPoint) {
  105491. if (gazer._teleportationRequestInitiated) {
  105492. this._displayTeleportationTarget();
  105493. this._haloCenter.copyFrom(hit.pickedPoint);
  105494. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  105495. }
  105496. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  105497. if (pickNormal) {
  105498. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  105499. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  105500. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  105501. }
  105502. this._teleportationTarget.position.y += 0.1;
  105503. }
  105504. };
  105505. /**
  105506. * Teleports the users feet to the desired location
  105507. * @param location The location where the user's feet should be placed
  105508. */
  105509. VRExperienceHelper.prototype.teleportCamera = function (location) {
  105510. var _this = this;
  105511. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  105512. return;
  105513. }
  105514. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  105515. // offset of the headset from the anchor.
  105516. if (this.webVRCamera.leftCamera) {
  105517. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  105518. this._workingVector.subtractInPlace(this.webVRCamera.position);
  105519. location.subtractToRef(this._workingVector, this._workingVector);
  105520. }
  105521. else {
  105522. this._workingVector.copyFrom(location);
  105523. }
  105524. // Add height to account for user's height offset
  105525. if (this.isInVRMode) {
  105526. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  105527. }
  105528. else {
  105529. this._workingVector.y += this._defaultHeight;
  105530. }
  105531. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  105532. // Create animation from the camera's position to the new location
  105533. this.currentVRCamera.animations = [];
  105534. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  105535. var animationCameraTeleportationKeys = [{
  105536. frame: 0,
  105537. value: this.currentVRCamera.position
  105538. },
  105539. {
  105540. frame: 11,
  105541. value: this._workingVector
  105542. }
  105543. ];
  105544. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  105545. animationCameraTeleportation.setEasingFunction(this._circleEase);
  105546. this.currentVRCamera.animations.push(animationCameraTeleportation);
  105547. this._postProcessMove.animations = [];
  105548. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  105549. var vignetteWeightKeys = [];
  105550. vignetteWeightKeys.push({
  105551. frame: 0,
  105552. value: 0
  105553. });
  105554. vignetteWeightKeys.push({
  105555. frame: 5,
  105556. value: 8
  105557. });
  105558. vignetteWeightKeys.push({
  105559. frame: 11,
  105560. value: 0
  105561. });
  105562. animationPP.setKeys(vignetteWeightKeys);
  105563. this._postProcessMove.animations.push(animationPP);
  105564. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  105565. var vignetteStretchKeys = [];
  105566. vignetteStretchKeys.push({
  105567. frame: 0,
  105568. value: 0
  105569. });
  105570. vignetteStretchKeys.push({
  105571. frame: 5,
  105572. value: 10
  105573. });
  105574. vignetteStretchKeys.push({
  105575. frame: 11,
  105576. value: 0
  105577. });
  105578. animationPP2.setKeys(vignetteStretchKeys);
  105579. this._postProcessMove.animations.push(animationPP2);
  105580. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  105581. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  105582. this._webVRCamera.attachPostProcess(this._postProcessMove);
  105583. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  105584. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  105585. });
  105586. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  105587. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  105588. });
  105589. this._hideTeleportationTarget();
  105590. };
  105591. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  105592. if (normal) {
  105593. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  105594. if (angle < Math.PI / 2) {
  105595. normal.scaleInPlace(-1);
  105596. }
  105597. }
  105598. return normal;
  105599. };
  105600. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  105601. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  105602. return;
  105603. }
  105604. var ray = gazer._getForwardRay(this._rayLength);
  105605. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  105606. if (hit) {
  105607. // Populate the contrllers mesh that can be used for drag/drop
  105608. if (gazer._laserPointer) {
  105609. hit.originMesh = gazer._laserPointer.parent;
  105610. }
  105611. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  105612. }
  105613. gazer._currentHit = hit;
  105614. // Moving the gazeTracker on the mesh face targetted
  105615. if (hit && hit.pickedPoint) {
  105616. if (this._displayGaze) {
  105617. var multiplier = 1;
  105618. gazer._gazeTracker.isVisible = true;
  105619. if (gazer._isActionableMesh) {
  105620. multiplier = 3;
  105621. }
  105622. if (this.updateGazeTrackerScale) {
  105623. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  105624. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  105625. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  105626. }
  105627. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  105628. // To avoid z-fighting
  105629. var deltaFighting = 0.002;
  105630. if (pickNormal) {
  105631. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  105632. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  105633. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  105634. }
  105635. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  105636. if (gazer._gazeTracker.position.x < 0) {
  105637. gazer._gazeTracker.position.x += deltaFighting;
  105638. }
  105639. else {
  105640. gazer._gazeTracker.position.x -= deltaFighting;
  105641. }
  105642. if (gazer._gazeTracker.position.y < 0) {
  105643. gazer._gazeTracker.position.y += deltaFighting;
  105644. }
  105645. else {
  105646. gazer._gazeTracker.position.y -= deltaFighting;
  105647. }
  105648. if (gazer._gazeTracker.position.z < 0) {
  105649. gazer._gazeTracker.position.z += deltaFighting;
  105650. }
  105651. else {
  105652. gazer._gazeTracker.position.z -= deltaFighting;
  105653. }
  105654. }
  105655. // Changing the size of the laser pointer based on the distance from the targetted point
  105656. gazer._updatePointerDistance(hit.distance);
  105657. }
  105658. else {
  105659. gazer._updatePointerDistance();
  105660. gazer._gazeTracker.isVisible = false;
  105661. }
  105662. if (hit && hit.pickedMesh) {
  105663. // The object selected is the floor, we're in a teleportation scenario
  105664. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  105665. // Moving the teleportation area to this targetted point
  105666. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  105667. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  105668. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  105669. }
  105670. gazer._currentMeshSelected = null;
  105671. if (gazer._teleportationRequestInitiated) {
  105672. this._moveTeleportationSelectorTo(hit, gazer, ray);
  105673. }
  105674. return;
  105675. }
  105676. // If not, we're in a selection scenario
  105677. //this._teleportationAllowed = false;
  105678. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  105679. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  105680. this.onNewMeshPicked.notifyObservers(hit);
  105681. gazer._currentMeshSelected = hit.pickedMesh;
  105682. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  105683. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  105684. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  105685. gazer._isActionableMesh = true;
  105686. }
  105687. else {
  105688. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  105689. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  105690. gazer._isActionableMesh = false;
  105691. }
  105692. try {
  105693. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  105694. }
  105695. catch (err) {
  105696. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  105697. }
  105698. }
  105699. else {
  105700. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  105701. gazer._currentMeshSelected = null;
  105702. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  105703. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  105704. }
  105705. }
  105706. }
  105707. else {
  105708. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  105709. gazer._currentMeshSelected = null;
  105710. //this._teleportationAllowed = false;
  105711. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  105712. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  105713. }
  105714. };
  105715. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  105716. if (mesh) {
  105717. this.onSelectedMeshUnselected.notifyObservers(mesh);
  105718. }
  105719. };
  105720. /**
  105721. * Sets the color of the laser ray from the vr controllers.
  105722. * @param color new color for the ray.
  105723. */
  105724. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  105725. if (this._leftController) {
  105726. this._leftController._setLaserPointerColor(color);
  105727. }
  105728. if (this._rightController) {
  105729. this._rightController._setLaserPointerColor(color);
  105730. }
  105731. };
  105732. /**
  105733. * Sets the color of the ray from the vr headsets gaze.
  105734. * @param color new color for the ray.
  105735. */
  105736. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  105737. if (!this._cameraGazer._gazeTracker.material) {
  105738. return;
  105739. }
  105740. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  105741. if (this._leftController) {
  105742. this._leftController._gazeTracker.material.emissiveColor = color;
  105743. }
  105744. if (this._rightController) {
  105745. this._rightController._gazeTracker.material.emissiveColor = color;
  105746. }
  105747. };
  105748. /**
  105749. * Exits VR and disposes of the vr experience helper
  105750. */
  105751. VRExperienceHelper.prototype.dispose = function () {
  105752. if (this.isInVRMode) {
  105753. this.exitVR();
  105754. }
  105755. if (this._postProcessMove) {
  105756. this._postProcessMove.dispose();
  105757. }
  105758. if (this._webVRCamera) {
  105759. this._webVRCamera.dispose();
  105760. }
  105761. if (this._vrDeviceOrientationCamera) {
  105762. this._vrDeviceOrientationCamera.dispose();
  105763. }
  105764. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  105765. document.body.removeChild(this._btnVR);
  105766. }
  105767. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  105768. this._deviceOrientationCamera.dispose();
  105769. }
  105770. if (this._cameraGazer) {
  105771. this._cameraGazer.dispose();
  105772. }
  105773. if (this._leftController) {
  105774. this._leftController.dispose();
  105775. }
  105776. if (this._rightController) {
  105777. this._rightController.dispose();
  105778. }
  105779. if (this._teleportationTarget) {
  105780. this._teleportationTarget.dispose();
  105781. }
  105782. this._floorMeshesCollection = [];
  105783. document.removeEventListener("keydown", this._onKeyDown);
  105784. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  105785. window.removeEventListener("resize", this._onResize);
  105786. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  105787. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  105788. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  105789. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  105790. document.onmsfullscreenchange = null;
  105791. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  105792. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  105793. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  105794. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  105795. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  105796. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  105797. this._scene.unregisterBeforeRender(this.beforeRender);
  105798. };
  105799. /**
  105800. * Gets the name of the VRExperienceHelper class
  105801. * @returns "VRExperienceHelper"
  105802. */
  105803. VRExperienceHelper.prototype.getClassName = function () {
  105804. return "VRExperienceHelper";
  105805. };
  105806. return VRExperienceHelper;
  105807. }());
  105808. BABYLON.VRExperienceHelper = VRExperienceHelper;
  105809. })(BABYLON || (BABYLON = {}));
  105810. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  105811. // Mainly based on these 2 articles :
  105812. // 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
  105813. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  105814. var BABYLON;
  105815. (function (BABYLON) {
  105816. /**
  105817. * Defines the potential axis of a Joystick
  105818. */
  105819. var JoystickAxis;
  105820. (function (JoystickAxis) {
  105821. /** X axis */
  105822. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  105823. /** Y axis */
  105824. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  105825. /** Z axis */
  105826. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  105827. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  105828. /**
  105829. * Class used to define virtual joystick (used in touch mode)
  105830. */
  105831. var VirtualJoystick = /** @class */ (function () {
  105832. /**
  105833. * Creates a new virtual joystick
  105834. * @param leftJoystick defines that the joystick is for left hand (false by default)
  105835. */
  105836. function VirtualJoystick(leftJoystick) {
  105837. var _this = this;
  105838. if (leftJoystick) {
  105839. this._leftJoystick = true;
  105840. }
  105841. else {
  105842. this._leftJoystick = false;
  105843. }
  105844. VirtualJoystick._globalJoystickIndex++;
  105845. // By default left & right arrow keys are moving the X
  105846. // and up & down keys are moving the Y
  105847. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  105848. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  105849. this.reverseLeftRight = false;
  105850. this.reverseUpDown = false;
  105851. // collections of pointers
  105852. this._touches = new BABYLON.StringDictionary();
  105853. this.deltaPosition = BABYLON.Vector3.Zero();
  105854. this._joystickSensibility = 25;
  105855. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  105856. this._onResize = function (evt) {
  105857. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  105858. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  105859. if (VirtualJoystick.vjCanvas) {
  105860. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  105861. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  105862. }
  105863. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  105864. };
  105865. // injecting a canvas element on top of the canvas 3D game
  105866. if (!VirtualJoystick.vjCanvas) {
  105867. window.addEventListener("resize", this._onResize, false);
  105868. VirtualJoystick.vjCanvas = document.createElement("canvas");
  105869. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  105870. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  105871. VirtualJoystick.vjCanvas.width = window.innerWidth;
  105872. VirtualJoystick.vjCanvas.height = window.innerHeight;
  105873. VirtualJoystick.vjCanvas.style.width = "100%";
  105874. VirtualJoystick.vjCanvas.style.height = "100%";
  105875. VirtualJoystick.vjCanvas.style.position = "absolute";
  105876. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  105877. VirtualJoystick.vjCanvas.style.top = "0px";
  105878. VirtualJoystick.vjCanvas.style.left = "0px";
  105879. VirtualJoystick.vjCanvas.style.zIndex = "5";
  105880. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  105881. // Support for jQuery PEP polyfill
  105882. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  105883. var context = VirtualJoystick.vjCanvas.getContext('2d');
  105884. if (!context) {
  105885. throw new Error("Unable to create canvas for virtual joystick");
  105886. }
  105887. VirtualJoystick.vjCanvasContext = context;
  105888. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  105889. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  105890. document.body.appendChild(VirtualJoystick.vjCanvas);
  105891. }
  105892. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  105893. this.pressed = false;
  105894. // default joystick color
  105895. this._joystickColor = "cyan";
  105896. this._joystickPointerID = -1;
  105897. // current joystick position
  105898. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  105899. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  105900. // origin joystick position
  105901. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  105902. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  105903. this._onPointerDownHandlerRef = function (evt) {
  105904. _this._onPointerDown(evt);
  105905. };
  105906. this._onPointerMoveHandlerRef = function (evt) {
  105907. _this._onPointerMove(evt);
  105908. };
  105909. this._onPointerUpHandlerRef = function (evt) {
  105910. _this._onPointerUp(evt);
  105911. };
  105912. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  105913. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  105914. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  105915. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  105916. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  105917. evt.preventDefault(); // Disables system menu
  105918. }, false);
  105919. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  105920. }
  105921. /**
  105922. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  105923. * @param newJoystickSensibility defines the new sensibility
  105924. */
  105925. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  105926. this._joystickSensibility = newJoystickSensibility;
  105927. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  105928. };
  105929. VirtualJoystick.prototype._onPointerDown = function (e) {
  105930. var positionOnScreenCondition;
  105931. e.preventDefault();
  105932. if (this._leftJoystick === true) {
  105933. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  105934. }
  105935. else {
  105936. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  105937. }
  105938. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  105939. // First contact will be dedicated to the virtual joystick
  105940. this._joystickPointerID = e.pointerId;
  105941. this._joystickPointerStartPos.x = e.clientX;
  105942. this._joystickPointerStartPos.y = e.clientY;
  105943. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  105944. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  105945. this._deltaJoystickVector.x = 0;
  105946. this._deltaJoystickVector.y = 0;
  105947. this.pressed = true;
  105948. this._touches.add(e.pointerId.toString(), e);
  105949. }
  105950. else {
  105951. // You can only trigger the action buttons with a joystick declared
  105952. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  105953. this._action();
  105954. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  105955. }
  105956. }
  105957. };
  105958. VirtualJoystick.prototype._onPointerMove = function (e) {
  105959. // If the current pointer is the one associated to the joystick (first touch contact)
  105960. if (this._joystickPointerID == e.pointerId) {
  105961. this._joystickPointerPos.x = e.clientX;
  105962. this._joystickPointerPos.y = e.clientY;
  105963. this._deltaJoystickVector = this._joystickPointerPos.clone();
  105964. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  105965. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  105966. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  105967. switch (this._axisTargetedByLeftAndRight) {
  105968. case JoystickAxis.X:
  105969. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  105970. break;
  105971. case JoystickAxis.Y:
  105972. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  105973. break;
  105974. case JoystickAxis.Z:
  105975. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  105976. break;
  105977. }
  105978. var directionUpDown = this.reverseUpDown ? 1 : -1;
  105979. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  105980. switch (this._axisTargetedByUpAndDown) {
  105981. case JoystickAxis.X:
  105982. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  105983. break;
  105984. case JoystickAxis.Y:
  105985. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  105986. break;
  105987. case JoystickAxis.Z:
  105988. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  105989. break;
  105990. }
  105991. }
  105992. else {
  105993. var data = this._touches.get(e.pointerId.toString());
  105994. if (data) {
  105995. data.x = e.clientX;
  105996. data.y = e.clientY;
  105997. }
  105998. }
  105999. };
  106000. VirtualJoystick.prototype._onPointerUp = function (e) {
  106001. if (this._joystickPointerID == e.pointerId) {
  106002. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  106003. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  106004. this._joystickPointerID = -1;
  106005. this.pressed = false;
  106006. }
  106007. else {
  106008. var touch = this._touches.get(e.pointerId.toString());
  106009. if (touch) {
  106010. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  106011. }
  106012. }
  106013. this._deltaJoystickVector.x = 0;
  106014. this._deltaJoystickVector.y = 0;
  106015. this._touches.remove(e.pointerId.toString());
  106016. };
  106017. /**
  106018. * Change the color of the virtual joystick
  106019. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  106020. */
  106021. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  106022. this._joystickColor = newColor;
  106023. };
  106024. /**
  106025. * Defines a callback to call when the joystick is touched
  106026. * @param action defines the callback
  106027. */
  106028. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  106029. this._action = action;
  106030. };
  106031. /**
  106032. * Defines which axis you'd like to control for left & right
  106033. * @param axis defines the axis to use
  106034. */
  106035. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  106036. switch (axis) {
  106037. case JoystickAxis.X:
  106038. case JoystickAxis.Y:
  106039. case JoystickAxis.Z:
  106040. this._axisTargetedByLeftAndRight = axis;
  106041. break;
  106042. default:
  106043. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  106044. break;
  106045. }
  106046. };
  106047. /**
  106048. * Defines which axis you'd like to control for up & down
  106049. * @param axis defines the axis to use
  106050. */
  106051. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  106052. switch (axis) {
  106053. case JoystickAxis.X:
  106054. case JoystickAxis.Y:
  106055. case JoystickAxis.Z:
  106056. this._axisTargetedByUpAndDown = axis;
  106057. break;
  106058. default:
  106059. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  106060. break;
  106061. }
  106062. };
  106063. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  106064. var _this = this;
  106065. if (this.pressed) {
  106066. this._touches.forEach(function (key, touch) {
  106067. if (touch.pointerId === _this._joystickPointerID) {
  106068. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  106069. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  106070. VirtualJoystick.vjCanvasContext.beginPath();
  106071. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  106072. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  106073. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  106074. VirtualJoystick.vjCanvasContext.stroke();
  106075. VirtualJoystick.vjCanvasContext.closePath();
  106076. VirtualJoystick.vjCanvasContext.beginPath();
  106077. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  106078. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  106079. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  106080. VirtualJoystick.vjCanvasContext.stroke();
  106081. VirtualJoystick.vjCanvasContext.closePath();
  106082. VirtualJoystick.vjCanvasContext.beginPath();
  106083. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  106084. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  106085. VirtualJoystick.vjCanvasContext.stroke();
  106086. VirtualJoystick.vjCanvasContext.closePath();
  106087. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  106088. }
  106089. else {
  106090. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  106091. VirtualJoystick.vjCanvasContext.beginPath();
  106092. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  106093. VirtualJoystick.vjCanvasContext.beginPath();
  106094. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  106095. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  106096. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  106097. VirtualJoystick.vjCanvasContext.stroke();
  106098. VirtualJoystick.vjCanvasContext.closePath();
  106099. touch.prevX = touch.x;
  106100. touch.prevY = touch.y;
  106101. }
  106102. ;
  106103. });
  106104. }
  106105. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  106106. };
  106107. /**
  106108. * Release internal HTML canvas
  106109. */
  106110. VirtualJoystick.prototype.releaseCanvas = function () {
  106111. if (VirtualJoystick.vjCanvas) {
  106112. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  106113. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  106114. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  106115. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  106116. window.removeEventListener("resize", this._onResize);
  106117. document.body.removeChild(VirtualJoystick.vjCanvas);
  106118. VirtualJoystick.vjCanvas = null;
  106119. }
  106120. };
  106121. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  106122. VirtualJoystick._globalJoystickIndex = 0;
  106123. return VirtualJoystick;
  106124. }());
  106125. BABYLON.VirtualJoystick = VirtualJoystick;
  106126. })(BABYLON || (BABYLON = {}));
  106127. //# sourceMappingURL=babylon.virtualJoystick.js.map
  106128. var BABYLON;
  106129. (function (BABYLON) {
  106130. BABYLON.Node.AddNodeConstructor("VirtualJoysticksCamera", function (name, scene) {
  106131. return function () { return new VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  106132. });
  106133. /**
  106134. * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
  106135. * It is identical to the Free Camera and simply adds by default a virtual joystick.
  106136. * Virtual Joysticks are on-screen 2D graphics that are used to control the camera or other scene items.
  106137. * @see http://doc.babylonjs.com/features/cameras#virtual-joysticks-camera
  106138. */
  106139. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  106140. __extends(VirtualJoysticksCamera, _super);
  106141. /**
  106142. * Intantiates a VirtualJoysticksCamera. It can be usefull in First Person Shooter game for instance.
  106143. * It is identical to the Free Camera and simply adds by default a virtual joystick.
  106144. * Virtual Joysticks are on-screen 2D graphics that are used to control the camera or other scene items.
  106145. * @see http://doc.babylonjs.com/features/cameras#virtual-joysticks-camera
  106146. * @param name Define the name of the camera in the scene
  106147. * @param position Define the start position of the camera in the scene
  106148. * @param scene Define the scene the camera belongs to
  106149. */
  106150. function VirtualJoysticksCamera(name, position, scene) {
  106151. var _this = _super.call(this, name, position, scene) || this;
  106152. _this.inputs.addVirtualJoystick();
  106153. return _this;
  106154. }
  106155. /**
  106156. * Gets the current object class name.
  106157. * @return the class name
  106158. */
  106159. VirtualJoysticksCamera.prototype.getClassName = function () {
  106160. return "VirtualJoysticksCamera";
  106161. };
  106162. return VirtualJoysticksCamera;
  106163. }(BABYLON.FreeCamera));
  106164. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  106165. })(BABYLON || (BABYLON = {}));
  106166. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  106167. var BABYLON;
  106168. (function (BABYLON) {
  106169. /**
  106170. * Manage the Virtual Joystick inputs to control the movement of a free camera.
  106171. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  106172. */
  106173. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  106174. function FreeCameraVirtualJoystickInput() {
  106175. }
  106176. /**
  106177. * Gets the left stick of the virtual joystick.
  106178. * @returns The virtual Joystick
  106179. */
  106180. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  106181. return this._leftjoystick;
  106182. };
  106183. /**
  106184. * Gets the right stick of the virtual joystick.
  106185. * @returns The virtual Joystick
  106186. */
  106187. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  106188. return this._rightjoystick;
  106189. };
  106190. /**
  106191. * Update the current camera state depending on the inputs that have been used this frame.
  106192. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  106193. */
  106194. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  106195. if (this._leftjoystick) {
  106196. var camera = this.camera;
  106197. var speed = camera._computeLocalCameraSpeed() * 50;
  106198. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  106199. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  106200. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  106201. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  106202. if (!this._leftjoystick.pressed) {
  106203. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  106204. }
  106205. if (!this._rightjoystick.pressed) {
  106206. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  106207. }
  106208. }
  106209. };
  106210. /**
  106211. * Attach the input controls to a specific dom element to get the input from.
  106212. * @param element Defines the element the controls should be listened from
  106213. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  106214. */
  106215. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  106216. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  106217. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  106218. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  106219. this._leftjoystick.setJoystickSensibility(0.15);
  106220. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  106221. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  106222. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  106223. this._rightjoystick.reverseUpDown = true;
  106224. this._rightjoystick.setJoystickSensibility(0.05);
  106225. this._rightjoystick.setJoystickColor("yellow");
  106226. };
  106227. /**
  106228. * Detach the current controls from the specified dom element.
  106229. * @param element Defines the element to stop listening the inputs from
  106230. */
  106231. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  106232. this._leftjoystick.releaseCanvas();
  106233. this._rightjoystick.releaseCanvas();
  106234. };
  106235. /**
  106236. * Gets the class name of the current intput.
  106237. * @returns the class name
  106238. */
  106239. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  106240. return "FreeCameraVirtualJoystickInput";
  106241. };
  106242. /**
  106243. * Get the friendly name associated with the input class.
  106244. * @returns the input friendly name
  106245. */
  106246. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  106247. return "virtualJoystick";
  106248. };
  106249. return FreeCameraVirtualJoystickInput;
  106250. }());
  106251. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  106252. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  106253. })(BABYLON || (BABYLON = {}));
  106254. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  106255. var BABYLON;
  106256. (function (BABYLON) {
  106257. /**
  106258. * Class used to specify simplification options
  106259. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  106260. */
  106261. var SimplificationSettings = /** @class */ (function () {
  106262. /**
  106263. * Creates a SimplificationSettings
  106264. * @param quality expected quality
  106265. * @param distance distance when this optimized version should be used
  106266. * @param optimizeMesh already optimized mesh
  106267. */
  106268. function SimplificationSettings(
  106269. /** expected quality */
  106270. quality,
  106271. /** distance when this optimized version should be used */
  106272. distance,
  106273. /** already optimized mesh */
  106274. optimizeMesh) {
  106275. this.quality = quality;
  106276. this.distance = distance;
  106277. this.optimizeMesh = optimizeMesh;
  106278. }
  106279. return SimplificationSettings;
  106280. }());
  106281. BABYLON.SimplificationSettings = SimplificationSettings;
  106282. /**
  106283. * Queue used to order the simplification tasks
  106284. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  106285. */
  106286. var SimplificationQueue = /** @class */ (function () {
  106287. /**
  106288. * Creates a new queue
  106289. */
  106290. function SimplificationQueue() {
  106291. this.running = false;
  106292. this._simplificationArray = [];
  106293. }
  106294. /**
  106295. * Adds a new simplification task
  106296. * @param task defines a task to add
  106297. */
  106298. SimplificationQueue.prototype.addTask = function (task) {
  106299. this._simplificationArray.push(task);
  106300. };
  106301. /**
  106302. * Execute next task
  106303. */
  106304. SimplificationQueue.prototype.executeNext = function () {
  106305. var task = this._simplificationArray.pop();
  106306. if (task) {
  106307. this.running = true;
  106308. this.runSimplification(task);
  106309. }
  106310. else {
  106311. this.running = false;
  106312. }
  106313. };
  106314. /**
  106315. * Execute a simplification task
  106316. * @param task defines the task to run
  106317. */
  106318. SimplificationQueue.prototype.runSimplification = function (task) {
  106319. var _this = this;
  106320. if (task.parallelProcessing) {
  106321. //parallel simplifier
  106322. task.settings.forEach(function (setting) {
  106323. var simplifier = _this.getSimplifier(task);
  106324. simplifier.simplify(setting, function (newMesh) {
  106325. task.mesh.addLODLevel(setting.distance, newMesh);
  106326. newMesh.isVisible = true;
  106327. //check if it is the last
  106328. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  106329. //all done, run the success callback.
  106330. task.successCallback();
  106331. }
  106332. _this.executeNext();
  106333. });
  106334. });
  106335. }
  106336. else {
  106337. //single simplifier.
  106338. var simplifier = this.getSimplifier(task);
  106339. var runDecimation = function (setting, callback) {
  106340. simplifier.simplify(setting, function (newMesh) {
  106341. task.mesh.addLODLevel(setting.distance, newMesh);
  106342. newMesh.isVisible = true;
  106343. //run the next quality level
  106344. callback();
  106345. });
  106346. };
  106347. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  106348. runDecimation(task.settings[loop.index], function () {
  106349. loop.executeNext();
  106350. });
  106351. }, function () {
  106352. //execution ended, run the success callback.
  106353. if (task.successCallback) {
  106354. task.successCallback();
  106355. }
  106356. _this.executeNext();
  106357. });
  106358. }
  106359. };
  106360. SimplificationQueue.prototype.getSimplifier = function (task) {
  106361. switch (task.simplificationType) {
  106362. case SimplificationType.QUADRATIC:
  106363. default:
  106364. return new QuadraticErrorSimplification(task.mesh);
  106365. }
  106366. };
  106367. return SimplificationQueue;
  106368. }());
  106369. BABYLON.SimplificationQueue = SimplificationQueue;
  106370. /**
  106371. * The implemented types of simplification
  106372. * At the moment only Quadratic Error Decimation is implemented
  106373. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  106374. */
  106375. var SimplificationType;
  106376. (function (SimplificationType) {
  106377. /** Quadratic error decimation */
  106378. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  106379. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  106380. var DecimationTriangle = /** @class */ (function () {
  106381. function DecimationTriangle(vertices) {
  106382. this.vertices = vertices;
  106383. this.error = new Array(4);
  106384. this.deleted = false;
  106385. this.isDirty = false;
  106386. this.deletePending = false;
  106387. this.borderFactor = 0;
  106388. }
  106389. return DecimationTriangle;
  106390. }());
  106391. var DecimationVertex = /** @class */ (function () {
  106392. function DecimationVertex(position, id) {
  106393. this.position = position;
  106394. this.id = id;
  106395. this.isBorder = true;
  106396. this.q = new QuadraticMatrix();
  106397. this.triangleCount = 0;
  106398. this.triangleStart = 0;
  106399. this.originalOffsets = [];
  106400. }
  106401. DecimationVertex.prototype.updatePosition = function (newPosition) {
  106402. this.position.copyFrom(newPosition);
  106403. };
  106404. return DecimationVertex;
  106405. }());
  106406. var QuadraticMatrix = /** @class */ (function () {
  106407. function QuadraticMatrix(data) {
  106408. this.data = new Array(10);
  106409. for (var i = 0; i < 10; ++i) {
  106410. if (data && data[i]) {
  106411. this.data[i] = data[i];
  106412. }
  106413. else {
  106414. this.data[i] = 0;
  106415. }
  106416. }
  106417. }
  106418. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  106419. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  106420. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  106421. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  106422. return det;
  106423. };
  106424. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  106425. for (var i = 0; i < 10; ++i) {
  106426. this.data[i] += matrix.data[i];
  106427. }
  106428. };
  106429. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  106430. for (var i = 0; i < 10; ++i) {
  106431. this.data[i] += data[i];
  106432. }
  106433. };
  106434. QuadraticMatrix.prototype.add = function (matrix) {
  106435. var m = new QuadraticMatrix();
  106436. for (var i = 0; i < 10; ++i) {
  106437. m.data[i] = this.data[i] + matrix.data[i];
  106438. }
  106439. return m;
  106440. };
  106441. QuadraticMatrix.FromData = function (a, b, c, d) {
  106442. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  106443. };
  106444. //returning an array to avoid garbage collection
  106445. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  106446. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  106447. };
  106448. return QuadraticMatrix;
  106449. }());
  106450. var Reference = /** @class */ (function () {
  106451. function Reference(vertexId, triangleId) {
  106452. this.vertexId = vertexId;
  106453. this.triangleId = triangleId;
  106454. }
  106455. return Reference;
  106456. }());
  106457. /**
  106458. * An implementation of the Quadratic Error simplification algorithm.
  106459. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  106460. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  106461. * @author RaananW
  106462. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  106463. */
  106464. var QuadraticErrorSimplification = /** @class */ (function () {
  106465. function QuadraticErrorSimplification(_mesh) {
  106466. this._mesh = _mesh;
  106467. this.syncIterations = 5000;
  106468. this.aggressiveness = 7;
  106469. this.decimationIterations = 100;
  106470. this.boundingBoxEpsilon = BABYLON.Epsilon;
  106471. }
  106472. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  106473. var _this = this;
  106474. this.initDecimatedMesh();
  106475. //iterating through the submeshes array, one after the other.
  106476. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  106477. _this.initWithMesh(loop.index, function () {
  106478. _this.runDecimation(settings, loop.index, function () {
  106479. loop.executeNext();
  106480. });
  106481. }, settings.optimizeMesh);
  106482. }, function () {
  106483. setTimeout(function () {
  106484. successCallback(_this._reconstructedMesh);
  106485. }, 0);
  106486. });
  106487. };
  106488. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  106489. var _this = this;
  106490. var targetCount = ~~(this.triangles.length * settings.quality);
  106491. var deletedTriangles = 0;
  106492. var triangleCount = this.triangles.length;
  106493. var iterationFunction = function (iteration, callback) {
  106494. setTimeout(function () {
  106495. if (iteration % 5 === 0) {
  106496. _this.updateMesh(iteration === 0);
  106497. }
  106498. for (var i = 0; i < _this.triangles.length; ++i) {
  106499. _this.triangles[i].isDirty = false;
  106500. }
  106501. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  106502. var trianglesIterator = function (i) {
  106503. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  106504. var t = _this.triangles[tIdx];
  106505. if (!t)
  106506. return;
  106507. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  106508. return;
  106509. }
  106510. for (var j = 0; j < 3; ++j) {
  106511. if (t.error[j] < threshold) {
  106512. var deleted0 = [];
  106513. var deleted1 = [];
  106514. var v0 = t.vertices[j];
  106515. var v1 = t.vertices[(j + 1) % 3];
  106516. if (v0.isBorder || v1.isBorder)
  106517. continue;
  106518. var p = BABYLON.Vector3.Zero();
  106519. var n = BABYLON.Vector3.Zero();
  106520. var uv = BABYLON.Vector2.Zero();
  106521. var color = new BABYLON.Color4(0, 0, 0, 1);
  106522. _this.calculateError(v0, v1, p, n, uv, color);
  106523. var delTr = new Array();
  106524. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  106525. continue;
  106526. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  106527. continue;
  106528. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  106529. continue;
  106530. var uniqueArray = new Array();
  106531. delTr.forEach(function (deletedT) {
  106532. if (uniqueArray.indexOf(deletedT) === -1) {
  106533. deletedT.deletePending = true;
  106534. uniqueArray.push(deletedT);
  106535. }
  106536. });
  106537. if (uniqueArray.length % 2 !== 0) {
  106538. continue;
  106539. }
  106540. v0.q = v1.q.add(v0.q);
  106541. v0.updatePosition(p);
  106542. var tStart = _this.references.length;
  106543. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  106544. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  106545. var tCount = _this.references.length - tStart;
  106546. if (tCount <= v0.triangleCount) {
  106547. if (tCount) {
  106548. for (var c = 0; c < tCount; c++) {
  106549. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  106550. }
  106551. }
  106552. }
  106553. else {
  106554. v0.triangleStart = tStart;
  106555. }
  106556. v0.triangleCount = tCount;
  106557. break;
  106558. }
  106559. }
  106560. };
  106561. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  106562. }, 0);
  106563. };
  106564. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  106565. if (triangleCount - deletedTriangles <= targetCount)
  106566. loop.breakLoop();
  106567. else {
  106568. iterationFunction(loop.index, function () {
  106569. loop.executeNext();
  106570. });
  106571. }
  106572. }, function () {
  106573. setTimeout(function () {
  106574. //reconstruct this part of the mesh
  106575. _this.reconstructMesh(submeshIndex);
  106576. successCallback();
  106577. }, 0);
  106578. });
  106579. };
  106580. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  106581. var _this = this;
  106582. this.vertices = [];
  106583. this.triangles = [];
  106584. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  106585. var indices = this._mesh.getIndices();
  106586. var submesh = this._mesh.subMeshes[submeshIndex];
  106587. var findInVertices = function (positionToSearch) {
  106588. if (optimizeMesh) {
  106589. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  106590. if (_this.vertices[ii].position.equals(positionToSearch)) {
  106591. return _this.vertices[ii];
  106592. }
  106593. }
  106594. }
  106595. return null;
  106596. };
  106597. var vertexReferences = [];
  106598. var vertexInit = function (i) {
  106599. if (!positionData) {
  106600. return;
  106601. }
  106602. var offset = i + submesh.verticesStart;
  106603. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  106604. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  106605. vertex.originalOffsets.push(offset);
  106606. if (vertex.id === _this.vertices.length) {
  106607. _this.vertices.push(vertex);
  106608. }
  106609. vertexReferences.push(vertex.id);
  106610. };
  106611. //var totalVertices = mesh.getTotalVertices();
  106612. var totalVertices = submesh.verticesCount;
  106613. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  106614. var indicesInit = function (i) {
  106615. if (!indices) {
  106616. return;
  106617. }
  106618. var offset = (submesh.indexStart / 3) + i;
  106619. var pos = (offset * 3);
  106620. var i0 = indices[pos + 0];
  106621. var i1 = indices[pos + 1];
  106622. var i2 = indices[pos + 2];
  106623. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  106624. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  106625. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  106626. var triangle = new DecimationTriangle([v0, v1, v2]);
  106627. triangle.originalOffset = pos;
  106628. _this.triangles.push(triangle);
  106629. };
  106630. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  106631. _this.init(callback);
  106632. });
  106633. });
  106634. };
  106635. QuadraticErrorSimplification.prototype.init = function (callback) {
  106636. var _this = this;
  106637. var triangleInit1 = function (i) {
  106638. var t = _this.triangles[i];
  106639. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  106640. for (var j = 0; j < 3; j++) {
  106641. 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))));
  106642. }
  106643. };
  106644. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  106645. var triangleInit2 = function (i) {
  106646. var t = _this.triangles[i];
  106647. for (var j = 0; j < 3; ++j) {
  106648. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  106649. }
  106650. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  106651. };
  106652. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  106653. callback();
  106654. });
  106655. });
  106656. };
  106657. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  106658. var newTriangles = [];
  106659. var i;
  106660. for (i = 0; i < this.vertices.length; ++i) {
  106661. this.vertices[i].triangleCount = 0;
  106662. }
  106663. var t;
  106664. var j;
  106665. for (i = 0; i < this.triangles.length; ++i) {
  106666. if (!this.triangles[i].deleted) {
  106667. t = this.triangles[i];
  106668. for (j = 0; j < 3; ++j) {
  106669. t.vertices[j].triangleCount = 1;
  106670. }
  106671. newTriangles.push(t);
  106672. }
  106673. }
  106674. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  106675. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  106676. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  106677. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  106678. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  106679. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  106680. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  106681. var vertexCount = 0;
  106682. for (i = 0; i < this.vertices.length; ++i) {
  106683. var vertex = this.vertices[i];
  106684. vertex.id = vertexCount;
  106685. if (vertex.triangleCount) {
  106686. vertex.originalOffsets.forEach(function (originalOffset) {
  106687. if (!normalData) {
  106688. return;
  106689. }
  106690. newPositionData.push(vertex.position.x);
  106691. newPositionData.push(vertex.position.y);
  106692. newPositionData.push(vertex.position.z);
  106693. newNormalData.push(normalData[originalOffset * 3]);
  106694. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  106695. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  106696. if (uvs && uvs.length) {
  106697. newUVsData.push(uvs[(originalOffset * 2)]);
  106698. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  106699. }
  106700. else if (colorsData && colorsData.length) {
  106701. newColorsData.push(colorsData[(originalOffset * 4)]);
  106702. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  106703. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  106704. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  106705. }
  106706. ++vertexCount;
  106707. });
  106708. }
  106709. }
  106710. var startingIndex = this._reconstructedMesh.getTotalIndices();
  106711. var startingVertex = this._reconstructedMesh.getTotalVertices();
  106712. var submeshesArray = this._reconstructedMesh.subMeshes;
  106713. this._reconstructedMesh.subMeshes = [];
  106714. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  106715. var originalIndices = this._mesh.getIndices();
  106716. for (i = 0; i < newTriangles.length; ++i) {
  106717. t = newTriangles[i]; //now get the new referencing point for each vertex
  106718. [0, 1, 2].forEach(function (idx) {
  106719. var id = originalIndices[t.originalOffset + idx];
  106720. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  106721. if (offset < 0)
  106722. offset = 0;
  106723. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  106724. });
  106725. }
  106726. //overwriting the old vertex buffers and indices.
  106727. this._reconstructedMesh.setIndices(newIndicesArray);
  106728. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  106729. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  106730. if (newUVsData.length > 0)
  106731. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  106732. if (newColorsData.length > 0)
  106733. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  106734. //create submesh
  106735. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  106736. if (submeshIndex > 0) {
  106737. this._reconstructedMesh.subMeshes = [];
  106738. submeshesArray.forEach(function (submesh) {
  106739. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  106740. });
  106741. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  106742. }
  106743. };
  106744. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  106745. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  106746. this._reconstructedMesh.material = this._mesh.material;
  106747. this._reconstructedMesh.parent = this._mesh.parent;
  106748. this._reconstructedMesh.isVisible = false;
  106749. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  106750. };
  106751. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  106752. for (var i = 0; i < vertex1.triangleCount; ++i) {
  106753. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  106754. if (t.deleted)
  106755. continue;
  106756. var s = this.references[vertex1.triangleStart + i].vertexId;
  106757. var v1 = t.vertices[(s + 1) % 3];
  106758. var v2 = t.vertices[(s + 2) % 3];
  106759. if ((v1 === vertex2 || v2 === vertex2)) {
  106760. deletedArray[i] = true;
  106761. delTr.push(t);
  106762. continue;
  106763. }
  106764. var d1 = v1.position.subtract(point);
  106765. d1 = d1.normalize();
  106766. var d2 = v2.position.subtract(point);
  106767. d2 = d2.normalize();
  106768. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  106769. return true;
  106770. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  106771. deletedArray[i] = false;
  106772. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  106773. return true;
  106774. }
  106775. return false;
  106776. };
  106777. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  106778. var newDeleted = deletedTriangles;
  106779. for (var i = 0; i < vertex.triangleCount; ++i) {
  106780. var ref = this.references[vertex.triangleStart + i];
  106781. var t = this.triangles[ref.triangleId];
  106782. if (t.deleted)
  106783. continue;
  106784. if (deletedArray[i] && t.deletePending) {
  106785. t.deleted = true;
  106786. newDeleted++;
  106787. continue;
  106788. }
  106789. t.vertices[ref.vertexId] = origVertex;
  106790. t.isDirty = true;
  106791. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  106792. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  106793. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  106794. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  106795. this.references.push(ref);
  106796. }
  106797. return newDeleted;
  106798. };
  106799. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  106800. for (var i = 0; i < this.vertices.length; ++i) {
  106801. var vCount = [];
  106802. var vId = [];
  106803. var v = this.vertices[i];
  106804. var j;
  106805. for (j = 0; j < v.triangleCount; ++j) {
  106806. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  106807. for (var ii = 0; ii < 3; ii++) {
  106808. var ofs = 0;
  106809. var vv = triangle.vertices[ii];
  106810. while (ofs < vCount.length) {
  106811. if (vId[ofs] === vv.id)
  106812. break;
  106813. ++ofs;
  106814. }
  106815. if (ofs === vCount.length) {
  106816. vCount.push(1);
  106817. vId.push(vv.id);
  106818. }
  106819. else {
  106820. vCount[ofs]++;
  106821. }
  106822. }
  106823. }
  106824. for (j = 0; j < vCount.length; ++j) {
  106825. if (vCount[j] === 1) {
  106826. this.vertices[vId[j]].isBorder = true;
  106827. }
  106828. else {
  106829. this.vertices[vId[j]].isBorder = false;
  106830. }
  106831. }
  106832. }
  106833. };
  106834. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  106835. if (identifyBorders === void 0) { identifyBorders = false; }
  106836. var i;
  106837. if (!identifyBorders) {
  106838. var newTrianglesVector = [];
  106839. for (i = 0; i < this.triangles.length; ++i) {
  106840. if (!this.triangles[i].deleted) {
  106841. newTrianglesVector.push(this.triangles[i]);
  106842. }
  106843. }
  106844. this.triangles = newTrianglesVector;
  106845. }
  106846. for (i = 0; i < this.vertices.length; ++i) {
  106847. this.vertices[i].triangleCount = 0;
  106848. this.vertices[i].triangleStart = 0;
  106849. }
  106850. var t;
  106851. var j;
  106852. var v;
  106853. for (i = 0; i < this.triangles.length; ++i) {
  106854. t = this.triangles[i];
  106855. for (j = 0; j < 3; ++j) {
  106856. v = t.vertices[j];
  106857. v.triangleCount++;
  106858. }
  106859. }
  106860. var tStart = 0;
  106861. for (i = 0; i < this.vertices.length; ++i) {
  106862. this.vertices[i].triangleStart = tStart;
  106863. tStart += this.vertices[i].triangleCount;
  106864. this.vertices[i].triangleCount = 0;
  106865. }
  106866. var newReferences = new Array(this.triangles.length * 3);
  106867. for (i = 0; i < this.triangles.length; ++i) {
  106868. t = this.triangles[i];
  106869. for (j = 0; j < 3; ++j) {
  106870. v = t.vertices[j];
  106871. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  106872. v.triangleCount++;
  106873. }
  106874. }
  106875. this.references = newReferences;
  106876. if (identifyBorders) {
  106877. this.identifyBorder();
  106878. }
  106879. };
  106880. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  106881. var x = point.x;
  106882. var y = point.y;
  106883. var z = point.z;
  106884. 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
  106885. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  106886. };
  106887. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  106888. var q = vertex1.q.add(vertex2.q);
  106889. var border = vertex1.isBorder && vertex2.isBorder;
  106890. var error = 0;
  106891. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  106892. if (qDet !== 0 && !border) {
  106893. if (!pointResult) {
  106894. pointResult = BABYLON.Vector3.Zero();
  106895. }
  106896. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  106897. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  106898. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  106899. error = this.vertexError(q, pointResult);
  106900. }
  106901. else {
  106902. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  106903. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  106904. var error1 = this.vertexError(q, vertex1.position);
  106905. var error2 = this.vertexError(q, vertex2.position);
  106906. var error3 = this.vertexError(q, p3);
  106907. error = Math.min(error1, error2, error3);
  106908. if (error === error1) {
  106909. if (pointResult) {
  106910. pointResult.copyFrom(vertex1.position);
  106911. }
  106912. }
  106913. else if (error === error2) {
  106914. if (pointResult) {
  106915. pointResult.copyFrom(vertex2.position);
  106916. }
  106917. }
  106918. else {
  106919. if (pointResult) {
  106920. pointResult.copyFrom(p3);
  106921. }
  106922. }
  106923. }
  106924. return error;
  106925. };
  106926. return QuadraticErrorSimplification;
  106927. }());
  106928. })(BABYLON || (BABYLON = {}));
  106929. //# sourceMappingURL=babylon.meshSimplification.js.map
  106930. var BABYLON;
  106931. (function (BABYLON) {
  106932. Object.defineProperty(BABYLON.Scene.prototype, "simplificationQueue", {
  106933. get: function () {
  106934. if (!this._simplificationQueue) {
  106935. this._simplificationQueue = new BABYLON.SimplificationQueue();
  106936. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE);
  106937. if (!component) {
  106938. component = new SimplicationQueueSceneComponent(this);
  106939. this._addComponent(component);
  106940. }
  106941. }
  106942. return this._simplificationQueue;
  106943. },
  106944. set: function (value) {
  106945. this._simplificationQueue = value;
  106946. },
  106947. enumerable: true,
  106948. configurable: true
  106949. });
  106950. BABYLON.Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  106951. if (parallelProcessing === void 0) { parallelProcessing = true; }
  106952. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  106953. this.getScene().simplificationQueue.addTask({
  106954. settings: settings,
  106955. parallelProcessing: parallelProcessing,
  106956. mesh: this,
  106957. simplificationType: simplificationType,
  106958. successCallback: successCallback
  106959. });
  106960. return this;
  106961. };
  106962. /**
  106963. * Defines the simplification queue scene component responsible to help scheduling the various simplification task
  106964. * created in a scene
  106965. */
  106966. var SimplicationQueueSceneComponent = /** @class */ (function () {
  106967. /**
  106968. * Creates a new instance of the component for the given scene
  106969. * @param scene Defines the scene to register the component in
  106970. */
  106971. function SimplicationQueueSceneComponent(scene) {
  106972. /**
  106973. * The component name helpfull to identify the component in the list of scene components.
  106974. */
  106975. this.name = BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE;
  106976. this.scene = scene;
  106977. }
  106978. /**
  106979. * Registers the component in a given scene
  106980. */
  106981. SimplicationQueueSceneComponent.prototype.register = function () {
  106982. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE, this, this._beforeCameraUpdate);
  106983. };
  106984. /**
  106985. * Rebuilds the elements related to this component in case of
  106986. * context lost for instance.
  106987. */
  106988. SimplicationQueueSceneComponent.prototype.rebuild = function () {
  106989. // Nothing to do for this component
  106990. };
  106991. /**
  106992. * Disposes the component and the associated ressources
  106993. */
  106994. SimplicationQueueSceneComponent.prototype.dispose = function () {
  106995. // Nothing to do for this component
  106996. };
  106997. SimplicationQueueSceneComponent.prototype._beforeCameraUpdate = function () {
  106998. if (this.scene._simplificationQueue && !this.scene._simplificationQueue.running) {
  106999. this.scene._simplificationQueue.executeNext();
  107000. }
  107001. };
  107002. return SimplicationQueueSceneComponent;
  107003. }());
  107004. BABYLON.SimplicationQueueSceneComponent = SimplicationQueueSceneComponent;
  107005. })(BABYLON || (BABYLON = {}));
  107006. //# sourceMappingURL=babylon.meshSimplificationSceneComponent.js.map
  107007. var BABYLON;
  107008. (function (BABYLON) {
  107009. /**
  107010. * Class used to represent a specific level of detail of a mesh
  107011. * @see http://doc.babylonjs.com/how_to/how_to_use_lod
  107012. */
  107013. var MeshLODLevel = /** @class */ (function () {
  107014. /**
  107015. * Creates a new LOD level
  107016. * @param distance defines the distance where this level should star being displayed
  107017. * @param mesh defines the mesh to use to render this level
  107018. */
  107019. function MeshLODLevel(
  107020. /** Defines the distance where this level should star being displayed */
  107021. distance,
  107022. /** Defines the mesh to use to render this level */
  107023. mesh) {
  107024. this.distance = distance;
  107025. this.mesh = mesh;
  107026. }
  107027. return MeshLODLevel;
  107028. }());
  107029. BABYLON.MeshLODLevel = MeshLODLevel;
  107030. })(BABYLON || (BABYLON = {}));
  107031. //# sourceMappingURL=babylon.meshLODLevel.js.map
  107032. var BABYLON;
  107033. (function (BABYLON) {
  107034. /**
  107035. * Defines the root class used to create scene optimization to use with SceneOptimizer
  107036. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  107037. */
  107038. var SceneOptimization = /** @class */ (function () {
  107039. /**
  107040. * Creates the SceneOptimization object
  107041. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  107042. * @param desc defines the description associated with the optimization
  107043. */
  107044. function SceneOptimization(
  107045. /**
  107046. * Defines the priority of this optimization (0 by default which means first in the list)
  107047. */
  107048. priority) {
  107049. if (priority === void 0) { priority = 0; }
  107050. this.priority = priority;
  107051. }
  107052. /**
  107053. * Gets a string describing the action executed by the current optimization
  107054. * @returns description string
  107055. */
  107056. SceneOptimization.prototype.getDescription = function () {
  107057. return "";
  107058. };
  107059. /**
  107060. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  107061. * @param scene defines the current scene where to apply this optimization
  107062. * @param optimizer defines the current optimizer
  107063. * @returns true if everything that can be done was applied
  107064. */
  107065. SceneOptimization.prototype.apply = function (scene, optimizer) {
  107066. return true;
  107067. };
  107068. ;
  107069. return SceneOptimization;
  107070. }());
  107071. BABYLON.SceneOptimization = SceneOptimization;
  107072. /**
  107073. * Defines an optimization used to reduce the size of render target textures
  107074. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  107075. */
  107076. var TextureOptimization = /** @class */ (function (_super) {
  107077. __extends(TextureOptimization, _super);
  107078. /**
  107079. * Creates the TextureOptimization object
  107080. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  107081. * @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
  107082. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  107083. */
  107084. function TextureOptimization(
  107085. /**
  107086. * Defines the priority of this optimization (0 by default which means first in the list)
  107087. */
  107088. priority,
  107089. /**
  107090. * 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
  107091. */
  107092. maximumSize,
  107093. /**
  107094. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  107095. */
  107096. step) {
  107097. if (priority === void 0) { priority = 0; }
  107098. if (maximumSize === void 0) { maximumSize = 1024; }
  107099. if (step === void 0) { step = 0.5; }
  107100. var _this = _super.call(this, priority) || this;
  107101. _this.priority = priority;
  107102. _this.maximumSize = maximumSize;
  107103. _this.step = step;
  107104. return _this;
  107105. }
  107106. /**
  107107. * Gets a string describing the action executed by the current optimization
  107108. * @returns description string
  107109. */
  107110. TextureOptimization.prototype.getDescription = function () {
  107111. return "Reducing render target texture size to " + this.maximumSize;
  107112. };
  107113. /**
  107114. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  107115. * @param scene defines the current scene where to apply this optimization
  107116. * @param optimizer defines the current optimizer
  107117. * @returns true if everything that can be done was applied
  107118. */
  107119. TextureOptimization.prototype.apply = function (scene, optimizer) {
  107120. var allDone = true;
  107121. for (var index = 0; index < scene.textures.length; index++) {
  107122. var texture = scene.textures[index];
  107123. if (!texture.canRescale || texture.getContext) {
  107124. continue;
  107125. }
  107126. var currentSize = texture.getSize();
  107127. var maxDimension = Math.max(currentSize.width, currentSize.height);
  107128. if (maxDimension > this.maximumSize) {
  107129. texture.scale(this.step);
  107130. allDone = false;
  107131. }
  107132. }
  107133. return allDone;
  107134. };
  107135. return TextureOptimization;
  107136. }(SceneOptimization));
  107137. BABYLON.TextureOptimization = TextureOptimization;
  107138. /**
  107139. * Defines an optimization used to increase or decrease the rendering resolution
  107140. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  107141. */
  107142. var HardwareScalingOptimization = /** @class */ (function (_super) {
  107143. __extends(HardwareScalingOptimization, _super);
  107144. /**
  107145. * Creates the HardwareScalingOptimization object
  107146. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  107147. * @param maximumScale defines the maximum scale to use (2 by default)
  107148. * @param step defines the step to use between two passes (0.5 by default)
  107149. */
  107150. function HardwareScalingOptimization(
  107151. /**
  107152. * Defines the priority of this optimization (0 by default which means first in the list)
  107153. */
  107154. priority,
  107155. /**
  107156. * Defines the maximum scale to use (2 by default)
  107157. */
  107158. maximumScale,
  107159. /**
  107160. * Defines the step to use between two passes (0.5 by default)
  107161. */
  107162. step) {
  107163. if (priority === void 0) { priority = 0; }
  107164. if (maximumScale === void 0) { maximumScale = 2; }
  107165. if (step === void 0) { step = 0.25; }
  107166. var _this = _super.call(this, priority) || this;
  107167. _this.priority = priority;
  107168. _this.maximumScale = maximumScale;
  107169. _this.step = step;
  107170. _this._currentScale = -1;
  107171. _this._directionOffset = 1;
  107172. return _this;
  107173. }
  107174. /**
  107175. * Gets a string describing the action executed by the current optimization
  107176. * @return description string
  107177. */
  107178. HardwareScalingOptimization.prototype.getDescription = function () {
  107179. return "Setting hardware scaling level to " + this._currentScale;
  107180. };
  107181. /**
  107182. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  107183. * @param scene defines the current scene where to apply this optimization
  107184. * @param optimizer defines the current optimizer
  107185. * @returns true if everything that can be done was applied
  107186. */
  107187. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  107188. if (this._currentScale === -1) {
  107189. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  107190. if (this._currentScale > this.maximumScale) {
  107191. this._directionOffset = -1;
  107192. }
  107193. }
  107194. this._currentScale += this._directionOffset * this.step;
  107195. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  107196. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  107197. };
  107198. ;
  107199. return HardwareScalingOptimization;
  107200. }(SceneOptimization));
  107201. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  107202. /**
  107203. * Defines an optimization used to remove shadows
  107204. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  107205. */
  107206. var ShadowsOptimization = /** @class */ (function (_super) {
  107207. __extends(ShadowsOptimization, _super);
  107208. function ShadowsOptimization() {
  107209. return _super !== null && _super.apply(this, arguments) || this;
  107210. }
  107211. /**
  107212. * Gets a string describing the action executed by the current optimization
  107213. * @return description string
  107214. */
  107215. ShadowsOptimization.prototype.getDescription = function () {
  107216. return "Turning shadows on/off";
  107217. };
  107218. /**
  107219. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  107220. * @param scene defines the current scene where to apply this optimization
  107221. * @param optimizer defines the current optimizer
  107222. * @returns true if everything that can be done was applied
  107223. */
  107224. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  107225. scene.shadowsEnabled = optimizer.isInImprovementMode;
  107226. return true;
  107227. };
  107228. ;
  107229. return ShadowsOptimization;
  107230. }(SceneOptimization));
  107231. BABYLON.ShadowsOptimization = ShadowsOptimization;
  107232. /**
  107233. * Defines an optimization used to turn post-processes off
  107234. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  107235. */
  107236. var PostProcessesOptimization = /** @class */ (function (_super) {
  107237. __extends(PostProcessesOptimization, _super);
  107238. function PostProcessesOptimization() {
  107239. return _super !== null && _super.apply(this, arguments) || this;
  107240. }
  107241. /**
  107242. * Gets a string describing the action executed by the current optimization
  107243. * @return description string
  107244. */
  107245. PostProcessesOptimization.prototype.getDescription = function () {
  107246. return "Turning post-processes on/off";
  107247. };
  107248. /**
  107249. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  107250. * @param scene defines the current scene where to apply this optimization
  107251. * @param optimizer defines the current optimizer
  107252. * @returns true if everything that can be done was applied
  107253. */
  107254. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  107255. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  107256. return true;
  107257. };
  107258. ;
  107259. return PostProcessesOptimization;
  107260. }(SceneOptimization));
  107261. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  107262. /**
  107263. * Defines an optimization used to turn lens flares off
  107264. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  107265. */
  107266. var LensFlaresOptimization = /** @class */ (function (_super) {
  107267. __extends(LensFlaresOptimization, _super);
  107268. function LensFlaresOptimization() {
  107269. return _super !== null && _super.apply(this, arguments) || this;
  107270. }
  107271. /**
  107272. * Gets a string describing the action executed by the current optimization
  107273. * @return description string
  107274. */
  107275. LensFlaresOptimization.prototype.getDescription = function () {
  107276. return "Turning lens flares on/off";
  107277. };
  107278. /**
  107279. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  107280. * @param scene defines the current scene where to apply this optimization
  107281. * @param optimizer defines the current optimizer
  107282. * @returns true if everything that can be done was applied
  107283. */
  107284. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  107285. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  107286. return true;
  107287. };
  107288. ;
  107289. return LensFlaresOptimization;
  107290. }(SceneOptimization));
  107291. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  107292. /**
  107293. * Defines an optimization based on user defined callback.
  107294. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  107295. */
  107296. var CustomOptimization = /** @class */ (function (_super) {
  107297. __extends(CustomOptimization, _super);
  107298. function CustomOptimization() {
  107299. return _super !== null && _super.apply(this, arguments) || this;
  107300. }
  107301. /**
  107302. * Gets a string describing the action executed by the current optimization
  107303. * @returns description string
  107304. */
  107305. CustomOptimization.prototype.getDescription = function () {
  107306. if (this.onGetDescription) {
  107307. return this.onGetDescription();
  107308. }
  107309. return "Running user defined callback";
  107310. };
  107311. /**
  107312. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  107313. * @param scene defines the current scene where to apply this optimization
  107314. * @param optimizer defines the current optimizer
  107315. * @returns true if everything that can be done was applied
  107316. */
  107317. CustomOptimization.prototype.apply = function (scene, optimizer) {
  107318. if (this.onApply) {
  107319. return this.onApply(scene, optimizer);
  107320. }
  107321. return true;
  107322. };
  107323. ;
  107324. return CustomOptimization;
  107325. }(SceneOptimization));
  107326. BABYLON.CustomOptimization = CustomOptimization;
  107327. /**
  107328. * Defines an optimization used to turn particles off
  107329. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  107330. */
  107331. var ParticlesOptimization = /** @class */ (function (_super) {
  107332. __extends(ParticlesOptimization, _super);
  107333. function ParticlesOptimization() {
  107334. return _super !== null && _super.apply(this, arguments) || this;
  107335. }
  107336. /**
  107337. * Gets a string describing the action executed by the current optimization
  107338. * @return description string
  107339. */
  107340. ParticlesOptimization.prototype.getDescription = function () {
  107341. return "Turning particles on/off";
  107342. };
  107343. /**
  107344. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  107345. * @param scene defines the current scene where to apply this optimization
  107346. * @param optimizer defines the current optimizer
  107347. * @returns true if everything that can be done was applied
  107348. */
  107349. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  107350. scene.particlesEnabled = optimizer.isInImprovementMode;
  107351. return true;
  107352. };
  107353. ;
  107354. return ParticlesOptimization;
  107355. }(SceneOptimization));
  107356. BABYLON.ParticlesOptimization = ParticlesOptimization;
  107357. /**
  107358. * Defines an optimization used to turn render targets off
  107359. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  107360. */
  107361. var RenderTargetsOptimization = /** @class */ (function (_super) {
  107362. __extends(RenderTargetsOptimization, _super);
  107363. function RenderTargetsOptimization() {
  107364. return _super !== null && _super.apply(this, arguments) || this;
  107365. }
  107366. /**
  107367. * Gets a string describing the action executed by the current optimization
  107368. * @return description string
  107369. */
  107370. RenderTargetsOptimization.prototype.getDescription = function () {
  107371. return "Turning render targets off";
  107372. };
  107373. /**
  107374. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  107375. * @param scene defines the current scene where to apply this optimization
  107376. * @param optimizer defines the current optimizer
  107377. * @returns true if everything that can be done was applied
  107378. */
  107379. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  107380. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  107381. return true;
  107382. };
  107383. ;
  107384. return RenderTargetsOptimization;
  107385. }(SceneOptimization));
  107386. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  107387. /**
  107388. * Defines an optimization used to merge meshes with compatible materials
  107389. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  107390. */
  107391. var MergeMeshesOptimization = /** @class */ (function (_super) {
  107392. __extends(MergeMeshesOptimization, _super);
  107393. function MergeMeshesOptimization() {
  107394. var _this = _super !== null && _super.apply(this, arguments) || this;
  107395. _this._canBeMerged = function (abstractMesh) {
  107396. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  107397. return false;
  107398. }
  107399. var mesh = abstractMesh;
  107400. if (mesh.isDisposed()) {
  107401. return false;
  107402. }
  107403. if (!mesh.isVisible || !mesh.isEnabled()) {
  107404. return false;
  107405. }
  107406. if (mesh.instances.length > 0) {
  107407. return false;
  107408. }
  107409. if (mesh.skeleton || mesh.hasLODLevels) {
  107410. return false;
  107411. }
  107412. return true;
  107413. };
  107414. return _this;
  107415. }
  107416. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  107417. /**
  107418. * Gets or sets a boolean which defines if optimization octree has to be updated
  107419. */
  107420. get: function () {
  107421. return MergeMeshesOptimization._UpdateSelectionTree;
  107422. },
  107423. /**
  107424. * Gets or sets a boolean which defines if optimization octree has to be updated
  107425. */
  107426. set: function (value) {
  107427. MergeMeshesOptimization._UpdateSelectionTree = value;
  107428. },
  107429. enumerable: true,
  107430. configurable: true
  107431. });
  107432. /**
  107433. * Gets a string describing the action executed by the current optimization
  107434. * @return description string
  107435. */
  107436. MergeMeshesOptimization.prototype.getDescription = function () {
  107437. return "Merging similar meshes together";
  107438. };
  107439. /**
  107440. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  107441. * @param scene defines the current scene where to apply this optimization
  107442. * @param optimizer defines the current optimizer
  107443. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  107444. * @returns true if everything that can be done was applied
  107445. */
  107446. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  107447. var globalPool = scene.meshes.slice(0);
  107448. var globalLength = globalPool.length;
  107449. for (var index = 0; index < globalLength; index++) {
  107450. var currentPool = new Array();
  107451. var current = globalPool[index];
  107452. // Checks
  107453. if (!this._canBeMerged(current)) {
  107454. continue;
  107455. }
  107456. currentPool.push(current);
  107457. // Find compatible meshes
  107458. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  107459. var otherMesh = globalPool[subIndex];
  107460. if (!this._canBeMerged(otherMesh)) {
  107461. continue;
  107462. }
  107463. if (otherMesh.material !== current.material) {
  107464. continue;
  107465. }
  107466. if (otherMesh.checkCollisions !== current.checkCollisions) {
  107467. continue;
  107468. }
  107469. currentPool.push(otherMesh);
  107470. globalLength--;
  107471. globalPool.splice(subIndex, 1);
  107472. subIndex--;
  107473. }
  107474. if (currentPool.length < 2) {
  107475. continue;
  107476. }
  107477. // Merge meshes
  107478. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  107479. }
  107480. // Call the octree system optimization if it is defined.
  107481. var sceneAsAny = scene;
  107482. if (sceneAsAny.createOrUpdateSelectionOctree) {
  107483. if (updateSelectionTree != undefined) {
  107484. if (updateSelectionTree) {
  107485. sceneAsAny.createOrUpdateSelectionOctree();
  107486. }
  107487. }
  107488. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  107489. sceneAsAny.createOrUpdateSelectionOctree();
  107490. }
  107491. }
  107492. return true;
  107493. };
  107494. ;
  107495. MergeMeshesOptimization._UpdateSelectionTree = false;
  107496. return MergeMeshesOptimization;
  107497. }(SceneOptimization));
  107498. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  107499. /**
  107500. * Defines a list of options used by SceneOptimizer
  107501. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  107502. */
  107503. var SceneOptimizerOptions = /** @class */ (function () {
  107504. /**
  107505. * Creates a new list of options used by SceneOptimizer
  107506. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  107507. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  107508. */
  107509. function SceneOptimizerOptions(
  107510. /**
  107511. * Defines the target frame rate to reach (60 by default)
  107512. */
  107513. targetFrameRate,
  107514. /**
  107515. * Defines the interval between two checkes (2000ms by default)
  107516. */
  107517. trackerDuration) {
  107518. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  107519. if (trackerDuration === void 0) { trackerDuration = 2000; }
  107520. this.targetFrameRate = targetFrameRate;
  107521. this.trackerDuration = trackerDuration;
  107522. /**
  107523. * Gets the list of optimizations to apply
  107524. */
  107525. this.optimizations = new Array();
  107526. }
  107527. /**
  107528. * Add a new optimization
  107529. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  107530. * @returns the current SceneOptimizerOptions
  107531. */
  107532. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  107533. this.optimizations.push(optimization);
  107534. return this;
  107535. };
  107536. /**
  107537. * Add a new custom optimization
  107538. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  107539. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  107540. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  107541. * @returns the current SceneOptimizerOptions
  107542. */
  107543. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  107544. if (priority === void 0) { priority = 0; }
  107545. var optimization = new CustomOptimization(priority);
  107546. optimization.onApply = onApply;
  107547. optimization.onGetDescription = onGetDescription;
  107548. this.optimizations.push(optimization);
  107549. return this;
  107550. };
  107551. /**
  107552. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  107553. * @param targetFrameRate defines the target frame rate (60 by default)
  107554. * @returns a SceneOptimizerOptions object
  107555. */
  107556. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  107557. var result = new SceneOptimizerOptions(targetFrameRate);
  107558. var priority = 0;
  107559. result.addOptimization(new MergeMeshesOptimization(priority));
  107560. result.addOptimization(new ShadowsOptimization(priority));
  107561. result.addOptimization(new LensFlaresOptimization(priority));
  107562. // Next priority
  107563. priority++;
  107564. result.addOptimization(new PostProcessesOptimization(priority));
  107565. result.addOptimization(new ParticlesOptimization(priority));
  107566. // Next priority
  107567. priority++;
  107568. result.addOptimization(new TextureOptimization(priority, 1024));
  107569. return result;
  107570. };
  107571. /**
  107572. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  107573. * @param targetFrameRate defines the target frame rate (60 by default)
  107574. * @returns a SceneOptimizerOptions object
  107575. */
  107576. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  107577. var result = new SceneOptimizerOptions(targetFrameRate);
  107578. var priority = 0;
  107579. result.addOptimization(new MergeMeshesOptimization(priority));
  107580. result.addOptimization(new ShadowsOptimization(priority));
  107581. result.addOptimization(new LensFlaresOptimization(priority));
  107582. // Next priority
  107583. priority++;
  107584. result.addOptimization(new PostProcessesOptimization(priority));
  107585. result.addOptimization(new ParticlesOptimization(priority));
  107586. // Next priority
  107587. priority++;
  107588. result.addOptimization(new TextureOptimization(priority, 512));
  107589. // Next priority
  107590. priority++;
  107591. result.addOptimization(new RenderTargetsOptimization(priority));
  107592. // Next priority
  107593. priority++;
  107594. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  107595. return result;
  107596. };
  107597. /**
  107598. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  107599. * @param targetFrameRate defines the target frame rate (60 by default)
  107600. * @returns a SceneOptimizerOptions object
  107601. */
  107602. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  107603. var result = new SceneOptimizerOptions(targetFrameRate);
  107604. var priority = 0;
  107605. result.addOptimization(new MergeMeshesOptimization(priority));
  107606. result.addOptimization(new ShadowsOptimization(priority));
  107607. result.addOptimization(new LensFlaresOptimization(priority));
  107608. // Next priority
  107609. priority++;
  107610. result.addOptimization(new PostProcessesOptimization(priority));
  107611. result.addOptimization(new ParticlesOptimization(priority));
  107612. // Next priority
  107613. priority++;
  107614. result.addOptimization(new TextureOptimization(priority, 256));
  107615. // Next priority
  107616. priority++;
  107617. result.addOptimization(new RenderTargetsOptimization(priority));
  107618. // Next priority
  107619. priority++;
  107620. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  107621. return result;
  107622. };
  107623. return SceneOptimizerOptions;
  107624. }());
  107625. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  107626. /**
  107627. * Class used to run optimizations in order to reach a target frame rate
  107628. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  107629. */
  107630. var SceneOptimizer = /** @class */ (function () {
  107631. /**
  107632. * Creates a new SceneOptimizer
  107633. * @param scene defines the scene to work on
  107634. * @param options defines the options to use with the SceneOptimizer
  107635. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  107636. * @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)
  107637. */
  107638. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  107639. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  107640. if (improvementMode === void 0) { improvementMode = false; }
  107641. var _this = this;
  107642. this._isRunning = false;
  107643. this._currentPriorityLevel = 0;
  107644. this._targetFrameRate = 60;
  107645. this._trackerDuration = 2000;
  107646. this._currentFrameRate = 0;
  107647. this._improvementMode = false;
  107648. /**
  107649. * Defines an observable called when the optimizer reaches the target frame rate
  107650. */
  107651. this.onSuccessObservable = new BABYLON.Observable();
  107652. /**
  107653. * Defines an observable called when the optimizer enables an optimization
  107654. */
  107655. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  107656. /**
  107657. * Defines an observable called when the optimizer is not able to reach the target frame rate
  107658. */
  107659. this.onFailureObservable = new BABYLON.Observable();
  107660. if (!options) {
  107661. this._options = new SceneOptimizerOptions();
  107662. }
  107663. else {
  107664. this._options = options;
  107665. }
  107666. if (this._options.targetFrameRate) {
  107667. this._targetFrameRate = this._options.targetFrameRate;
  107668. }
  107669. if (this._options.trackerDuration) {
  107670. this._trackerDuration = this._options.trackerDuration;
  107671. }
  107672. if (autoGeneratePriorities) {
  107673. var priority = 0;
  107674. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  107675. var optim = _a[_i];
  107676. optim.priority = priority++;
  107677. }
  107678. }
  107679. this._improvementMode = improvementMode;
  107680. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  107681. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  107682. _this._sceneDisposeObserver = null;
  107683. _this.dispose();
  107684. });
  107685. }
  107686. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  107687. /**
  107688. * Gets a boolean indicating if the optimizer is in improvement mode
  107689. */
  107690. get: function () {
  107691. return this._improvementMode;
  107692. },
  107693. enumerable: true,
  107694. configurable: true
  107695. });
  107696. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  107697. /**
  107698. * Gets the current priority level (0 at start)
  107699. */
  107700. get: function () {
  107701. return this._currentPriorityLevel;
  107702. },
  107703. enumerable: true,
  107704. configurable: true
  107705. });
  107706. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  107707. /**
  107708. * Gets the current frame rate checked by the SceneOptimizer
  107709. */
  107710. get: function () {
  107711. return this._currentFrameRate;
  107712. },
  107713. enumerable: true,
  107714. configurable: true
  107715. });
  107716. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  107717. /**
  107718. * Gets or sets the current target frame rate (60 by default)
  107719. */
  107720. get: function () {
  107721. return this._targetFrameRate;
  107722. },
  107723. /**
  107724. * Gets or sets the current target frame rate (60 by default)
  107725. */
  107726. set: function (value) {
  107727. this._targetFrameRate = value;
  107728. },
  107729. enumerable: true,
  107730. configurable: true
  107731. });
  107732. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  107733. /**
  107734. * Gets or sets the current interval between two checks (every 2000ms by default)
  107735. */
  107736. get: function () {
  107737. return this._trackerDuration;
  107738. },
  107739. /**
  107740. * Gets or sets the current interval between two checks (every 2000ms by default)
  107741. */
  107742. set: function (value) {
  107743. this._trackerDuration = value;
  107744. },
  107745. enumerable: true,
  107746. configurable: true
  107747. });
  107748. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  107749. /**
  107750. * Gets the list of active optimizations
  107751. */
  107752. get: function () {
  107753. return this._options.optimizations;
  107754. },
  107755. enumerable: true,
  107756. configurable: true
  107757. });
  107758. /**
  107759. * Stops the current optimizer
  107760. */
  107761. SceneOptimizer.prototype.stop = function () {
  107762. this._isRunning = false;
  107763. };
  107764. /**
  107765. * Reset the optimizer to initial step (current priority level = 0)
  107766. */
  107767. SceneOptimizer.prototype.reset = function () {
  107768. this._currentPriorityLevel = 0;
  107769. };
  107770. /**
  107771. * Start the optimizer. By default it will try to reach a specific framerate
  107772. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  107773. */
  107774. SceneOptimizer.prototype.start = function () {
  107775. var _this = this;
  107776. if (this._isRunning) {
  107777. return;
  107778. }
  107779. this._isRunning = true;
  107780. // Let's wait for the scene to be ready before running our check
  107781. this._scene.executeWhenReady(function () {
  107782. setTimeout(function () {
  107783. _this._checkCurrentState();
  107784. }, _this._trackerDuration);
  107785. });
  107786. };
  107787. SceneOptimizer.prototype._checkCurrentState = function () {
  107788. var _this = this;
  107789. if (!this._isRunning) {
  107790. return;
  107791. }
  107792. var scene = this._scene;
  107793. var options = this._options;
  107794. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  107795. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  107796. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  107797. this._isRunning = false;
  107798. this.onSuccessObservable.notifyObservers(this);
  107799. return;
  107800. }
  107801. // Apply current level of optimizations
  107802. var allDone = true;
  107803. var noOptimizationApplied = true;
  107804. for (var index = 0; index < options.optimizations.length; index++) {
  107805. var optimization = options.optimizations[index];
  107806. if (optimization.priority === this._currentPriorityLevel) {
  107807. noOptimizationApplied = false;
  107808. allDone = allDone && optimization.apply(scene, this);
  107809. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  107810. }
  107811. }
  107812. // If no optimization was applied, this is a failure :(
  107813. if (noOptimizationApplied) {
  107814. this._isRunning = false;
  107815. this.onFailureObservable.notifyObservers(this);
  107816. return;
  107817. }
  107818. // If all optimizations were done, move to next level
  107819. if (allDone) {
  107820. this._currentPriorityLevel++;
  107821. }
  107822. // Let's the system running for a specific amount of time before checking FPS
  107823. scene.executeWhenReady(function () {
  107824. setTimeout(function () {
  107825. _this._checkCurrentState();
  107826. }, _this._trackerDuration);
  107827. });
  107828. };
  107829. /**
  107830. * Release all resources
  107831. */
  107832. SceneOptimizer.prototype.dispose = function () {
  107833. this.stop();
  107834. this.onSuccessObservable.clear();
  107835. this.onFailureObservable.clear();
  107836. this.onNewOptimizationAppliedObservable.clear();
  107837. if (this._sceneDisposeObserver) {
  107838. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  107839. }
  107840. };
  107841. /**
  107842. * Helper function to create a SceneOptimizer with one single line of code
  107843. * @param scene defines the scene to work on
  107844. * @param options defines the options to use with the SceneOptimizer
  107845. * @param onSuccess defines a callback to call on success
  107846. * @param onFailure defines a callback to call on failure
  107847. * @returns the new SceneOptimizer object
  107848. */
  107849. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  107850. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  107851. if (onSuccess) {
  107852. optimizer.onSuccessObservable.add(function () {
  107853. onSuccess();
  107854. });
  107855. }
  107856. if (onFailure) {
  107857. optimizer.onFailureObservable.add(function () {
  107858. onFailure();
  107859. });
  107860. }
  107861. optimizer.start();
  107862. return optimizer;
  107863. };
  107864. return SceneOptimizer;
  107865. }());
  107866. BABYLON.SceneOptimizer = SceneOptimizer;
  107867. })(BABYLON || (BABYLON = {}));
  107868. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  107869. var BABYLON;
  107870. (function (BABYLON) {
  107871. /**
  107872. * Gets the outline renderer associated with the scene
  107873. * @returns a OutlineRenderer
  107874. */
  107875. BABYLON.Scene.prototype.getOutlineRenderer = function () {
  107876. if (!this._outlineRenderer) {
  107877. this._outlineRenderer = new OutlineRenderer(this);
  107878. }
  107879. return this._outlineRenderer;
  107880. };
  107881. Object.defineProperty(BABYLON.AbstractMesh.prototype, "renderOutline", {
  107882. get: function () {
  107883. return this._renderOutline;
  107884. },
  107885. set: function (value) {
  107886. if (value) {
  107887. // Lazy Load the component.
  107888. this.getScene().getOutlineRenderer();
  107889. }
  107890. this._renderOutline = value;
  107891. },
  107892. enumerable: true,
  107893. configurable: true
  107894. });
  107895. Object.defineProperty(BABYLON.AbstractMesh.prototype, "renderOverlay", {
  107896. get: function () {
  107897. return this._renderOverlay;
  107898. },
  107899. set: function (value) {
  107900. if (value) {
  107901. // Lazy Load the component.
  107902. this.getScene().getOutlineRenderer();
  107903. }
  107904. this._renderOverlay = value;
  107905. },
  107906. enumerable: true,
  107907. configurable: true
  107908. });
  107909. /**
  107910. * This class is responsible to draw bothe outline/overlay of meshes.
  107911. * It should not be used directly but through the available method on mesh.
  107912. */
  107913. var OutlineRenderer = /** @class */ (function () {
  107914. /**
  107915. * Instantiates a new outline renderer. (There could be only one per scene).
  107916. * @param scene Defines the scene it belongs to
  107917. */
  107918. function OutlineRenderer(scene) {
  107919. /**
  107920. * The name of the component. Each component must have a unique name.
  107921. */
  107922. this.name = BABYLON.SceneComponentConstants.NAME_OUTLINERENDERER;
  107923. /**
  107924. * Defines a zOffset to prevent zFighting between the overlay and the mesh.
  107925. */
  107926. this.zOffset = 1;
  107927. this.scene = scene;
  107928. this._engine = scene.getEngine();
  107929. this.scene._addComponent(this);
  107930. }
  107931. /**
  107932. * Register the component to one instance of a scene.
  107933. */
  107934. OutlineRenderer.prototype.register = function () {
  107935. this.scene._beforeRenderingMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE, this, this._beforeRenderingMesh);
  107936. this.scene._afterRenderingMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE, this, this._afterRenderingMesh);
  107937. };
  107938. /**
  107939. * Rebuilds the elements related to this component in case of
  107940. * context lost for instance.
  107941. */
  107942. OutlineRenderer.prototype.rebuild = function () {
  107943. // Nothing to do here.
  107944. };
  107945. /**
  107946. * Disposes the component and the associated ressources.
  107947. */
  107948. OutlineRenderer.prototype.dispose = function () {
  107949. // Nothing to do here.
  107950. };
  107951. /**
  107952. * Renders the outline in the canvas.
  107953. * @param subMesh Defines the sumesh to render
  107954. * @param batch Defines the batch of meshes in case of instances
  107955. * @param useOverlay Defines if the rendering is for the overlay or the outline
  107956. */
  107957. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  107958. var _this = this;
  107959. if (useOverlay === void 0) { useOverlay = false; }
  107960. var scene = this.scene;
  107961. var engine = scene.getEngine();
  107962. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  107963. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  107964. return;
  107965. }
  107966. var mesh = subMesh.getRenderingMesh();
  107967. var material = subMesh.getMaterial();
  107968. if (!material || !scene.activeCamera) {
  107969. return;
  107970. }
  107971. engine.enableEffect(this._effect);
  107972. // Logarithmic depth
  107973. if (material.useLogarithmicDepth) {
  107974. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  107975. }
  107976. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  107977. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  107978. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  107979. // Bones
  107980. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  107981. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  107982. }
  107983. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  107984. // Alpha test
  107985. if (material && material.needAlphaTesting()) {
  107986. var alphaTexture = material.getAlphaTestTexture();
  107987. if (alphaTexture) {
  107988. this._effect.setTexture("diffuseSampler", alphaTexture);
  107989. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  107990. }
  107991. }
  107992. engine.setZOffset(-this.zOffset);
  107993. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  107994. engine.setZOffset(0);
  107995. };
  107996. /**
  107997. * Returns whether or not the outline renderer is ready for a given submesh.
  107998. * All the dependencies e.g. submeshes, texture, effect... mus be ready
  107999. * @param subMesh Defines the submesh to check readyness for
  108000. * @param useInstances Defines wheter wee are trying to render instances or not
  108001. * @returns true if ready otherwise false
  108002. */
  108003. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  108004. var defines = [];
  108005. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  108006. var mesh = subMesh.getMesh();
  108007. var material = subMesh.getMaterial();
  108008. if (material) {
  108009. // Alpha test
  108010. if (material.needAlphaTesting()) {
  108011. defines.push("#define ALPHATEST");
  108012. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  108013. attribs.push(BABYLON.VertexBuffer.UVKind);
  108014. defines.push("#define UV1");
  108015. }
  108016. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  108017. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  108018. defines.push("#define UV2");
  108019. }
  108020. }
  108021. //Logarithmic depth
  108022. if (material.useLogarithmicDepth) {
  108023. defines.push("#define LOGARITHMICDEPTH");
  108024. }
  108025. }
  108026. // Bones
  108027. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  108028. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  108029. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  108030. if (mesh.numBoneInfluencers > 4) {
  108031. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  108032. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  108033. }
  108034. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  108035. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  108036. }
  108037. else {
  108038. defines.push("#define NUM_BONE_INFLUENCERS 0");
  108039. }
  108040. // Instances
  108041. if (useInstances) {
  108042. defines.push("#define INSTANCES");
  108043. attribs.push("world0");
  108044. attribs.push("world1");
  108045. attribs.push("world2");
  108046. attribs.push("world3");
  108047. }
  108048. // Get correct effect
  108049. var join = defines.join("\n");
  108050. if (this._cachedDefines !== join) {
  108051. this._cachedDefines = join;
  108052. this._effect = this.scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  108053. }
  108054. return this._effect.isReady();
  108055. };
  108056. OutlineRenderer.prototype._beforeRenderingMesh = function (mesh, subMesh, batch) {
  108057. // Outline - step 1
  108058. this._savedDepthWrite = this._engine.getDepthWrite();
  108059. if (mesh.renderOutline) {
  108060. this._engine.setDepthWrite(false);
  108061. this.render(subMesh, batch);
  108062. this._engine.setDepthWrite(this._savedDepthWrite);
  108063. }
  108064. };
  108065. OutlineRenderer.prototype._afterRenderingMesh = function (mesh, subMesh, batch) {
  108066. // Outline - step 2
  108067. if (mesh.renderOutline && this._savedDepthWrite) {
  108068. this._engine.setDepthWrite(true);
  108069. this._engine.setColorWrite(false);
  108070. this.render(subMesh, batch);
  108071. this._engine.setColorWrite(true);
  108072. }
  108073. // Overlay
  108074. if (mesh.renderOverlay) {
  108075. var currentMode = this._engine.getAlphaMode();
  108076. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  108077. this.render(subMesh, batch, true);
  108078. this._engine.setAlphaMode(currentMode);
  108079. }
  108080. };
  108081. return OutlineRenderer;
  108082. }());
  108083. BABYLON.OutlineRenderer = OutlineRenderer;
  108084. })(BABYLON || (BABYLON = {}));
  108085. //# sourceMappingURL=babylon.outlineRenderer.js.map
  108086. var BABYLON;
  108087. (function (BABYLON) {
  108088. BABYLON.AbstractMesh.prototype.disableEdgesRendering = function () {
  108089. if (this._edgesRenderer) {
  108090. this._edgesRenderer.dispose();
  108091. this._edgesRenderer = null;
  108092. }
  108093. return this;
  108094. };
  108095. BABYLON.AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  108096. if (epsilon === void 0) { epsilon = 0.95; }
  108097. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  108098. this.disableEdgesRendering();
  108099. this._edgesRenderer = new EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  108100. return this;
  108101. };
  108102. Object.defineProperty(BABYLON.AbstractMesh.prototype, "edgesRenderer", {
  108103. get: function () {
  108104. return this._edgesRenderer;
  108105. },
  108106. enumerable: true,
  108107. configurable: true
  108108. });
  108109. BABYLON.LinesMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  108110. if (epsilon === void 0) { epsilon = 0.95; }
  108111. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  108112. this.disableEdgesRendering();
  108113. this._edgesRenderer = new BABYLON.LineEdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  108114. return this;
  108115. };
  108116. /**
  108117. * FaceAdjacencies Helper class to generate edges
  108118. */
  108119. var FaceAdjacencies = /** @class */ (function () {
  108120. function FaceAdjacencies() {
  108121. this.edges = new Array();
  108122. this.edgesConnectedCount = 0;
  108123. }
  108124. return FaceAdjacencies;
  108125. }());
  108126. /**
  108127. * This class is used to generate edges of the mesh that could then easily be rendered in a scene.
  108128. */
  108129. var EdgesRenderer = /** @class */ (function () {
  108130. /**
  108131. * Creates an instance of the EdgesRenderer. It is primarily use to display edges of a mesh.
  108132. * Beware when you use this class with complex objects as the adjacencies computation can be really long
  108133. * @param source Mesh used to create edges
  108134. * @param epsilon sum of angles in adjacency to check for edge
  108135. * @param checkVerticesInsteadOfIndices
  108136. * @param generateEdgesLines - should generate Lines or only prepare resources.
  108137. */
  108138. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices, generateEdgesLines) {
  108139. if (epsilon === void 0) { epsilon = 0.95; }
  108140. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  108141. if (generateEdgesLines === void 0) { generateEdgesLines = true; }
  108142. var _this = this;
  108143. /**
  108144. * Define the size of the edges with an orthographic camera
  108145. */
  108146. this.edgesWidthScalerForOrthographic = 1000.0;
  108147. /**
  108148. * Define the size of the edges with a perspective camera
  108149. */
  108150. this.edgesWidthScalerForPerspective = 50.0;
  108151. this._linesPositions = new Array();
  108152. this._linesNormals = new Array();
  108153. this._linesIndices = new Array();
  108154. this._buffers = {};
  108155. this._checkVerticesInsteadOfIndices = false;
  108156. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  108157. this.isEnabled = true;
  108158. this._source = source;
  108159. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  108160. this._epsilon = epsilon;
  108161. this._prepareRessources();
  108162. if (generateEdgesLines) {
  108163. this._generateEdgesLines();
  108164. }
  108165. this._meshRebuildObserver = this._source.onRebuildObservable.add(function () {
  108166. _this._rebuild();
  108167. });
  108168. this._meshDisposeObserver = this._source.onDisposeObservable.add(function () {
  108169. _this.dispose();
  108170. });
  108171. }
  108172. EdgesRenderer.prototype._prepareRessources = function () {
  108173. if (this._lineShader) {
  108174. return;
  108175. }
  108176. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  108177. attributes: ["position", "normal"],
  108178. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  108179. });
  108180. this._lineShader.disableDepthWrite = true;
  108181. this._lineShader.backFaceCulling = false;
  108182. };
  108183. /** @hidden */
  108184. EdgesRenderer.prototype._rebuild = function () {
  108185. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  108186. if (buffer) {
  108187. buffer._rebuild();
  108188. }
  108189. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  108190. if (buffer) {
  108191. buffer._rebuild();
  108192. }
  108193. var scene = this._source.getScene();
  108194. var engine = scene.getEngine();
  108195. this._ib = engine.createIndexBuffer(this._linesIndices);
  108196. };
  108197. /**
  108198. * Releases the required resources for the edges renderer
  108199. */
  108200. EdgesRenderer.prototype.dispose = function () {
  108201. this._source.onRebuildObservable.remove(this._meshRebuildObserver);
  108202. this._source.onDisposeObservable.remove(this._meshDisposeObserver);
  108203. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  108204. if (buffer) {
  108205. buffer.dispose();
  108206. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  108207. }
  108208. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  108209. if (buffer) {
  108210. buffer.dispose();
  108211. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  108212. }
  108213. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  108214. this._lineShader.dispose();
  108215. };
  108216. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  108217. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  108218. return 0;
  108219. }
  108220. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  108221. return 1;
  108222. }
  108223. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  108224. return 2;
  108225. }
  108226. return -1;
  108227. };
  108228. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  108229. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  108230. return 0;
  108231. }
  108232. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  108233. return 1;
  108234. }
  108235. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  108236. return 2;
  108237. }
  108238. return -1;
  108239. };
  108240. /**
  108241. * Checks if the pair of p0 and p1 is en edge
  108242. * @param faceIndex
  108243. * @param edge
  108244. * @param faceNormals
  108245. * @param p0
  108246. * @param p1
  108247. * @private
  108248. */
  108249. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  108250. var needToCreateLine;
  108251. if (edge === undefined) {
  108252. needToCreateLine = true;
  108253. }
  108254. else {
  108255. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  108256. needToCreateLine = dotProduct < this._epsilon;
  108257. }
  108258. if (needToCreateLine) {
  108259. var offset = this._linesPositions.length / 3;
  108260. var normal = p0.subtract(p1);
  108261. normal.normalize();
  108262. // Positions
  108263. this._linesPositions.push(p0.x);
  108264. this._linesPositions.push(p0.y);
  108265. this._linesPositions.push(p0.z);
  108266. this._linesPositions.push(p0.x);
  108267. this._linesPositions.push(p0.y);
  108268. this._linesPositions.push(p0.z);
  108269. this._linesPositions.push(p1.x);
  108270. this._linesPositions.push(p1.y);
  108271. this._linesPositions.push(p1.z);
  108272. this._linesPositions.push(p1.x);
  108273. this._linesPositions.push(p1.y);
  108274. this._linesPositions.push(p1.z);
  108275. // Normals
  108276. this._linesNormals.push(p1.x);
  108277. this._linesNormals.push(p1.y);
  108278. this._linesNormals.push(p1.z);
  108279. this._linesNormals.push(-1);
  108280. this._linesNormals.push(p1.x);
  108281. this._linesNormals.push(p1.y);
  108282. this._linesNormals.push(p1.z);
  108283. this._linesNormals.push(1);
  108284. this._linesNormals.push(p0.x);
  108285. this._linesNormals.push(p0.y);
  108286. this._linesNormals.push(p0.z);
  108287. this._linesNormals.push(-1);
  108288. this._linesNormals.push(p0.x);
  108289. this._linesNormals.push(p0.y);
  108290. this._linesNormals.push(p0.z);
  108291. this._linesNormals.push(1);
  108292. // Indices
  108293. this._linesIndices.push(offset);
  108294. this._linesIndices.push(offset + 1);
  108295. this._linesIndices.push(offset + 2);
  108296. this._linesIndices.push(offset);
  108297. this._linesIndices.push(offset + 2);
  108298. this._linesIndices.push(offset + 3);
  108299. }
  108300. };
  108301. /**
  108302. * Generates lines edges from adjacencjes
  108303. * @private
  108304. */
  108305. EdgesRenderer.prototype._generateEdgesLines = function () {
  108306. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  108307. var indices = this._source.getIndices();
  108308. if (!indices || !positions) {
  108309. return;
  108310. }
  108311. // First let's find adjacencies
  108312. var adjacencies = new Array();
  108313. var faceNormals = new Array();
  108314. var index;
  108315. var faceAdjacencies;
  108316. // Prepare faces
  108317. for (index = 0; index < indices.length; index += 3) {
  108318. faceAdjacencies = new FaceAdjacencies();
  108319. var p0Index = indices[index];
  108320. var p1Index = indices[index + 1];
  108321. var p2Index = indices[index + 2];
  108322. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  108323. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  108324. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  108325. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  108326. faceNormal.normalize();
  108327. faceNormals.push(faceNormal);
  108328. adjacencies.push(faceAdjacencies);
  108329. }
  108330. // Scan
  108331. for (index = 0; index < adjacencies.length; index++) {
  108332. faceAdjacencies = adjacencies[index];
  108333. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  108334. var otherFaceAdjacencies = adjacencies[otherIndex];
  108335. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  108336. break;
  108337. }
  108338. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  108339. continue;
  108340. }
  108341. var otherP0 = indices[otherIndex * 3];
  108342. var otherP1 = indices[otherIndex * 3 + 1];
  108343. var otherP2 = indices[otherIndex * 3 + 2];
  108344. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  108345. var otherEdgeIndex = 0;
  108346. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  108347. continue;
  108348. }
  108349. switch (edgeIndex) {
  108350. case 0:
  108351. if (this._checkVerticesInsteadOfIndices) {
  108352. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  108353. }
  108354. else {
  108355. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  108356. }
  108357. break;
  108358. case 1:
  108359. if (this._checkVerticesInsteadOfIndices) {
  108360. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  108361. }
  108362. else {
  108363. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  108364. }
  108365. break;
  108366. case 2:
  108367. if (this._checkVerticesInsteadOfIndices) {
  108368. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  108369. }
  108370. else {
  108371. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  108372. }
  108373. break;
  108374. }
  108375. if (otherEdgeIndex === -1) {
  108376. continue;
  108377. }
  108378. faceAdjacencies.edges[edgeIndex] = otherIndex;
  108379. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  108380. faceAdjacencies.edgesConnectedCount++;
  108381. otherFaceAdjacencies.edgesConnectedCount++;
  108382. if (faceAdjacencies.edgesConnectedCount === 3) {
  108383. break;
  108384. }
  108385. }
  108386. }
  108387. }
  108388. // Create lines
  108389. for (index = 0; index < adjacencies.length; index++) {
  108390. // 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
  108391. var current = adjacencies[index];
  108392. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  108393. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  108394. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  108395. }
  108396. // Merge into a single mesh
  108397. var engine = this._source.getScene().getEngine();
  108398. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  108399. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  108400. this._ib = engine.createIndexBuffer(this._linesIndices);
  108401. this._indicesCount = this._linesIndices.length;
  108402. };
  108403. /**
  108404. * Checks wether or not the edges renderer is ready to render.
  108405. * @return true if ready, otherwise false.
  108406. */
  108407. EdgesRenderer.prototype.isReady = function () {
  108408. return this._lineShader.isReady();
  108409. };
  108410. /**
  108411. * Renders the edges of the attached mesh,
  108412. */
  108413. EdgesRenderer.prototype.render = function () {
  108414. var scene = this._source.getScene();
  108415. if (!this.isReady() || !scene.activeCamera) {
  108416. return;
  108417. }
  108418. var engine = scene.getEngine();
  108419. this._lineShader._preBind();
  108420. if (this._source.edgesColor.a !== 1) {
  108421. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  108422. }
  108423. else {
  108424. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  108425. }
  108426. // VBOs
  108427. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  108428. scene.resetCachedMaterial();
  108429. this._lineShader.setColor4("color", this._source.edgesColor);
  108430. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  108431. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  108432. }
  108433. else {
  108434. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  108435. }
  108436. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  108437. this._lineShader.bind(this._source.getWorldMatrix());
  108438. // Draw order
  108439. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  108440. this._lineShader.unbind();
  108441. };
  108442. return EdgesRenderer;
  108443. }());
  108444. BABYLON.EdgesRenderer = EdgesRenderer;
  108445. })(BABYLON || (BABYLON = {}));
  108446. //# sourceMappingURL=babylon.edgesRenderer.js.map
  108447. var BABYLON;
  108448. (function (BABYLON) {
  108449. /**
  108450. * FaceAdjacencies Helper class to generate edges
  108451. */
  108452. var FaceAdjacencies = /** @class */ (function () {
  108453. function FaceAdjacencies() {
  108454. this.edges = new Array();
  108455. this.edgesConnectedCount = 0;
  108456. }
  108457. return FaceAdjacencies;
  108458. }());
  108459. /**
  108460. * LineEdgesRenderer for LineMeshes to remove unnecessary triangulation
  108461. */
  108462. var LineEdgesRenderer = /** @class */ (function (_super) {
  108463. __extends(LineEdgesRenderer, _super);
  108464. /**
  108465. * This constructor turns off auto generating edges line in Edges Renderer to make it here.
  108466. * @param source LineMesh used to generate edges
  108467. * @param epsilon not important (specified angle for edge detection)
  108468. * @param checkVerticesInsteadOfIndices not important for LineMesh
  108469. */
  108470. function LineEdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  108471. if (epsilon === void 0) { epsilon = 0.95; }
  108472. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  108473. var _this = _super.call(this, source, epsilon, checkVerticesInsteadOfIndices, false) || this;
  108474. _this._generateEdgesLines();
  108475. return _this;
  108476. }
  108477. /**
  108478. * Always create the edge since its a line so only important things are p0 and p1
  108479. * @param faceIndex not important for LineMesh
  108480. * @param edge not important for LineMesh
  108481. * @param faceNormals not important for LineMesh
  108482. * @param p0 beginnig of line
  108483. * @param p1 end of line
  108484. */
  108485. LineEdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  108486. var offset = this._linesPositions.length / 3;
  108487. var normal = p0.subtract(p1);
  108488. normal.normalize();
  108489. // Positions
  108490. this._linesPositions.push(p0.x);
  108491. this._linesPositions.push(p0.y);
  108492. this._linesPositions.push(p0.z);
  108493. this._linesPositions.push(p0.x);
  108494. this._linesPositions.push(p0.y);
  108495. this._linesPositions.push(p0.z);
  108496. this._linesPositions.push(p1.x);
  108497. this._linesPositions.push(p1.y);
  108498. this._linesPositions.push(p1.z);
  108499. this._linesPositions.push(p1.x);
  108500. this._linesPositions.push(p1.y);
  108501. this._linesPositions.push(p1.z);
  108502. // Normals
  108503. this._linesNormals.push(p1.x);
  108504. this._linesNormals.push(p1.y);
  108505. this._linesNormals.push(p1.z);
  108506. this._linesNormals.push(-1);
  108507. this._linesNormals.push(p1.x);
  108508. this._linesNormals.push(p1.y);
  108509. this._linesNormals.push(p1.z);
  108510. this._linesNormals.push(1);
  108511. this._linesNormals.push(p0.x);
  108512. this._linesNormals.push(p0.y);
  108513. this._linesNormals.push(p0.z);
  108514. this._linesNormals.push(-1);
  108515. this._linesNormals.push(p0.x);
  108516. this._linesNormals.push(p0.y);
  108517. this._linesNormals.push(p0.z);
  108518. this._linesNormals.push(1);
  108519. // Indices
  108520. this._linesIndices.push(offset);
  108521. this._linesIndices.push(offset + 1);
  108522. this._linesIndices.push(offset + 2);
  108523. this._linesIndices.push(offset);
  108524. this._linesIndices.push(offset + 2);
  108525. this._linesIndices.push(offset + 3);
  108526. };
  108527. /**
  108528. * Generate edges for each line in LinesMesh. Every Line should be rendered as edge.
  108529. */
  108530. LineEdgesRenderer.prototype._generateEdgesLines = function () {
  108531. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  108532. var indices = this._source.getIndices();
  108533. if (!indices || !positions) {
  108534. return;
  108535. }
  108536. // First let's find adjacencies
  108537. var adjacencies = new Array();
  108538. var faceNormals = new Array();
  108539. var index;
  108540. for (var i = 0; i < (positions.length / 3) - 1; i++) {
  108541. var currentAdjecancy = new FaceAdjacencies();
  108542. currentAdjecancy.p0 = new BABYLON.Vector3(positions[i * 3], positions[i * 3 + 1], positions[i * 3 + 2]);
  108543. currentAdjecancy.p1 = new BABYLON.Vector3(positions[(i + 1) * 3], positions[(i + 1) * 3 + 1], positions[(i + 1) * 3 + 2]);
  108544. adjacencies.push(currentAdjecancy);
  108545. }
  108546. // Create lines
  108547. for (index = 0; index < adjacencies.length; index++) {
  108548. // 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
  108549. var current = adjacencies[index];
  108550. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  108551. }
  108552. // Merge into a single mesh
  108553. var engine = this._source.getScene().getEngine();
  108554. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  108555. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  108556. this._ib = engine.createIndexBuffer(this._linesIndices);
  108557. this._indicesCount = this._linesIndices.length;
  108558. };
  108559. return LineEdgesRenderer;
  108560. }(BABYLON.EdgesRenderer));
  108561. BABYLON.LineEdgesRenderer = LineEdgesRenderer;
  108562. })(BABYLON || (BABYLON = {}));
  108563. //# sourceMappingURL=babylon.lineEdgesRenderer.js.map
  108564. var BABYLON;
  108565. (function (BABYLON) {
  108566. // Adds the parser to the scene parsers.
  108567. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER, function (parsedData, scene, container, rootUrl) {
  108568. if (parsedData.effectLayers) {
  108569. if (!container.effectLayers) {
  108570. container.effectLayers = new Array();
  108571. }
  108572. for (var index = 0; index < parsedData.effectLayers.length; index++) {
  108573. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  108574. container.effectLayers.push(effectLayer);
  108575. }
  108576. }
  108577. });
  108578. BABYLON.AbstractScene.prototype.removeEffectLayer = function (toRemove) {
  108579. var index = this.effectLayers.indexOf(toRemove);
  108580. if (index !== -1) {
  108581. this.effectLayers.splice(index, 1);
  108582. }
  108583. return index;
  108584. };
  108585. BABYLON.AbstractScene.prototype.addEffectLayer = function (newEffectLayer) {
  108586. this.effectLayers.push(newEffectLayer);
  108587. };
  108588. /**
  108589. * Defines the layer scene component responsible to manage any effect layers
  108590. * in a given scene.
  108591. */
  108592. var EffectLayerSceneComponent = /** @class */ (function () {
  108593. /**
  108594. * Creates a new instance of the component for the given scene
  108595. * @param scene Defines the scene to register the component in
  108596. */
  108597. function EffectLayerSceneComponent(scene) {
  108598. /**
  108599. * The component name helpfull to identify the component in the list of scene components.
  108600. */
  108601. this.name = BABYLON.SceneComponentConstants.NAME_EFFECTLAYER;
  108602. this._renderEffects = false;
  108603. this._needStencil = false;
  108604. this._previousStencilState = false;
  108605. this.scene = scene;
  108606. this._engine = scene.getEngine();
  108607. scene.effectLayers = new Array();
  108608. }
  108609. /**
  108610. * Registers the component in a given scene
  108611. */
  108612. EffectLayerSceneComponent.prototype.register = function () {
  108613. this.scene._isReadyForMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER, this, this._isReadyForMesh);
  108614. this.scene._cameraDrawRenderTargetStage.registerStep(BABYLON.SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER, this, this._renderMainTexture);
  108615. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER, this, this._setStencil);
  108616. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW, this, this._drawRenderingGroup);
  108617. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER, this, this._setStencilBack);
  108618. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW, this, this._drawCamera);
  108619. };
  108620. /**
  108621. * Rebuilds the elements related to this component in case of
  108622. * context lost for instance.
  108623. */
  108624. EffectLayerSceneComponent.prototype.rebuild = function () {
  108625. var layers = this.scene.effectLayers;
  108626. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  108627. var effectLayer = layers_1[_i];
  108628. effectLayer._rebuild();
  108629. }
  108630. };
  108631. /**
  108632. * Serializes the component data to the specified json object
  108633. * @param serializationObject The object to serialize to
  108634. */
  108635. EffectLayerSceneComponent.prototype.serialize = function (serializationObject) {
  108636. // Effect layers
  108637. serializationObject.effectLayers = [];
  108638. var layers = this.scene.effectLayers;
  108639. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  108640. var effectLayer = layers_2[_i];
  108641. if (effectLayer.serialize) {
  108642. serializationObject.effectLayers.push(effectLayer.serialize());
  108643. }
  108644. }
  108645. };
  108646. /**
  108647. * Adds all the element from the container to the scene
  108648. * @param container the container holding the elements
  108649. */
  108650. EffectLayerSceneComponent.prototype.addFromContainer = function (container) {
  108651. var _this = this;
  108652. if (!container.effectLayers) {
  108653. return;
  108654. }
  108655. container.effectLayers.forEach(function (o) {
  108656. _this.scene.addEffectLayer(o);
  108657. });
  108658. };
  108659. /**
  108660. * Removes all the elements in the container from the scene
  108661. * @param container contains the elements to remove
  108662. */
  108663. EffectLayerSceneComponent.prototype.removeFromContainer = function (container) {
  108664. var _this = this;
  108665. if (!container.effectLayers) {
  108666. return;
  108667. }
  108668. container.effectLayers.forEach(function (o) {
  108669. _this.scene.removeEffectLayer(o);
  108670. });
  108671. };
  108672. /**
  108673. * Disposes the component and the associated ressources.
  108674. */
  108675. EffectLayerSceneComponent.prototype.dispose = function () {
  108676. var layers = this.scene.effectLayers;
  108677. while (layers.length) {
  108678. layers[0].dispose();
  108679. }
  108680. };
  108681. EffectLayerSceneComponent.prototype._isReadyForMesh = function (mesh, hardwareInstancedRendering) {
  108682. var layers = this.scene.effectLayers;
  108683. for (var _i = 0, layers_3 = layers; _i < layers_3.length; _i++) {
  108684. var layer = layers_3[_i];
  108685. if (!layer.hasMesh(mesh)) {
  108686. continue;
  108687. }
  108688. for (var _a = 0, _b = mesh.subMeshes; _a < _b.length; _a++) {
  108689. var subMesh = _b[_a];
  108690. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  108691. return false;
  108692. }
  108693. }
  108694. }
  108695. return true;
  108696. };
  108697. EffectLayerSceneComponent.prototype._renderMainTexture = function (camera) {
  108698. this._renderEffects = false;
  108699. this._needStencil = false;
  108700. var layers = this.scene.effectLayers;
  108701. if (layers && layers.length > 0) {
  108702. this._previousStencilState = this._engine.getStencilBuffer();
  108703. for (var _i = 0, layers_4 = layers; _i < layers_4.length; _i++) {
  108704. var effectLayer = layers_4[_i];
  108705. if (effectLayer.shouldRender() &&
  108706. (!effectLayer.camera ||
  108707. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  108708. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  108709. this._renderEffects = true;
  108710. this._needStencil = this._needStencil || effectLayer.needStencil();
  108711. var renderTarget = effectLayer._mainTexture;
  108712. if (renderTarget._shouldRender()) {
  108713. this.scene.incrementRenderId();
  108714. renderTarget.render(false, false);
  108715. }
  108716. }
  108717. }
  108718. this.scene.incrementRenderId();
  108719. }
  108720. };
  108721. EffectLayerSceneComponent.prototype._setStencil = function (camera) {
  108722. // Activate effect Layer stencil
  108723. if (this._needStencil) {
  108724. this._engine.setStencilBuffer(true);
  108725. }
  108726. };
  108727. EffectLayerSceneComponent.prototype._setStencilBack = function (camera) {
  108728. // Restore effect Layer stencil
  108729. if (this._needStencil) {
  108730. this._engine.setStencilBuffer(this._previousStencilState);
  108731. }
  108732. };
  108733. EffectLayerSceneComponent.prototype._draw = function (renderingGroupId) {
  108734. if (this._renderEffects) {
  108735. this._engine.setDepthBuffer(false);
  108736. var layers = this.scene.effectLayers;
  108737. for (var i = 0; i < layers.length; i++) {
  108738. var effectLayer = layers[i];
  108739. if (effectLayer.renderingGroupId === renderingGroupId) {
  108740. if (effectLayer.shouldRender()) {
  108741. effectLayer.render();
  108742. }
  108743. }
  108744. }
  108745. this._engine.setDepthBuffer(true);
  108746. }
  108747. };
  108748. EffectLayerSceneComponent.prototype._drawCamera = function (camera) {
  108749. if (this._renderEffects) {
  108750. this._draw(-1);
  108751. }
  108752. };
  108753. EffectLayerSceneComponent.prototype._drawRenderingGroup = function (index) {
  108754. if (!this.scene._isInIntermediateRendering() && this._renderEffects) {
  108755. this._draw(index);
  108756. }
  108757. };
  108758. return EffectLayerSceneComponent;
  108759. }());
  108760. BABYLON.EffectLayerSceneComponent = EffectLayerSceneComponent;
  108761. })(BABYLON || (BABYLON = {}));
  108762. //# sourceMappingURL=babylon.effectLayerSceneComponent.js.map
  108763. var __assign = (this && this.__assign) || function () {
  108764. __assign = Object.assign || function(t) {
  108765. for (var s, i = 1, n = arguments.length; i < n; i++) {
  108766. s = arguments[i];
  108767. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  108768. t[p] = s[p];
  108769. }
  108770. return t;
  108771. };
  108772. return __assign.apply(this, arguments);
  108773. };
  108774. var BABYLON;
  108775. (function (BABYLON) {
  108776. /**
  108777. * The effect layer Helps adding post process effect blended with the main pass.
  108778. *
  108779. * This can be for instance use to generate glow or higlight effects on the scene.
  108780. *
  108781. * The effect layer class can not be used directly and is intented to inherited from to be
  108782. * customized per effects.
  108783. */
  108784. var EffectLayer = /** @class */ (function () {
  108785. /**
  108786. * Instantiates a new effect Layer and references it in the scene.
  108787. * @param name The name of the layer
  108788. * @param scene The scene to use the layer in
  108789. */
  108790. function EffectLayer(
  108791. /** The Friendly of the effect in the scene */
  108792. name, scene) {
  108793. this._vertexBuffers = {};
  108794. this._maxSize = 0;
  108795. this._mainTextureDesiredSize = { width: 0, height: 0 };
  108796. this._shouldRender = true;
  108797. this._postProcesses = [];
  108798. this._textures = [];
  108799. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  108800. /**
  108801. * The clear color of the texture used to generate the glow map.
  108802. */
  108803. this.neutralColor = new BABYLON.Color4();
  108804. /**
  108805. * Specifies wether the highlight layer is enabled or not.
  108806. */
  108807. this.isEnabled = true;
  108808. /**
  108809. * An event triggered when the effect layer has been disposed.
  108810. */
  108811. this.onDisposeObservable = new BABYLON.Observable();
  108812. /**
  108813. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  108814. */
  108815. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  108816. /**
  108817. * An event triggered when the generated texture is being merged in the scene.
  108818. */
  108819. this.onBeforeComposeObservable = new BABYLON.Observable();
  108820. /**
  108821. * An event triggered when the generated texture has been merged in the scene.
  108822. */
  108823. this.onAfterComposeObservable = new BABYLON.Observable();
  108824. /**
  108825. * An event triggered when the efffect layer changes its size.
  108826. */
  108827. this.onSizeChangedObservable = new BABYLON.Observable();
  108828. this.name = name;
  108829. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  108830. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER);
  108831. if (!component) {
  108832. component = new BABYLON.EffectLayerSceneComponent(this._scene);
  108833. this._scene._addComponent(component);
  108834. }
  108835. this._engine = this._scene.getEngine();
  108836. this._maxSize = this._engine.getCaps().maxTextureSize;
  108837. this._scene.effectLayers.push(this);
  108838. // Generate Buffers
  108839. this._generateIndexBuffer();
  108840. this._genrateVertexBuffer();
  108841. }
  108842. Object.defineProperty(EffectLayer.prototype, "camera", {
  108843. /**
  108844. * Gets the camera attached to the layer.
  108845. */
  108846. get: function () {
  108847. return this._effectLayerOptions.camera;
  108848. },
  108849. enumerable: true,
  108850. configurable: true
  108851. });
  108852. Object.defineProperty(EffectLayer.prototype, "renderingGroupId", {
  108853. /**
  108854. * Gets the rendering group id the layer should render in.
  108855. */
  108856. get: function () {
  108857. return this._effectLayerOptions.renderingGroupId;
  108858. },
  108859. enumerable: true,
  108860. configurable: true
  108861. });
  108862. /**
  108863. * Initializes the effect layer with the required options.
  108864. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  108865. */
  108866. EffectLayer.prototype._init = function (options) {
  108867. // Adapt options
  108868. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
  108869. this._setMainTextureSize();
  108870. this._createMainTexture();
  108871. this._createTextureAndPostProcesses();
  108872. this._mergeEffect = this._createMergeEffect();
  108873. };
  108874. /**
  108875. * Generates the index buffer of the full screen quad blending to the main canvas.
  108876. */
  108877. EffectLayer.prototype._generateIndexBuffer = function () {
  108878. // Indices
  108879. var indices = [];
  108880. indices.push(0);
  108881. indices.push(1);
  108882. indices.push(2);
  108883. indices.push(0);
  108884. indices.push(2);
  108885. indices.push(3);
  108886. this._indexBuffer = this._engine.createIndexBuffer(indices);
  108887. };
  108888. /**
  108889. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  108890. */
  108891. EffectLayer.prototype._genrateVertexBuffer = function () {
  108892. // VBO
  108893. var vertices = [];
  108894. vertices.push(1, 1);
  108895. vertices.push(-1, 1);
  108896. vertices.push(-1, -1);
  108897. vertices.push(1, -1);
  108898. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  108899. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  108900. };
  108901. /**
  108902. * Sets the main texture desired size which is the closest power of two
  108903. * of the engine canvas size.
  108904. */
  108905. EffectLayer.prototype._setMainTextureSize = function () {
  108906. if (this._effectLayerOptions.mainTextureFixedSize) {
  108907. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  108908. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  108909. }
  108910. else {
  108911. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  108912. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  108913. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  108914. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  108915. }
  108916. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  108917. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  108918. };
  108919. /**
  108920. * Creates the main texture for the effect layer.
  108921. */
  108922. EffectLayer.prototype._createMainTexture = function () {
  108923. var _this = this;
  108924. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  108925. width: this._mainTextureDesiredSize.width,
  108926. height: this._mainTextureDesiredSize.height
  108927. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  108928. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  108929. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  108930. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  108931. this._mainTexture.anisotropicFilteringLevel = 1;
  108932. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  108933. this._mainTexture.renderParticles = false;
  108934. this._mainTexture.renderList = null;
  108935. this._mainTexture.ignoreCameraViewport = true;
  108936. // Custom render function
  108937. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  108938. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  108939. var index;
  108940. var engine = _this._scene.getEngine();
  108941. if (depthOnlySubMeshes.length) {
  108942. engine.setColorWrite(false);
  108943. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  108944. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  108945. }
  108946. engine.setColorWrite(true);
  108947. }
  108948. for (index = 0; index < opaqueSubMeshes.length; index++) {
  108949. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  108950. }
  108951. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  108952. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  108953. }
  108954. for (index = 0; index < transparentSubMeshes.length; index++) {
  108955. _this._renderSubMesh(transparentSubMeshes.data[index]);
  108956. }
  108957. };
  108958. this._mainTexture.onClearObservable.add(function (engine) {
  108959. engine.clear(_this.neutralColor, true, true, true);
  108960. });
  108961. };
  108962. /**
  108963. * Checks for the readiness of the element composing the layer.
  108964. * @param subMesh the mesh to check for
  108965. * @param useInstances specify wether or not to use instances to render the mesh
  108966. * @param emissiveTexture the associated emissive texture used to generate the glow
  108967. * @return true if ready otherwise, false
  108968. */
  108969. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  108970. var material = subMesh.getMaterial();
  108971. if (!material) {
  108972. return false;
  108973. }
  108974. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  108975. return false;
  108976. }
  108977. var defines = [];
  108978. var attribs = [BABYLON.VertexBuffer.PositionKind];
  108979. var mesh = subMesh.getMesh();
  108980. var uv1 = false;
  108981. var uv2 = false;
  108982. // Alpha test
  108983. if (material && material.needAlphaTesting()) {
  108984. var alphaTexture = material.getAlphaTestTexture();
  108985. if (alphaTexture) {
  108986. defines.push("#define ALPHATEST");
  108987. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  108988. alphaTexture.coordinatesIndex === 1) {
  108989. defines.push("#define DIFFUSEUV2");
  108990. uv2 = true;
  108991. }
  108992. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  108993. defines.push("#define DIFFUSEUV1");
  108994. uv1 = true;
  108995. }
  108996. }
  108997. }
  108998. // Emissive
  108999. if (emissiveTexture) {
  109000. defines.push("#define EMISSIVE");
  109001. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  109002. emissiveTexture.coordinatesIndex === 1) {
  109003. defines.push("#define EMISSIVEUV2");
  109004. uv2 = true;
  109005. }
  109006. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  109007. defines.push("#define EMISSIVEUV1");
  109008. uv1 = true;
  109009. }
  109010. }
  109011. if (uv1) {
  109012. attribs.push(BABYLON.VertexBuffer.UVKind);
  109013. defines.push("#define UV1");
  109014. }
  109015. if (uv2) {
  109016. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  109017. defines.push("#define UV2");
  109018. }
  109019. // Bones
  109020. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  109021. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  109022. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  109023. if (mesh.numBoneInfluencers > 4) {
  109024. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  109025. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  109026. }
  109027. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  109028. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  109029. }
  109030. else {
  109031. defines.push("#define NUM_BONE_INFLUENCERS 0");
  109032. }
  109033. // Morph targets
  109034. var manager = mesh.morphTargetManager;
  109035. var morphInfluencers = 0;
  109036. if (manager) {
  109037. if (manager.numInfluencers > 0) {
  109038. defines.push("#define MORPHTARGETS");
  109039. morphInfluencers = manager.numInfluencers;
  109040. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  109041. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  109042. }
  109043. }
  109044. // Instances
  109045. if (useInstances) {
  109046. defines.push("#define INSTANCES");
  109047. attribs.push("world0");
  109048. attribs.push("world1");
  109049. attribs.push("world2");
  109050. attribs.push("world3");
  109051. }
  109052. // Get correct effect
  109053. var join = defines.join("\n");
  109054. if (this._cachedDefines !== join) {
  109055. this._cachedDefines = join;
  109056. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  109057. }
  109058. return this._effectLayerMapGenerationEffect.isReady();
  109059. };
  109060. /**
  109061. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  109062. */
  109063. EffectLayer.prototype.render = function () {
  109064. var currentEffect = this._mergeEffect;
  109065. // Check
  109066. if (!currentEffect.isReady())
  109067. return;
  109068. for (var i = 0; i < this._postProcesses.length; i++) {
  109069. if (!this._postProcesses[i].isReady()) {
  109070. return;
  109071. }
  109072. }
  109073. var engine = this._scene.getEngine();
  109074. this.onBeforeComposeObservable.notifyObservers(this);
  109075. // Render
  109076. engine.enableEffect(currentEffect);
  109077. engine.setState(false);
  109078. // VBOs
  109079. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  109080. // Cache
  109081. var previousAlphaMode = engine.getAlphaMode();
  109082. // Go Blend.
  109083. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  109084. // Blends the map on the main canvas.
  109085. this._internalRender(currentEffect);
  109086. // Restore Alpha
  109087. engine.setAlphaMode(previousAlphaMode);
  109088. this.onAfterComposeObservable.notifyObservers(this);
  109089. // Handle size changes.
  109090. var size = this._mainTexture.getSize();
  109091. this._setMainTextureSize();
  109092. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  109093. // Recreate RTT and post processes on size change.
  109094. this.onSizeChangedObservable.notifyObservers(this);
  109095. this._disposeTextureAndPostProcesses();
  109096. this._createMainTexture();
  109097. this._createTextureAndPostProcesses();
  109098. }
  109099. };
  109100. /**
  109101. * Determine if a given mesh will be used in the current effect.
  109102. * @param mesh mesh to test
  109103. * @returns true if the mesh will be used
  109104. */
  109105. EffectLayer.prototype.hasMesh = function (mesh) {
  109106. if (this.renderingGroupId === -1 || mesh.renderingGroupId === this.renderingGroupId) {
  109107. return true;
  109108. }
  109109. return false;
  109110. };
  109111. /**
  109112. * Returns true if the layer contains information to display, otherwise false.
  109113. * @returns true if the glow layer should be rendered
  109114. */
  109115. EffectLayer.prototype.shouldRender = function () {
  109116. return this.isEnabled && this._shouldRender;
  109117. };
  109118. /**
  109119. * Returns true if the mesh should render, otherwise false.
  109120. * @param mesh The mesh to render
  109121. * @returns true if it should render otherwise false
  109122. */
  109123. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  109124. return true;
  109125. };
  109126. /**
  109127. * Returns true if the mesh should render, otherwise false.
  109128. * @param mesh The mesh to render
  109129. * @returns true if it should render otherwise false
  109130. */
  109131. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  109132. return true;
  109133. };
  109134. /**
  109135. * Renders the submesh passed in parameter to the generation map.
  109136. */
  109137. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  109138. var _this = this;
  109139. if (!this.shouldRender()) {
  109140. return;
  109141. }
  109142. var material = subMesh.getMaterial();
  109143. var mesh = subMesh.getRenderingMesh();
  109144. var scene = this._scene;
  109145. var engine = scene.getEngine();
  109146. if (!material) {
  109147. return;
  109148. }
  109149. // Do not block in blend mode.
  109150. if (material.needAlphaBlendingForMesh(mesh)) {
  109151. return;
  109152. }
  109153. // Culling
  109154. engine.setState(material.backFaceCulling);
  109155. // Managing instances
  109156. var batch = mesh._getInstancesRenderList(subMesh._id);
  109157. if (batch.mustReturn) {
  109158. return;
  109159. }
  109160. // Early Exit per mesh
  109161. if (!this._shouldRenderMesh(mesh)) {
  109162. return;
  109163. }
  109164. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  109165. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  109166. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  109167. engine.enableEffect(this._effectLayerMapGenerationEffect);
  109168. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  109169. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  109170. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  109171. // Alpha test
  109172. if (material && material.needAlphaTesting()) {
  109173. var alphaTexture = material.getAlphaTestTexture();
  109174. if (alphaTexture) {
  109175. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  109176. var textureMatrix = alphaTexture.getTextureMatrix();
  109177. if (textureMatrix) {
  109178. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  109179. }
  109180. }
  109181. }
  109182. // Glow emissive only
  109183. if (this._emissiveTextureAndColor.texture) {
  109184. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  109185. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  109186. }
  109187. // Bones
  109188. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  109189. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  109190. }
  109191. // Morph targets
  109192. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  109193. // Draw
  109194. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  109195. }
  109196. else {
  109197. // Need to reset refresh rate of the main map
  109198. this._mainTexture.resetRefreshCounter();
  109199. }
  109200. };
  109201. /**
  109202. * Rebuild the required buffers.
  109203. * @hidden Internal use only.
  109204. */
  109205. EffectLayer.prototype._rebuild = function () {
  109206. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  109207. if (vb) {
  109208. vb._rebuild();
  109209. }
  109210. this._generateIndexBuffer();
  109211. };
  109212. /**
  109213. * Dispose only the render target textures and post process.
  109214. */
  109215. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  109216. this._mainTexture.dispose();
  109217. for (var i = 0; i < this._postProcesses.length; i++) {
  109218. if (this._postProcesses[i]) {
  109219. this._postProcesses[i].dispose();
  109220. }
  109221. }
  109222. this._postProcesses = [];
  109223. for (var i = 0; i < this._textures.length; i++) {
  109224. if (this._textures[i]) {
  109225. this._textures[i].dispose();
  109226. }
  109227. }
  109228. this._textures = [];
  109229. };
  109230. /**
  109231. * Dispose the highlight layer and free resources.
  109232. */
  109233. EffectLayer.prototype.dispose = function () {
  109234. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  109235. if (vertexBuffer) {
  109236. vertexBuffer.dispose();
  109237. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  109238. }
  109239. if (this._indexBuffer) {
  109240. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  109241. this._indexBuffer = null;
  109242. }
  109243. // Clean textures and post processes
  109244. this._disposeTextureAndPostProcesses();
  109245. // Remove from scene
  109246. var index = this._scene.effectLayers.indexOf(this, 0);
  109247. if (index > -1) {
  109248. this._scene.effectLayers.splice(index, 1);
  109249. }
  109250. // Callback
  109251. this.onDisposeObservable.notifyObservers(this);
  109252. this.onDisposeObservable.clear();
  109253. this.onBeforeRenderMainTextureObservable.clear();
  109254. this.onBeforeComposeObservable.clear();
  109255. this.onAfterComposeObservable.clear();
  109256. this.onSizeChangedObservable.clear();
  109257. };
  109258. /**
  109259. * Gets the class name of the effect layer
  109260. * @returns the string with the class name of the effect layer
  109261. */
  109262. EffectLayer.prototype.getClassName = function () {
  109263. return "EffectLayer";
  109264. };
  109265. /**
  109266. * Creates an effect layer from parsed effect layer data
  109267. * @param parsedEffectLayer defines effect layer data
  109268. * @param scene defines the current scene
  109269. * @param rootUrl defines the root URL containing the effect layer information
  109270. * @returns a parsed effect Layer
  109271. */
  109272. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  109273. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  109274. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  109275. };
  109276. __decorate([
  109277. BABYLON.serialize()
  109278. ], EffectLayer.prototype, "name", void 0);
  109279. __decorate([
  109280. BABYLON.serializeAsColor4()
  109281. ], EffectLayer.prototype, "neutralColor", void 0);
  109282. __decorate([
  109283. BABYLON.serialize()
  109284. ], EffectLayer.prototype, "isEnabled", void 0);
  109285. __decorate([
  109286. BABYLON.serializeAsCameraReference()
  109287. ], EffectLayer.prototype, "camera", null);
  109288. __decorate([
  109289. BABYLON.serialize()
  109290. ], EffectLayer.prototype, "renderingGroupId", null);
  109291. return EffectLayer;
  109292. }());
  109293. BABYLON.EffectLayer = EffectLayer;
  109294. })(BABYLON || (BABYLON = {}));
  109295. //# sourceMappingURL=babylon.effectLayer.js.map
  109296. var BABYLON;
  109297. (function (BABYLON) {
  109298. BABYLON.AbstractScene.prototype.getHighlightLayerByName = function (name) {
  109299. for (var index = 0; index < this.effectLayers.length; index++) {
  109300. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === HighlightLayer.EffectName) {
  109301. return this.effectLayers[index];
  109302. }
  109303. }
  109304. return null;
  109305. };
  109306. /**
  109307. * Special Glow Blur post process only blurring the alpha channel
  109308. * It enforces keeping the most luminous color in the color channel.
  109309. */
  109310. var GlowBlurPostProcess = /** @class */ (function (_super) {
  109311. __extends(GlowBlurPostProcess, _super);
  109312. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  109313. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  109314. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  109315. _this.direction = direction;
  109316. _this.kernel = kernel;
  109317. _this.onApplyObservable.add(function (effect) {
  109318. effect.setFloat2("screenSize", _this.width, _this.height);
  109319. effect.setVector2("direction", _this.direction);
  109320. effect.setFloat("blurWidth", _this.kernel);
  109321. });
  109322. return _this;
  109323. }
  109324. return GlowBlurPostProcess;
  109325. }(BABYLON.PostProcess));
  109326. /**
  109327. * The highlight layer Helps adding a glow effect around a mesh.
  109328. *
  109329. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  109330. * glowy meshes to your scene.
  109331. *
  109332. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  109333. */
  109334. var HighlightLayer = /** @class */ (function (_super) {
  109335. __extends(HighlightLayer, _super);
  109336. /**
  109337. * Instantiates a new highlight Layer and references it to the scene..
  109338. * @param name The name of the layer
  109339. * @param scene The scene to use the layer in
  109340. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  109341. */
  109342. function HighlightLayer(name, scene, options) {
  109343. var _this = _super.call(this, name, scene) || this;
  109344. _this.name = name;
  109345. /**
  109346. * Specifies whether or not the inner glow is ACTIVE in the layer.
  109347. */
  109348. _this.innerGlow = true;
  109349. /**
  109350. * Specifies whether or not the outer glow is ACTIVE in the layer.
  109351. */
  109352. _this.outerGlow = true;
  109353. /**
  109354. * An event triggered when the highlight layer is being blurred.
  109355. */
  109356. _this.onBeforeBlurObservable = new BABYLON.Observable();
  109357. /**
  109358. * An event triggered when the highlight layer has been blurred.
  109359. */
  109360. _this.onAfterBlurObservable = new BABYLON.Observable();
  109361. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  109362. _this._meshes = {};
  109363. _this._excludedMeshes = {};
  109364. _this.neutralColor = HighlightLayer.NeutralColor;
  109365. // Warn on stencil
  109366. if (!_this._engine.isStencilEnable) {
  109367. 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 }");
  109368. }
  109369. // Adapt options
  109370. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
  109371. // Initialize the layer
  109372. _this._init({
  109373. alphaBlendingMode: _this._options.alphaBlendingMode,
  109374. camera: _this._options.camera,
  109375. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  109376. mainTextureRatio: _this._options.mainTextureRatio,
  109377. renderingGroupId: _this._options.renderingGroupId
  109378. });
  109379. // Do not render as long as no meshes have been added
  109380. _this._shouldRender = false;
  109381. return _this;
  109382. }
  109383. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  109384. /**
  109385. * Gets the horizontal size of the blur.
  109386. */
  109387. get: function () {
  109388. return this._horizontalBlurPostprocess.kernel;
  109389. },
  109390. /**
  109391. * Specifies the horizontal size of the blur.
  109392. */
  109393. set: function (value) {
  109394. this._horizontalBlurPostprocess.kernel = value;
  109395. },
  109396. enumerable: true,
  109397. configurable: true
  109398. });
  109399. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  109400. /**
  109401. * Gets the vertical size of the blur.
  109402. */
  109403. get: function () {
  109404. return this._verticalBlurPostprocess.kernel;
  109405. },
  109406. /**
  109407. * Specifies the vertical size of the blur.
  109408. */
  109409. set: function (value) {
  109410. this._verticalBlurPostprocess.kernel = value;
  109411. },
  109412. enumerable: true,
  109413. configurable: true
  109414. });
  109415. /**
  109416. * Get the effect name of the layer.
  109417. * @return The effect name
  109418. */
  109419. HighlightLayer.prototype.getEffectName = function () {
  109420. return HighlightLayer.EffectName;
  109421. };
  109422. /**
  109423. * Create the merge effect. This is the shader use to blit the information back
  109424. * to the main canvas at the end of the scene rendering.
  109425. */
  109426. HighlightLayer.prototype._createMergeEffect = function () {
  109427. // Effect
  109428. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  109429. };
  109430. /**
  109431. * Creates the render target textures and post processes used in the highlight layer.
  109432. */
  109433. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  109434. var _this = this;
  109435. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  109436. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  109437. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  109438. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  109439. var textureType = 0;
  109440. if (this._engine.getCaps().textureHalfFloatRender) {
  109441. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  109442. }
  109443. else {
  109444. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  109445. }
  109446. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  109447. width: blurTextureWidth,
  109448. height: blurTextureHeight
  109449. }, this._scene, false, true, textureType);
  109450. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  109451. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  109452. this._blurTexture.anisotropicFilteringLevel = 16;
  109453. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  109454. this._blurTexture.renderParticles = false;
  109455. this._blurTexture.ignoreCameraViewport = true;
  109456. this._textures = [this._blurTexture];
  109457. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  109458. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  109459. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  109460. effect.setTexture("textureSampler", _this._mainTexture);
  109461. });
  109462. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  109463. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  109464. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  109465. });
  109466. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  109467. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  109468. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  109469. });
  109470. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  109471. }
  109472. else {
  109473. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  109474. width: blurTextureWidth,
  109475. height: blurTextureHeight
  109476. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  109477. this._horizontalBlurPostprocess.width = blurTextureWidth;
  109478. this._horizontalBlurPostprocess.height = blurTextureHeight;
  109479. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  109480. effect.setTexture("textureSampler", _this._mainTexture);
  109481. });
  109482. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  109483. width: blurTextureWidth,
  109484. height: blurTextureHeight
  109485. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  109486. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  109487. }
  109488. this._mainTexture.onAfterUnbindObservable.add(function () {
  109489. _this.onBeforeBlurObservable.notifyObservers(_this);
  109490. var internalTexture = _this._blurTexture.getInternalTexture();
  109491. if (internalTexture) {
  109492. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  109493. }
  109494. _this.onAfterBlurObservable.notifyObservers(_this);
  109495. });
  109496. // Prevent autoClear.
  109497. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  109498. };
  109499. /**
  109500. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  109501. */
  109502. HighlightLayer.prototype.needStencil = function () {
  109503. return true;
  109504. };
  109505. /**
  109506. * Checks for the readiness of the element composing the layer.
  109507. * @param subMesh the mesh to check for
  109508. * @param useInstances specify wether or not to use instances to render the mesh
  109509. * @param emissiveTexture the associated emissive texture used to generate the glow
  109510. * @return true if ready otherwise, false
  109511. */
  109512. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  109513. var material = subMesh.getMaterial();
  109514. var mesh = subMesh.getRenderingMesh();
  109515. if (!material || !mesh || !this._meshes) {
  109516. return false;
  109517. }
  109518. var emissiveTexture = null;
  109519. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  109520. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  109521. emissiveTexture = material.emissiveTexture;
  109522. }
  109523. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  109524. };
  109525. /**
  109526. * Implementation specific of rendering the generating effect on the main canvas.
  109527. * @param effect The effect used to render through
  109528. */
  109529. HighlightLayer.prototype._internalRender = function (effect) {
  109530. // Texture
  109531. effect.setTexture("textureSampler", this._blurTexture);
  109532. // Cache
  109533. var engine = this._engine;
  109534. var previousStencilBuffer = engine.getStencilBuffer();
  109535. var previousStencilFunction = engine.getStencilFunction();
  109536. var previousStencilMask = engine.getStencilMask();
  109537. var previousStencilOperationPass = engine.getStencilOperationPass();
  109538. var previousStencilOperationFail = engine.getStencilOperationFail();
  109539. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  109540. var previousStencilReference = engine.getStencilFunctionReference();
  109541. // Stencil operations
  109542. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  109543. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  109544. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  109545. // Draw order
  109546. engine.setStencilMask(0x00);
  109547. engine.setStencilBuffer(true);
  109548. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  109549. // 2 passes inner outer
  109550. if (this.outerGlow) {
  109551. effect.setFloat("offset", 0);
  109552. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  109553. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  109554. }
  109555. if (this.innerGlow) {
  109556. effect.setFloat("offset", 1);
  109557. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  109558. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  109559. }
  109560. // Restore Cache
  109561. engine.setStencilFunction(previousStencilFunction);
  109562. engine.setStencilMask(previousStencilMask);
  109563. engine.setStencilBuffer(previousStencilBuffer);
  109564. engine.setStencilOperationPass(previousStencilOperationPass);
  109565. engine.setStencilOperationFail(previousStencilOperationFail);
  109566. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  109567. engine.setStencilFunctionReference(previousStencilReference);
  109568. };
  109569. /**
  109570. * Returns true if the layer contains information to display, otherwise false.
  109571. */
  109572. HighlightLayer.prototype.shouldRender = function () {
  109573. if (_super.prototype.shouldRender.call(this)) {
  109574. return this._meshes ? true : false;
  109575. }
  109576. return false;
  109577. };
  109578. /**
  109579. * Returns true if the mesh should render, otherwise false.
  109580. * @param mesh The mesh to render
  109581. * @returns true if it should render otherwise false
  109582. */
  109583. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  109584. // Excluded Mesh
  109585. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  109586. return false;
  109587. }
  109588. ;
  109589. if (!_super.prototype.hasMesh.call(this, mesh)) {
  109590. return false;
  109591. }
  109592. return true;
  109593. };
  109594. /**
  109595. * Sets the required values for both the emissive texture and and the main color.
  109596. */
  109597. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  109598. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  109599. if (highlightLayerMesh) {
  109600. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  109601. }
  109602. else {
  109603. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  109604. }
  109605. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  109606. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  109607. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  109608. }
  109609. else {
  109610. this._emissiveTextureAndColor.texture = null;
  109611. }
  109612. };
  109613. /**
  109614. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  109615. * @param mesh The mesh to exclude from the highlight layer
  109616. */
  109617. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  109618. if (!this._excludedMeshes) {
  109619. return;
  109620. }
  109621. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  109622. if (!meshExcluded) {
  109623. this._excludedMeshes[mesh.uniqueId] = {
  109624. mesh: mesh,
  109625. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  109626. mesh.getEngine().setStencilBuffer(false);
  109627. }),
  109628. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  109629. mesh.getEngine().setStencilBuffer(true);
  109630. }),
  109631. };
  109632. }
  109633. };
  109634. /**
  109635. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  109636. * @param mesh The mesh to highlight
  109637. */
  109638. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  109639. if (!this._excludedMeshes) {
  109640. return;
  109641. }
  109642. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  109643. if (meshExcluded) {
  109644. if (meshExcluded.beforeRender) {
  109645. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  109646. }
  109647. if (meshExcluded.afterRender) {
  109648. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  109649. }
  109650. }
  109651. this._excludedMeshes[mesh.uniqueId] = null;
  109652. };
  109653. /**
  109654. * Determine if a given mesh will be highlighted by the current HighlightLayer
  109655. * @param mesh mesh to test
  109656. * @returns true if the mesh will be highlighted by the current HighlightLayer
  109657. */
  109658. HighlightLayer.prototype.hasMesh = function (mesh) {
  109659. if (!this._meshes) {
  109660. return false;
  109661. }
  109662. if (!_super.prototype.hasMesh.call(this, mesh)) {
  109663. return false;
  109664. }
  109665. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  109666. };
  109667. /**
  109668. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  109669. * @param mesh The mesh to highlight
  109670. * @param color The color of the highlight
  109671. * @param glowEmissiveOnly Extract the glow from the emissive texture
  109672. */
  109673. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  109674. var _this = this;
  109675. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  109676. if (!this._meshes) {
  109677. return;
  109678. }
  109679. var meshHighlight = this._meshes[mesh.uniqueId];
  109680. if (meshHighlight) {
  109681. meshHighlight.color = color;
  109682. }
  109683. else {
  109684. this._meshes[mesh.uniqueId] = {
  109685. mesh: mesh,
  109686. color: color,
  109687. // Lambda required for capture due to Observable this context
  109688. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  109689. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  109690. _this._defaultStencilReference(mesh);
  109691. }
  109692. else {
  109693. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  109694. }
  109695. }),
  109696. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  109697. glowEmissiveOnly: glowEmissiveOnly
  109698. };
  109699. mesh.onDisposeObservable.add(function () {
  109700. _this._disposeMesh(mesh);
  109701. });
  109702. }
  109703. this._shouldRender = true;
  109704. };
  109705. /**
  109706. * Remove a mesh from the highlight layer in order to make it stop glowing.
  109707. * @param mesh The mesh to highlight
  109708. */
  109709. HighlightLayer.prototype.removeMesh = function (mesh) {
  109710. if (!this._meshes) {
  109711. return;
  109712. }
  109713. var meshHighlight = this._meshes[mesh.uniqueId];
  109714. if (meshHighlight) {
  109715. if (meshHighlight.observerHighlight) {
  109716. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  109717. }
  109718. if (meshHighlight.observerDefault) {
  109719. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  109720. }
  109721. delete this._meshes[mesh.uniqueId];
  109722. }
  109723. this._shouldRender = false;
  109724. for (var meshHighlightToCheck in this._meshes) {
  109725. if (this._meshes[meshHighlightToCheck]) {
  109726. this._shouldRender = true;
  109727. break;
  109728. }
  109729. }
  109730. };
  109731. /**
  109732. * Force the stencil to the normal expected value for none glowing parts
  109733. */
  109734. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  109735. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  109736. };
  109737. /**
  109738. * Free any resources and references associated to a mesh.
  109739. * Internal use
  109740. * @param mesh The mesh to free.
  109741. * @hidden
  109742. */
  109743. HighlightLayer.prototype._disposeMesh = function (mesh) {
  109744. this.removeMesh(mesh);
  109745. this.removeExcludedMesh(mesh);
  109746. };
  109747. /**
  109748. * Dispose the highlight layer and free resources.
  109749. */
  109750. HighlightLayer.prototype.dispose = function () {
  109751. if (this._meshes) {
  109752. // Clean mesh references
  109753. for (var id in this._meshes) {
  109754. var meshHighlight = this._meshes[id];
  109755. if (meshHighlight && meshHighlight.mesh) {
  109756. if (meshHighlight.observerHighlight) {
  109757. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  109758. }
  109759. if (meshHighlight.observerDefault) {
  109760. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  109761. }
  109762. }
  109763. }
  109764. this._meshes = null;
  109765. }
  109766. if (this._excludedMeshes) {
  109767. for (var id in this._excludedMeshes) {
  109768. var meshHighlight = this._excludedMeshes[id];
  109769. if (meshHighlight) {
  109770. if (meshHighlight.beforeRender) {
  109771. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  109772. }
  109773. if (meshHighlight.afterRender) {
  109774. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  109775. }
  109776. }
  109777. }
  109778. this._excludedMeshes = null;
  109779. }
  109780. _super.prototype.dispose.call(this);
  109781. };
  109782. /**
  109783. * Gets the class name of the effect layer
  109784. * @returns the string with the class name of the effect layer
  109785. */
  109786. HighlightLayer.prototype.getClassName = function () {
  109787. return "HighlightLayer";
  109788. };
  109789. /**
  109790. * Serializes this Highlight layer
  109791. * @returns a serialized Highlight layer object
  109792. */
  109793. HighlightLayer.prototype.serialize = function () {
  109794. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  109795. serializationObject.customType = "BABYLON.HighlightLayer";
  109796. // Highlighted meshes
  109797. serializationObject.meshes = [];
  109798. if (this._meshes) {
  109799. for (var m in this._meshes) {
  109800. var mesh = this._meshes[m];
  109801. if (mesh) {
  109802. serializationObject.meshes.push({
  109803. glowEmissiveOnly: mesh.glowEmissiveOnly,
  109804. color: mesh.color.asArray(),
  109805. meshId: mesh.mesh.id
  109806. });
  109807. }
  109808. }
  109809. }
  109810. // Excluded meshes
  109811. serializationObject.excludedMeshes = [];
  109812. if (this._excludedMeshes) {
  109813. for (var e in this._excludedMeshes) {
  109814. var excludedMesh = this._excludedMeshes[e];
  109815. if (excludedMesh) {
  109816. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  109817. }
  109818. }
  109819. }
  109820. return serializationObject;
  109821. };
  109822. /**
  109823. * Creates a Highlight layer from parsed Highlight layer data
  109824. * @param parsedHightlightLayer defines the Highlight layer data
  109825. * @param scene defines the current scene
  109826. * @param rootUrl defines the root URL containing the Highlight layer information
  109827. * @returns a parsed Highlight layer
  109828. */
  109829. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  109830. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  109831. var index;
  109832. // Excluded meshes
  109833. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  109834. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  109835. if (mesh) {
  109836. hl.addExcludedMesh(mesh);
  109837. }
  109838. }
  109839. // Included meshes
  109840. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  109841. var highlightedMesh = parsedHightlightLayer.meshes[index];
  109842. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  109843. if (mesh) {
  109844. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  109845. }
  109846. }
  109847. return hl;
  109848. };
  109849. /**
  109850. * Effect Name of the highlight layer.
  109851. */
  109852. HighlightLayer.EffectName = "HighlightLayer";
  109853. /**
  109854. * The neutral color used during the preparation of the glow effect.
  109855. * This is black by default as the blend operation is a blend operation.
  109856. */
  109857. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  109858. /**
  109859. * Stencil value used for glowing meshes.
  109860. */
  109861. HighlightLayer.GlowingMeshStencilReference = 0x02;
  109862. /**
  109863. * Stencil value used for the other meshes in the scene.
  109864. */
  109865. HighlightLayer.NormalMeshStencilReference = 0x01;
  109866. __decorate([
  109867. BABYLON.serialize()
  109868. ], HighlightLayer.prototype, "innerGlow", void 0);
  109869. __decorate([
  109870. BABYLON.serialize()
  109871. ], HighlightLayer.prototype, "outerGlow", void 0);
  109872. __decorate([
  109873. BABYLON.serialize()
  109874. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  109875. __decorate([
  109876. BABYLON.serialize()
  109877. ], HighlightLayer.prototype, "blurVerticalSize", null);
  109878. __decorate([
  109879. BABYLON.serialize("options")
  109880. ], HighlightLayer.prototype, "_options", void 0);
  109881. return HighlightLayer;
  109882. }(BABYLON.EffectLayer));
  109883. BABYLON.HighlightLayer = HighlightLayer;
  109884. })(BABYLON || (BABYLON = {}));
  109885. //# sourceMappingURL=babylon.highlightLayer.js.map
  109886. var BABYLON;
  109887. (function (BABYLON) {
  109888. BABYLON.AbstractScene.prototype.getGlowLayerByName = function (name) {
  109889. for (var index = 0; index < this.effectLayers.length; index++) {
  109890. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === GlowLayer.EffectName) {
  109891. return this.effectLayers[index];
  109892. }
  109893. }
  109894. return null;
  109895. };
  109896. /**
  109897. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  109898. *
  109899. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  109900. * glowy meshes to your scene.
  109901. *
  109902. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  109903. */
  109904. var GlowLayer = /** @class */ (function (_super) {
  109905. __extends(GlowLayer, _super);
  109906. /**
  109907. * Instantiates a new glow Layer and references it to the scene.
  109908. * @param name The name of the layer
  109909. * @param scene The scene to use the layer in
  109910. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  109911. */
  109912. function GlowLayer(name, scene, options) {
  109913. var _this = _super.call(this, name, scene) || this;
  109914. _this._intensity = 1.0;
  109915. _this._includedOnlyMeshes = [];
  109916. _this._excludedMeshes = [];
  109917. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  109918. // Adapt options
  109919. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1, renderingGroupId: -1 }, options);
  109920. // Initialize the layer
  109921. _this._init({
  109922. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  109923. camera: _this._options.camera,
  109924. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  109925. mainTextureRatio: _this._options.mainTextureRatio,
  109926. renderingGroupId: _this._options.renderingGroupId
  109927. });
  109928. return _this;
  109929. }
  109930. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  109931. /**
  109932. * Gets the kernel size of the blur.
  109933. */
  109934. get: function () {
  109935. return this._horizontalBlurPostprocess1.kernel;
  109936. },
  109937. /**
  109938. * Sets the kernel size of the blur.
  109939. */
  109940. set: function (value) {
  109941. this._horizontalBlurPostprocess1.kernel = value;
  109942. this._verticalBlurPostprocess1.kernel = value;
  109943. this._horizontalBlurPostprocess2.kernel = value;
  109944. this._verticalBlurPostprocess2.kernel = value;
  109945. },
  109946. enumerable: true,
  109947. configurable: true
  109948. });
  109949. Object.defineProperty(GlowLayer.prototype, "intensity", {
  109950. /**
  109951. * Gets the glow intensity.
  109952. */
  109953. get: function () {
  109954. return this._intensity;
  109955. },
  109956. /**
  109957. * Sets the glow intensity.
  109958. */
  109959. set: function (value) {
  109960. this._intensity = value;
  109961. },
  109962. enumerable: true,
  109963. configurable: true
  109964. });
  109965. /**
  109966. * Get the effect name of the layer.
  109967. * @return The effect name
  109968. */
  109969. GlowLayer.prototype.getEffectName = function () {
  109970. return GlowLayer.EffectName;
  109971. };
  109972. /**
  109973. * Create the merge effect. This is the shader use to blit the information back
  109974. * to the main canvas at the end of the scene rendering.
  109975. */
  109976. GlowLayer.prototype._createMergeEffect = function () {
  109977. // Effect
  109978. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  109979. };
  109980. /**
  109981. * Creates the render target textures and post processes used in the glow layer.
  109982. */
  109983. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  109984. var _this = this;
  109985. var blurTextureWidth = this._mainTextureDesiredSize.width;
  109986. var blurTextureHeight = this._mainTextureDesiredSize.height;
  109987. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  109988. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  109989. var textureType = 0;
  109990. if (this._engine.getCaps().textureHalfFloatRender) {
  109991. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  109992. }
  109993. else {
  109994. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  109995. }
  109996. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  109997. width: blurTextureWidth,
  109998. height: blurTextureHeight
  109999. }, this._scene, false, true, textureType);
  110000. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  110001. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  110002. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  110003. this._blurTexture1.renderParticles = false;
  110004. this._blurTexture1.ignoreCameraViewport = true;
  110005. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  110006. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  110007. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  110008. width: blurTextureWidth2,
  110009. height: blurTextureHeight2
  110010. }, this._scene, false, true, textureType);
  110011. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  110012. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  110013. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  110014. this._blurTexture2.renderParticles = false;
  110015. this._blurTexture2.ignoreCameraViewport = true;
  110016. this._textures = [this._blurTexture1, this._blurTexture2];
  110017. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  110018. width: blurTextureWidth,
  110019. height: blurTextureHeight
  110020. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  110021. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  110022. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  110023. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  110024. effect.setTexture("textureSampler", _this._mainTexture);
  110025. });
  110026. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  110027. width: blurTextureWidth,
  110028. height: blurTextureHeight
  110029. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  110030. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  110031. width: blurTextureWidth2,
  110032. height: blurTextureHeight2
  110033. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  110034. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  110035. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  110036. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  110037. effect.setTexture("textureSampler", _this._blurTexture1);
  110038. });
  110039. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  110040. width: blurTextureWidth2,
  110041. height: blurTextureHeight2
  110042. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  110043. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  110044. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  110045. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  110046. this._mainTexture.samples = this._options.mainTextureSamples;
  110047. this._mainTexture.onAfterUnbindObservable.add(function () {
  110048. var internalTexture = _this._blurTexture1.getInternalTexture();
  110049. if (internalTexture) {
  110050. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  110051. internalTexture = _this._blurTexture2.getInternalTexture();
  110052. if (internalTexture) {
  110053. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  110054. }
  110055. }
  110056. });
  110057. // Prevent autoClear.
  110058. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  110059. };
  110060. /**
  110061. * Checks for the readiness of the element composing the layer.
  110062. * @param subMesh the mesh to check for
  110063. * @param useInstances specify wether or not to use instances to render the mesh
  110064. * @param emissiveTexture the associated emissive texture used to generate the glow
  110065. * @return true if ready otherwise, false
  110066. */
  110067. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  110068. var material = subMesh.getMaterial();
  110069. var mesh = subMesh.getRenderingMesh();
  110070. if (!material || !mesh) {
  110071. return false;
  110072. }
  110073. var emissiveTexture = material.emissiveTexture;
  110074. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  110075. };
  110076. /**
  110077. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  110078. */
  110079. GlowLayer.prototype.needStencil = function () {
  110080. return false;
  110081. };
  110082. /**
  110083. * Implementation specific of rendering the generating effect on the main canvas.
  110084. * @param effect The effect used to render through
  110085. */
  110086. GlowLayer.prototype._internalRender = function (effect) {
  110087. // Texture
  110088. effect.setTexture("textureSampler", this._blurTexture1);
  110089. effect.setTexture("textureSampler2", this._blurTexture2);
  110090. effect.setFloat("offset", this._intensity);
  110091. // Cache
  110092. var engine = this._engine;
  110093. var previousStencilBuffer = engine.getStencilBuffer();
  110094. // Draw order
  110095. engine.setStencilBuffer(false);
  110096. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  110097. // Draw order
  110098. engine.setStencilBuffer(previousStencilBuffer);
  110099. };
  110100. /**
  110101. * Sets the required values for both the emissive texture and and the main color.
  110102. */
  110103. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  110104. var textureLevel = 1.0;
  110105. if (this.customEmissiveTextureSelector) {
  110106. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  110107. }
  110108. else {
  110109. if (material) {
  110110. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  110111. if (this._emissiveTextureAndColor.texture) {
  110112. textureLevel = this._emissiveTextureAndColor.texture.level;
  110113. }
  110114. }
  110115. else {
  110116. this._emissiveTextureAndColor.texture = null;
  110117. }
  110118. }
  110119. if (this.customEmissiveColorSelector) {
  110120. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  110121. }
  110122. else {
  110123. if (material.emissiveColor) {
  110124. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  110125. }
  110126. else {
  110127. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  110128. }
  110129. }
  110130. };
  110131. /**
  110132. * Returns true if the mesh should render, otherwise false.
  110133. * @param mesh The mesh to render
  110134. * @returns true if it should render otherwise false
  110135. */
  110136. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  110137. return this.hasMesh(mesh);
  110138. };
  110139. /**
  110140. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  110141. * @param mesh The mesh to exclude from the glow layer
  110142. */
  110143. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  110144. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  110145. this._excludedMeshes.push(mesh.uniqueId);
  110146. }
  110147. };
  110148. /**
  110149. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  110150. * @param mesh The mesh to remove
  110151. */
  110152. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  110153. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  110154. if (index !== -1) {
  110155. this._excludedMeshes.splice(index, 1);
  110156. }
  110157. };
  110158. /**
  110159. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  110160. * @param mesh The mesh to include in the glow layer
  110161. */
  110162. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  110163. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  110164. this._includedOnlyMeshes.push(mesh.uniqueId);
  110165. }
  110166. };
  110167. /**
  110168. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  110169. * @param mesh The mesh to remove
  110170. */
  110171. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  110172. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  110173. if (index !== -1) {
  110174. this._includedOnlyMeshes.splice(index, 1);
  110175. }
  110176. };
  110177. /**
  110178. * Determine if a given mesh will be used in the glow layer
  110179. * @param mesh The mesh to test
  110180. * @returns true if the mesh will be highlighted by the current glow layer
  110181. */
  110182. GlowLayer.prototype.hasMesh = function (mesh) {
  110183. if (!_super.prototype.hasMesh.call(this, mesh)) {
  110184. return false;
  110185. }
  110186. // Included Mesh
  110187. if (this._includedOnlyMeshes.length) {
  110188. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  110189. }
  110190. ;
  110191. // Excluded Mesh
  110192. if (this._excludedMeshes.length) {
  110193. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  110194. }
  110195. ;
  110196. return true;
  110197. };
  110198. /**
  110199. * Free any resources and references associated to a mesh.
  110200. * Internal use
  110201. * @param mesh The mesh to free.
  110202. * @hidden
  110203. */
  110204. GlowLayer.prototype._disposeMesh = function (mesh) {
  110205. this.removeIncludedOnlyMesh(mesh);
  110206. this.removeExcludedMesh(mesh);
  110207. };
  110208. /**
  110209. * Gets the class name of the effect layer
  110210. * @returns the string with the class name of the effect layer
  110211. */
  110212. GlowLayer.prototype.getClassName = function () {
  110213. return "GlowLayer";
  110214. };
  110215. /**
  110216. * Serializes this glow layer
  110217. * @returns a serialized glow layer object
  110218. */
  110219. GlowLayer.prototype.serialize = function () {
  110220. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  110221. serializationObject.customType = "BABYLON.GlowLayer";
  110222. var index;
  110223. // Included meshes
  110224. serializationObject.includedMeshes = [];
  110225. if (this._includedOnlyMeshes.length) {
  110226. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  110227. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  110228. if (mesh) {
  110229. serializationObject.includedMeshes.push(mesh.id);
  110230. }
  110231. }
  110232. }
  110233. // Excluded meshes
  110234. serializationObject.excludedMeshes = [];
  110235. if (this._excludedMeshes.length) {
  110236. for (index = 0; index < this._excludedMeshes.length; index++) {
  110237. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  110238. if (mesh) {
  110239. serializationObject.excludedMeshes.push(mesh.id);
  110240. }
  110241. }
  110242. }
  110243. return serializationObject;
  110244. };
  110245. /**
  110246. * Creates a Glow Layer from parsed glow layer data
  110247. * @param parsedGlowLayer defines glow layer data
  110248. * @param scene defines the current scene
  110249. * @param rootUrl defines the root URL containing the glow layer information
  110250. * @returns a parsed Glow Layer
  110251. */
  110252. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  110253. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  110254. var index;
  110255. // Excluded meshes
  110256. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  110257. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  110258. if (mesh) {
  110259. gl.addExcludedMesh(mesh);
  110260. }
  110261. }
  110262. // Included meshes
  110263. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  110264. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  110265. if (mesh) {
  110266. gl.addIncludedOnlyMesh(mesh);
  110267. }
  110268. }
  110269. return gl;
  110270. };
  110271. /**
  110272. * Effect Name of the layer.
  110273. */
  110274. GlowLayer.EffectName = "GlowLayer";
  110275. /**
  110276. * The default blur kernel size used for the glow.
  110277. */
  110278. GlowLayer.DefaultBlurKernelSize = 32;
  110279. /**
  110280. * The default texture size ratio used for the glow.
  110281. */
  110282. GlowLayer.DefaultTextureRatio = 0.5;
  110283. __decorate([
  110284. BABYLON.serialize()
  110285. ], GlowLayer.prototype, "blurKernelSize", null);
  110286. __decorate([
  110287. BABYLON.serialize()
  110288. ], GlowLayer.prototype, "intensity", null);
  110289. __decorate([
  110290. BABYLON.serialize("options")
  110291. ], GlowLayer.prototype, "_options", void 0);
  110292. return GlowLayer;
  110293. }(BABYLON.EffectLayer));
  110294. BABYLON.GlowLayer = GlowLayer;
  110295. })(BABYLON || (BABYLON = {}));
  110296. //# sourceMappingURL=babylon.glowLayer.js.map
  110297. var BABYLON;
  110298. (function (BABYLON) {
  110299. /**
  110300. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  110301. */
  110302. var AssetTaskState;
  110303. (function (AssetTaskState) {
  110304. /**
  110305. * Initialization
  110306. */
  110307. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  110308. /**
  110309. * Running
  110310. */
  110311. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  110312. /**
  110313. * Done
  110314. */
  110315. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  110316. /**
  110317. * Error
  110318. */
  110319. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  110320. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  110321. /**
  110322. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  110323. */
  110324. var AbstractAssetTask = /** @class */ (function () {
  110325. /**
  110326. * Creates a new {BABYLON.AssetsManager}
  110327. * @param name defines the name of the task
  110328. */
  110329. function AbstractAssetTask(
  110330. /**
  110331. * Task name
  110332. */ name) {
  110333. this.name = name;
  110334. this._isCompleted = false;
  110335. this._taskState = AssetTaskState.INIT;
  110336. }
  110337. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  110338. /**
  110339. * Get if the task is completed
  110340. */
  110341. get: function () {
  110342. return this._isCompleted;
  110343. },
  110344. enumerable: true,
  110345. configurable: true
  110346. });
  110347. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  110348. /**
  110349. * Gets the current state of the task
  110350. */
  110351. get: function () {
  110352. return this._taskState;
  110353. },
  110354. enumerable: true,
  110355. configurable: true
  110356. });
  110357. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  110358. /**
  110359. * Gets the current error object (if task is in error)
  110360. */
  110361. get: function () {
  110362. return this._errorObject;
  110363. },
  110364. enumerable: true,
  110365. configurable: true
  110366. });
  110367. /**
  110368. * Internal only
  110369. * @hidden
  110370. */
  110371. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  110372. if (this._errorObject) {
  110373. return;
  110374. }
  110375. this._errorObject = {
  110376. message: message,
  110377. exception: exception
  110378. };
  110379. };
  110380. /**
  110381. * Execute the current task
  110382. * @param scene defines the scene where you want your assets to be loaded
  110383. * @param onSuccess is a callback called when the task is successfully executed
  110384. * @param onError is a callback called if an error occurs
  110385. */
  110386. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  110387. var _this = this;
  110388. this._taskState = AssetTaskState.RUNNING;
  110389. this.runTask(scene, function () {
  110390. _this.onDoneCallback(onSuccess, onError);
  110391. }, function (msg, exception) {
  110392. _this.onErrorCallback(onError, msg, exception);
  110393. });
  110394. };
  110395. /**
  110396. * Execute the current task
  110397. * @param scene defines the scene where you want your assets to be loaded
  110398. * @param onSuccess is a callback called when the task is successfully executed
  110399. * @param onError is a callback called if an error occurs
  110400. */
  110401. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  110402. throw new Error("runTask is not implemented");
  110403. };
  110404. /**
  110405. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  110406. * This can be used with failed tasks that have the reason for failure fixed.
  110407. */
  110408. AbstractAssetTask.prototype.reset = function () {
  110409. this._taskState = AssetTaskState.INIT;
  110410. };
  110411. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  110412. this._taskState = AssetTaskState.ERROR;
  110413. this._errorObject = {
  110414. message: message,
  110415. exception: exception
  110416. };
  110417. if (this.onError) {
  110418. this.onError(this, message, exception);
  110419. }
  110420. onError();
  110421. };
  110422. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  110423. try {
  110424. this._taskState = AssetTaskState.DONE;
  110425. this._isCompleted = true;
  110426. if (this.onSuccess) {
  110427. this.onSuccess(this);
  110428. }
  110429. onSuccess();
  110430. }
  110431. catch (e) {
  110432. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  110433. }
  110434. };
  110435. return AbstractAssetTask;
  110436. }());
  110437. BABYLON.AbstractAssetTask = AbstractAssetTask;
  110438. /**
  110439. * Class used to share progress information about assets loading
  110440. */
  110441. var AssetsProgressEvent = /** @class */ (function () {
  110442. /**
  110443. * Creates a {BABYLON.AssetsProgressEvent}
  110444. * @param remainingCount defines the number of remaining tasks to process
  110445. * @param totalCount defines the total number of tasks
  110446. * @param task defines the task that was just processed
  110447. */
  110448. function AssetsProgressEvent(remainingCount, totalCount, task) {
  110449. this.remainingCount = remainingCount;
  110450. this.totalCount = totalCount;
  110451. this.task = task;
  110452. }
  110453. return AssetsProgressEvent;
  110454. }());
  110455. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  110456. /**
  110457. * Define a task used by {BABYLON.AssetsManager} to load meshes
  110458. */
  110459. var MeshAssetTask = /** @class */ (function (_super) {
  110460. __extends(MeshAssetTask, _super);
  110461. /**
  110462. * Creates a new {BABYLON.MeshAssetTask}
  110463. * @param name defines the name of the task
  110464. * @param meshesNames defines the list of mesh's names you want to load
  110465. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  110466. * @param sceneFilename defines the filename of the scene to load from
  110467. */
  110468. function MeshAssetTask(
  110469. /**
  110470. * Defines the name of the task
  110471. */
  110472. name,
  110473. /**
  110474. * Defines the list of mesh's names you want to load
  110475. */
  110476. meshesNames,
  110477. /**
  110478. * Defines the root url to use as a base to load your meshes and associated resources
  110479. */
  110480. rootUrl,
  110481. /**
  110482. * Defines the filename of the scene to load from
  110483. */
  110484. sceneFilename) {
  110485. var _this = _super.call(this, name) || this;
  110486. _this.name = name;
  110487. _this.meshesNames = meshesNames;
  110488. _this.rootUrl = rootUrl;
  110489. _this.sceneFilename = sceneFilename;
  110490. return _this;
  110491. }
  110492. /**
  110493. * Execute the current task
  110494. * @param scene defines the scene where you want your assets to be loaded
  110495. * @param onSuccess is a callback called when the task is successfully executed
  110496. * @param onError is a callback called if an error occurs
  110497. */
  110498. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  110499. var _this = this;
  110500. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  110501. _this.loadedMeshes = meshes;
  110502. _this.loadedParticleSystems = particleSystems;
  110503. _this.loadedSkeletons = skeletons;
  110504. onSuccess();
  110505. }, null, function (scene, message, exception) {
  110506. onError(message, exception);
  110507. });
  110508. };
  110509. return MeshAssetTask;
  110510. }(AbstractAssetTask));
  110511. BABYLON.MeshAssetTask = MeshAssetTask;
  110512. /**
  110513. * Define a task used by {BABYLON.AssetsManager} to load text content
  110514. */
  110515. var TextFileAssetTask = /** @class */ (function (_super) {
  110516. __extends(TextFileAssetTask, _super);
  110517. /**
  110518. * Creates a new TextFileAssetTask object
  110519. * @param name defines the name of the task
  110520. * @param url defines the location of the file to load
  110521. */
  110522. function TextFileAssetTask(
  110523. /**
  110524. * Defines the name of the task
  110525. */
  110526. name,
  110527. /**
  110528. * Defines the location of the file to load
  110529. */
  110530. url) {
  110531. var _this = _super.call(this, name) || this;
  110532. _this.name = name;
  110533. _this.url = url;
  110534. return _this;
  110535. }
  110536. /**
  110537. * Execute the current task
  110538. * @param scene defines the scene where you want your assets to be loaded
  110539. * @param onSuccess is a callback called when the task is successfully executed
  110540. * @param onError is a callback called if an error occurs
  110541. */
  110542. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  110543. var _this = this;
  110544. scene._loadFile(this.url, function (data) {
  110545. _this.text = data;
  110546. onSuccess();
  110547. }, undefined, false, false, function (request, exception) {
  110548. if (request) {
  110549. onError(request.status + " " + request.statusText, exception);
  110550. }
  110551. });
  110552. };
  110553. return TextFileAssetTask;
  110554. }(AbstractAssetTask));
  110555. BABYLON.TextFileAssetTask = TextFileAssetTask;
  110556. /**
  110557. * Define a task used by {BABYLON.AssetsManager} to load binary data
  110558. */
  110559. var BinaryFileAssetTask = /** @class */ (function (_super) {
  110560. __extends(BinaryFileAssetTask, _super);
  110561. /**
  110562. * Creates a new BinaryFileAssetTask object
  110563. * @param name defines the name of the new task
  110564. * @param url defines the location of the file to load
  110565. */
  110566. function BinaryFileAssetTask(
  110567. /**
  110568. * Defines the name of the task
  110569. */
  110570. name,
  110571. /**
  110572. * Defines the location of the file to load
  110573. */
  110574. url) {
  110575. var _this = _super.call(this, name) || this;
  110576. _this.name = name;
  110577. _this.url = url;
  110578. return _this;
  110579. }
  110580. /**
  110581. * Execute the current task
  110582. * @param scene defines the scene where you want your assets to be loaded
  110583. * @param onSuccess is a callback called when the task is successfully executed
  110584. * @param onError is a callback called if an error occurs
  110585. */
  110586. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  110587. var _this = this;
  110588. scene._loadFile(this.url, function (data) {
  110589. _this.data = data;
  110590. onSuccess();
  110591. }, undefined, true, true, function (request, exception) {
  110592. if (request) {
  110593. onError(request.status + " " + request.statusText, exception);
  110594. }
  110595. });
  110596. };
  110597. return BinaryFileAssetTask;
  110598. }(AbstractAssetTask));
  110599. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  110600. /**
  110601. * Define a task used by {BABYLON.AssetsManager} to load images
  110602. */
  110603. var ImageAssetTask = /** @class */ (function (_super) {
  110604. __extends(ImageAssetTask, _super);
  110605. /**
  110606. * Creates a new ImageAssetTask
  110607. * @param name defines the name of the task
  110608. * @param url defines the location of the image to load
  110609. */
  110610. function ImageAssetTask(
  110611. /**
  110612. * Defines the name of the task
  110613. */
  110614. name,
  110615. /**
  110616. * Defines the location of the image to load
  110617. */
  110618. url) {
  110619. var _this = _super.call(this, name) || this;
  110620. _this.name = name;
  110621. _this.url = url;
  110622. return _this;
  110623. }
  110624. /**
  110625. * Execute the current task
  110626. * @param scene defines the scene where you want your assets to be loaded
  110627. * @param onSuccess is a callback called when the task is successfully executed
  110628. * @param onError is a callback called if an error occurs
  110629. */
  110630. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  110631. var _this = this;
  110632. var img = new Image();
  110633. BABYLON.Tools.SetCorsBehavior(this.url, img);
  110634. img.onload = function () {
  110635. _this.image = img;
  110636. onSuccess();
  110637. };
  110638. img.onerror = function (err) {
  110639. onError("Error loading image", err);
  110640. };
  110641. img.src = this.url;
  110642. };
  110643. return ImageAssetTask;
  110644. }(AbstractAssetTask));
  110645. BABYLON.ImageAssetTask = ImageAssetTask;
  110646. /**
  110647. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  110648. */
  110649. var TextureAssetTask = /** @class */ (function (_super) {
  110650. __extends(TextureAssetTask, _super);
  110651. /**
  110652. * Creates a new TextureAssetTask object
  110653. * @param name defines the name of the task
  110654. * @param url defines the location of the file to load
  110655. * @param noMipmap defines if mipmap should not be generated (default is false)
  110656. * @param invertY defines if texture must be inverted on Y axis (default is false)
  110657. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  110658. */
  110659. function TextureAssetTask(
  110660. /**
  110661. * Defines the name of the task
  110662. */
  110663. name,
  110664. /**
  110665. * Defines the location of the file to load
  110666. */
  110667. url,
  110668. /**
  110669. * Defines if mipmap should not be generated (default is false)
  110670. */
  110671. noMipmap,
  110672. /**
  110673. * Defines if texture must be inverted on Y axis (default is false)
  110674. */
  110675. invertY,
  110676. /**
  110677. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  110678. */
  110679. samplingMode) {
  110680. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  110681. var _this = _super.call(this, name) || this;
  110682. _this.name = name;
  110683. _this.url = url;
  110684. _this.noMipmap = noMipmap;
  110685. _this.invertY = invertY;
  110686. _this.samplingMode = samplingMode;
  110687. return _this;
  110688. }
  110689. /**
  110690. * Execute the current task
  110691. * @param scene defines the scene where you want your assets to be loaded
  110692. * @param onSuccess is a callback called when the task is successfully executed
  110693. * @param onError is a callback called if an error occurs
  110694. */
  110695. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  110696. var onload = function () {
  110697. onSuccess();
  110698. };
  110699. var onerror = function (message, exception) {
  110700. onError(message, exception);
  110701. };
  110702. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  110703. };
  110704. return TextureAssetTask;
  110705. }(AbstractAssetTask));
  110706. BABYLON.TextureAssetTask = TextureAssetTask;
  110707. /**
  110708. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  110709. */
  110710. var CubeTextureAssetTask = /** @class */ (function (_super) {
  110711. __extends(CubeTextureAssetTask, _super);
  110712. /**
  110713. * Creates a new CubeTextureAssetTask
  110714. * @param name defines the name of the task
  110715. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  110716. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  110717. * @param noMipmap defines if mipmaps should not be generated (default is false)
  110718. * @param files defines the explicit list of files (undefined by default)
  110719. */
  110720. function CubeTextureAssetTask(
  110721. /**
  110722. * Defines the name of the task
  110723. */
  110724. name,
  110725. /**
  110726. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  110727. */
  110728. url,
  110729. /**
  110730. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  110731. */
  110732. extensions,
  110733. /**
  110734. * Defines if mipmaps should not be generated (default is false)
  110735. */
  110736. noMipmap,
  110737. /**
  110738. * Defines the explicit list of files (undefined by default)
  110739. */
  110740. files) {
  110741. var _this = _super.call(this, name) || this;
  110742. _this.name = name;
  110743. _this.url = url;
  110744. _this.extensions = extensions;
  110745. _this.noMipmap = noMipmap;
  110746. _this.files = files;
  110747. return _this;
  110748. }
  110749. /**
  110750. * Execute the current task
  110751. * @param scene defines the scene where you want your assets to be loaded
  110752. * @param onSuccess is a callback called when the task is successfully executed
  110753. * @param onError is a callback called if an error occurs
  110754. */
  110755. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  110756. var onload = function () {
  110757. onSuccess();
  110758. };
  110759. var onerror = function (message, exception) {
  110760. onError(message, exception);
  110761. };
  110762. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  110763. };
  110764. return CubeTextureAssetTask;
  110765. }(AbstractAssetTask));
  110766. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  110767. /**
  110768. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  110769. */
  110770. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  110771. __extends(HDRCubeTextureAssetTask, _super);
  110772. /**
  110773. * Creates a new HDRCubeTextureAssetTask object
  110774. * @param name defines the name of the task
  110775. * @param url defines the location of the file to load
  110776. * @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.
  110777. * @param noMipmap defines if mipmaps should not be generated (default is false)
  110778. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  110779. * @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)
  110780. * @param reserved Internal use only
  110781. */
  110782. function HDRCubeTextureAssetTask(
  110783. /**
  110784. * Defines the name of the task
  110785. */
  110786. name,
  110787. /**
  110788. * Defines the location of the file to load
  110789. */
  110790. url,
  110791. /**
  110792. * Defines the desired size (the more it increases the longer the generation will be)
  110793. */
  110794. size,
  110795. /**
  110796. * Defines if mipmaps should not be generated (default is false)
  110797. */
  110798. noMipmap,
  110799. /**
  110800. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  110801. */
  110802. generateHarmonics,
  110803. /**
  110804. * 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)
  110805. */
  110806. gammaSpace,
  110807. /**
  110808. * Internal Use Only
  110809. */
  110810. reserved) {
  110811. if (noMipmap === void 0) { noMipmap = false; }
  110812. if (generateHarmonics === void 0) { generateHarmonics = true; }
  110813. if (gammaSpace === void 0) { gammaSpace = false; }
  110814. if (reserved === void 0) { reserved = false; }
  110815. var _this = _super.call(this, name) || this;
  110816. _this.name = name;
  110817. _this.url = url;
  110818. _this.size = size;
  110819. _this.noMipmap = noMipmap;
  110820. _this.generateHarmonics = generateHarmonics;
  110821. _this.gammaSpace = gammaSpace;
  110822. _this.reserved = reserved;
  110823. return _this;
  110824. }
  110825. /**
  110826. * Execute the current task
  110827. * @param scene defines the scene where you want your assets to be loaded
  110828. * @param onSuccess is a callback called when the task is successfully executed
  110829. * @param onError is a callback called if an error occurs
  110830. */
  110831. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  110832. var onload = function () {
  110833. onSuccess();
  110834. };
  110835. var onerror = function (message, exception) {
  110836. onError(message, exception);
  110837. };
  110838. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  110839. };
  110840. return HDRCubeTextureAssetTask;
  110841. }(AbstractAssetTask));
  110842. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  110843. /**
  110844. * This class can be used to easily import assets into a scene
  110845. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  110846. */
  110847. var AssetsManager = /** @class */ (function () {
  110848. /**
  110849. * Creates a new AssetsManager
  110850. * @param scene defines the scene to work on
  110851. */
  110852. function AssetsManager(scene) {
  110853. this._isLoading = false;
  110854. this._tasks = new Array();
  110855. this._waitingTasksCount = 0;
  110856. this._totalTasksCount = 0;
  110857. /**
  110858. * Observable called when all tasks are processed
  110859. */
  110860. this.onTaskSuccessObservable = new BABYLON.Observable();
  110861. /**
  110862. * Observable called when a task had an error
  110863. */
  110864. this.onTaskErrorObservable = new BABYLON.Observable();
  110865. /**
  110866. * Observable called when a task is successful
  110867. */
  110868. this.onTasksDoneObservable = new BABYLON.Observable();
  110869. /**
  110870. * Observable called when a task is done (whatever the result is)
  110871. */
  110872. this.onProgressObservable = new BABYLON.Observable();
  110873. /**
  110874. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  110875. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  110876. */
  110877. this.useDefaultLoadingScreen = true;
  110878. this._scene = scene;
  110879. }
  110880. /**
  110881. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  110882. * @param taskName defines the name of the new task
  110883. * @param meshesNames defines the name of meshes to load
  110884. * @param rootUrl defines the root url to use to locate files
  110885. * @param sceneFilename defines the filename of the scene file
  110886. * @returns a new {BABYLON.MeshAssetTask} object
  110887. */
  110888. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  110889. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  110890. this._tasks.push(task);
  110891. return task;
  110892. };
  110893. /**
  110894. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  110895. * @param taskName defines the name of the new task
  110896. * @param url defines the url of the file to load
  110897. * @returns a new {BABYLON.TextFileAssetTask} object
  110898. */
  110899. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  110900. var task = new TextFileAssetTask(taskName, url);
  110901. this._tasks.push(task);
  110902. return task;
  110903. };
  110904. /**
  110905. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  110906. * @param taskName defines the name of the new task
  110907. * @param url defines the url of the file to load
  110908. * @returns a new {BABYLON.BinaryFileAssetTask} object
  110909. */
  110910. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  110911. var task = new BinaryFileAssetTask(taskName, url);
  110912. this._tasks.push(task);
  110913. return task;
  110914. };
  110915. /**
  110916. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  110917. * @param taskName defines the name of the new task
  110918. * @param url defines the url of the file to load
  110919. * @returns a new {BABYLON.ImageAssetTask} object
  110920. */
  110921. AssetsManager.prototype.addImageTask = function (taskName, url) {
  110922. var task = new ImageAssetTask(taskName, url);
  110923. this._tasks.push(task);
  110924. return task;
  110925. };
  110926. /**
  110927. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  110928. * @param taskName defines the name of the new task
  110929. * @param url defines the url of the file to load
  110930. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  110931. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  110932. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  110933. * @returns a new {BABYLON.TextureAssetTask} object
  110934. */
  110935. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  110936. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  110937. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  110938. this._tasks.push(task);
  110939. return task;
  110940. };
  110941. /**
  110942. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  110943. * @param taskName defines the name of the new task
  110944. * @param url defines the url of the file to load
  110945. * @param extensions defines the extension to use to load the cube map (can be null)
  110946. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  110947. * @param files defines the list of files to load (can be null)
  110948. * @returns a new {BABYLON.CubeTextureAssetTask} object
  110949. */
  110950. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  110951. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  110952. this._tasks.push(task);
  110953. return task;
  110954. };
  110955. /**
  110956. *
  110957. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  110958. * @param taskName defines the name of the new task
  110959. * @param url defines the url of the file to load
  110960. * @param size defines the size you want for the cubemap (can be null)
  110961. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  110962. * @param generateHarmonics defines if you want to automatically generate (true by default)
  110963. * @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)
  110964. * @param reserved Internal use only
  110965. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  110966. */
  110967. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  110968. if (noMipmap === void 0) { noMipmap = false; }
  110969. if (generateHarmonics === void 0) { generateHarmonics = true; }
  110970. if (gammaSpace === void 0) { gammaSpace = false; }
  110971. if (reserved === void 0) { reserved = false; }
  110972. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  110973. this._tasks.push(task);
  110974. return task;
  110975. };
  110976. /**
  110977. * Remove a task from the assets manager.
  110978. * @param task the task to remove
  110979. */
  110980. AssetsManager.prototype.removeTask = function (task) {
  110981. var index = this._tasks.indexOf(task);
  110982. if (index > -1) {
  110983. this._tasks.splice(index, 1);
  110984. }
  110985. };
  110986. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  110987. this._waitingTasksCount--;
  110988. try {
  110989. if (this.onProgress) {
  110990. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  110991. }
  110992. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  110993. }
  110994. catch (e) {
  110995. BABYLON.Tools.Error("Error running progress callbacks.");
  110996. console.log(e);
  110997. }
  110998. if (this._waitingTasksCount === 0) {
  110999. try {
  111000. if (this.onFinish) {
  111001. this.onFinish(this._tasks);
  111002. }
  111003. // Let's remove successfull tasks
  111004. var currentTasks = this._tasks.slice();
  111005. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  111006. var task = currentTasks_1[_i];
  111007. if (task.taskState === AssetTaskState.DONE) {
  111008. var index = this._tasks.indexOf(task);
  111009. if (index > -1) {
  111010. this._tasks.splice(index, 1);
  111011. }
  111012. }
  111013. }
  111014. this.onTasksDoneObservable.notifyObservers(this._tasks);
  111015. }
  111016. catch (e) {
  111017. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  111018. console.log(e);
  111019. }
  111020. this._isLoading = false;
  111021. this._scene.getEngine().hideLoadingUI();
  111022. }
  111023. };
  111024. AssetsManager.prototype._runTask = function (task) {
  111025. var _this = this;
  111026. var done = function () {
  111027. try {
  111028. if (_this.onTaskSuccess) {
  111029. _this.onTaskSuccess(task);
  111030. }
  111031. _this.onTaskSuccessObservable.notifyObservers(task);
  111032. _this._decreaseWaitingTasksCount(task);
  111033. }
  111034. catch (e) {
  111035. error("Error executing task success callbacks", e);
  111036. }
  111037. };
  111038. var error = function (message, exception) {
  111039. task._setErrorObject(message, exception);
  111040. if (_this.onTaskError) {
  111041. _this.onTaskError(task);
  111042. }
  111043. _this.onTaskErrorObservable.notifyObservers(task);
  111044. _this._decreaseWaitingTasksCount(task);
  111045. };
  111046. task.run(this._scene, done, error);
  111047. };
  111048. /**
  111049. * Reset the {BABYLON.AssetsManager} and remove all tasks
  111050. * @return the current instance of the {BABYLON.AssetsManager}
  111051. */
  111052. AssetsManager.prototype.reset = function () {
  111053. this._isLoading = false;
  111054. this._tasks = new Array();
  111055. return this;
  111056. };
  111057. /**
  111058. * Start the loading process
  111059. * @return the current instance of the {BABYLON.AssetsManager}
  111060. */
  111061. AssetsManager.prototype.load = function () {
  111062. if (this._isLoading) {
  111063. return this;
  111064. }
  111065. this._isLoading = true;
  111066. this._waitingTasksCount = this._tasks.length;
  111067. this._totalTasksCount = this._tasks.length;
  111068. if (this._waitingTasksCount === 0) {
  111069. this._isLoading = false;
  111070. if (this.onFinish) {
  111071. this.onFinish(this._tasks);
  111072. }
  111073. this.onTasksDoneObservable.notifyObservers(this._tasks);
  111074. return this;
  111075. }
  111076. if (this.useDefaultLoadingScreen) {
  111077. this._scene.getEngine().displayLoadingUI();
  111078. }
  111079. for (var index = 0; index < this._tasks.length; index++) {
  111080. var task = this._tasks[index];
  111081. if (task.taskState === AssetTaskState.INIT) {
  111082. this._runTask(task);
  111083. }
  111084. }
  111085. return this;
  111086. };
  111087. return AssetsManager;
  111088. }());
  111089. BABYLON.AssetsManager = AssetsManager;
  111090. })(BABYLON || (BABYLON = {}));
  111091. //# sourceMappingURL=babylon.assetsManager.js.map
  111092. var BABYLON;
  111093. (function (BABYLON) {
  111094. var serializedGeometries = [];
  111095. var serializeGeometry = function (geometry, serializationGeometries) {
  111096. if (serializedGeometries[geometry.id]) {
  111097. return;
  111098. }
  111099. if (geometry.doNotSerialize) {
  111100. return;
  111101. }
  111102. if (geometry instanceof BABYLON.BoxGeometry) {
  111103. serializationGeometries.boxes.push(geometry.serialize());
  111104. }
  111105. else if (geometry instanceof BABYLON.SphereGeometry) {
  111106. serializationGeometries.spheres.push(geometry.serialize());
  111107. }
  111108. else if (geometry instanceof BABYLON.CylinderGeometry) {
  111109. serializationGeometries.cylinders.push(geometry.serialize());
  111110. }
  111111. else if (geometry instanceof BABYLON.TorusGeometry) {
  111112. serializationGeometries.toruses.push(geometry.serialize());
  111113. }
  111114. else if (geometry instanceof BABYLON.GroundGeometry) {
  111115. serializationGeometries.grounds.push(geometry.serialize());
  111116. }
  111117. else if (geometry instanceof BABYLON.Plane) {
  111118. serializationGeometries.planes.push(geometry.serialize());
  111119. }
  111120. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  111121. serializationGeometries.torusKnots.push(geometry.serialize());
  111122. }
  111123. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  111124. throw new Error("Unknown primitive type");
  111125. }
  111126. else {
  111127. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  111128. }
  111129. serializedGeometries[geometry.id] = true;
  111130. };
  111131. var serializeMesh = function (mesh, serializationScene) {
  111132. var serializationObject = {};
  111133. // Geometry
  111134. var geometry = mesh._geometry;
  111135. if (geometry) {
  111136. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  111137. // 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
  111138. serializeGeometry(geometry, serializationScene.geometries);
  111139. }
  111140. }
  111141. // Custom
  111142. if (mesh.serialize) {
  111143. mesh.serialize(serializationObject);
  111144. }
  111145. return serializationObject;
  111146. };
  111147. var finalizeSingleMesh = function (mesh, serializationObject) {
  111148. //only works if the mesh is already loaded
  111149. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  111150. //serialize material
  111151. if (mesh.material) {
  111152. if (mesh.material instanceof BABYLON.MultiMaterial) {
  111153. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  111154. serializationObject.materials = serializationObject.materials || [];
  111155. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  111156. serializationObject.multiMaterials.push(mesh.material.serialize());
  111157. var _loop_1 = function (submaterial) {
  111158. if (submaterial) {
  111159. if (!serializationObject.materials.some(function (mat) { return (mat.id === submaterial.id); })) {
  111160. serializationObject.materials.push(submaterial.serialize());
  111161. }
  111162. }
  111163. };
  111164. for (var _i = 0, _a = mesh.material.subMaterials; _i < _a.length; _i++) {
  111165. var submaterial = _a[_i];
  111166. _loop_1(submaterial);
  111167. }
  111168. }
  111169. }
  111170. else {
  111171. serializationObject.materials = serializationObject.materials || [];
  111172. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  111173. serializationObject.materials.push(mesh.material.serialize());
  111174. }
  111175. }
  111176. }
  111177. //serialize geometry
  111178. var geometry = mesh._geometry;
  111179. if (geometry) {
  111180. if (!serializationObject.geometries) {
  111181. serializationObject.geometries = {};
  111182. serializationObject.geometries.boxes = [];
  111183. serializationObject.geometries.spheres = [];
  111184. serializationObject.geometries.cylinders = [];
  111185. serializationObject.geometries.toruses = [];
  111186. serializationObject.geometries.grounds = [];
  111187. serializationObject.geometries.planes = [];
  111188. serializationObject.geometries.torusKnots = [];
  111189. serializationObject.geometries.vertexData = [];
  111190. }
  111191. serializeGeometry(geometry, serializationObject.geometries);
  111192. }
  111193. // Skeletons
  111194. if (mesh.skeleton) {
  111195. serializationObject.skeletons = serializationObject.skeletons || [];
  111196. serializationObject.skeletons.push(mesh.skeleton.serialize());
  111197. }
  111198. //serialize the actual mesh
  111199. serializationObject.meshes = serializationObject.meshes || [];
  111200. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  111201. }
  111202. };
  111203. /**
  111204. * Class used to serialize a scene into a string
  111205. */
  111206. var SceneSerializer = /** @class */ (function () {
  111207. function SceneSerializer() {
  111208. }
  111209. /**
  111210. * Clear cache used by a previous serialization
  111211. */
  111212. SceneSerializer.ClearCache = function () {
  111213. serializedGeometries = [];
  111214. };
  111215. /**
  111216. * Serialize a scene into a JSON compatible object
  111217. * @param scene defines the scene to serialize
  111218. * @returns a JSON compatible object
  111219. */
  111220. SceneSerializer.Serialize = function (scene) {
  111221. var serializationObject = {};
  111222. SceneSerializer.ClearCache();
  111223. // Scene
  111224. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  111225. serializationObject.autoClear = scene.autoClear;
  111226. serializationObject.clearColor = scene.clearColor.asArray();
  111227. serializationObject.ambientColor = scene.ambientColor.asArray();
  111228. serializationObject.gravity = scene.gravity.asArray();
  111229. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  111230. serializationObject.workerCollisions = scene.workerCollisions;
  111231. // Fog
  111232. if (scene.fogMode && scene.fogMode !== 0) {
  111233. serializationObject.fogMode = scene.fogMode;
  111234. serializationObject.fogColor = scene.fogColor.asArray();
  111235. serializationObject.fogStart = scene.fogStart;
  111236. serializationObject.fogEnd = scene.fogEnd;
  111237. serializationObject.fogDensity = scene.fogDensity;
  111238. }
  111239. //Physics
  111240. if (scene.isPhysicsEnabled()) {
  111241. var physicEngine = scene.getPhysicsEngine();
  111242. if (physicEngine) {
  111243. serializationObject.physicsEnabled = true;
  111244. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  111245. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  111246. }
  111247. }
  111248. // Metadata
  111249. if (scene.metadata) {
  111250. serializationObject.metadata = scene.metadata;
  111251. }
  111252. // Morph targets
  111253. serializationObject.morphTargetManagers = [];
  111254. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  111255. var abstractMesh = _a[_i];
  111256. var manager = abstractMesh.morphTargetManager;
  111257. if (manager) {
  111258. serializationObject.morphTargetManagers.push(manager.serialize());
  111259. }
  111260. }
  111261. // Lights
  111262. serializationObject.lights = [];
  111263. var index;
  111264. var light;
  111265. for (index = 0; index < scene.lights.length; index++) {
  111266. light = scene.lights[index];
  111267. if (!light.doNotSerialize) {
  111268. serializationObject.lights.push(light.serialize());
  111269. }
  111270. }
  111271. // Cameras
  111272. serializationObject.cameras = [];
  111273. for (index = 0; index < scene.cameras.length; index++) {
  111274. var camera = scene.cameras[index];
  111275. if (!camera.doNotSerialize) {
  111276. serializationObject.cameras.push(camera.serialize());
  111277. }
  111278. }
  111279. if (scene.activeCamera) {
  111280. serializationObject.activeCameraID = scene.activeCamera.id;
  111281. }
  111282. // Animations
  111283. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  111284. // Materials
  111285. serializationObject.materials = [];
  111286. serializationObject.multiMaterials = [];
  111287. var material;
  111288. for (index = 0; index < scene.materials.length; index++) {
  111289. material = scene.materials[index];
  111290. if (!material.doNotSerialize) {
  111291. serializationObject.materials.push(material.serialize());
  111292. }
  111293. }
  111294. // MultiMaterials
  111295. serializationObject.multiMaterials = [];
  111296. for (index = 0; index < scene.multiMaterials.length; index++) {
  111297. var multiMaterial = scene.multiMaterials[index];
  111298. serializationObject.multiMaterials.push(multiMaterial.serialize());
  111299. }
  111300. // Environment texture
  111301. if (scene.environmentTexture) {
  111302. serializationObject.environmentTexture = scene.environmentTexture.name;
  111303. }
  111304. // Skeletons
  111305. serializationObject.skeletons = [];
  111306. for (index = 0; index < scene.skeletons.length; index++) {
  111307. var skeleton = scene.skeletons[index];
  111308. if (!skeleton.doNotSerialize) {
  111309. serializationObject.skeletons.push(skeleton.serialize());
  111310. }
  111311. }
  111312. // Transform nodes
  111313. serializationObject.transformNodes = [];
  111314. for (index = 0; index < scene.transformNodes.length; index++) {
  111315. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  111316. }
  111317. // Geometries
  111318. serializationObject.geometries = {};
  111319. serializationObject.geometries.boxes = [];
  111320. serializationObject.geometries.spheres = [];
  111321. serializationObject.geometries.cylinders = [];
  111322. serializationObject.geometries.toruses = [];
  111323. serializationObject.geometries.grounds = [];
  111324. serializationObject.geometries.planes = [];
  111325. serializationObject.geometries.torusKnots = [];
  111326. serializationObject.geometries.vertexData = [];
  111327. serializedGeometries = [];
  111328. var geometries = scene.getGeometries();
  111329. for (index = 0; index < geometries.length; index++) {
  111330. var geometry = geometries[index];
  111331. if (geometry.isReady()) {
  111332. serializeGeometry(geometry, serializationObject.geometries);
  111333. }
  111334. }
  111335. // Meshes
  111336. serializationObject.meshes = [];
  111337. for (index = 0; index < scene.meshes.length; index++) {
  111338. var abstractMesh = scene.meshes[index];
  111339. if (abstractMesh instanceof BABYLON.Mesh) {
  111340. var mesh = abstractMesh;
  111341. if (!mesh.doNotSerialize) {
  111342. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  111343. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  111344. }
  111345. }
  111346. }
  111347. }
  111348. // Particles Systems
  111349. serializationObject.particleSystems = [];
  111350. for (index = 0; index < scene.particleSystems.length; index++) {
  111351. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  111352. }
  111353. // Action Manager
  111354. if (scene.actionManager) {
  111355. serializationObject.actions = scene.actionManager.serialize("scene");
  111356. }
  111357. // Components
  111358. for (var _b = 0, _c = scene._serializableComponents; _b < _c.length; _b++) {
  111359. var component = _c[_b];
  111360. component.serialize(serializationObject);
  111361. }
  111362. return serializationObject;
  111363. };
  111364. /**
  111365. * Serialize a mesh into a JSON compatible object
  111366. * @param toSerialize defines the mesh to serialize
  111367. * @param withParents defines if parents must be serialized as well
  111368. * @param withChildren defines if children must be serialized as well
  111369. * @returns a JSON compatible object
  111370. */
  111371. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  111372. if (withParents === void 0) { withParents = false; }
  111373. if (withChildren === void 0) { withChildren = false; }
  111374. var serializationObject = {};
  111375. SceneSerializer.ClearCache();
  111376. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  111377. if (withParents || withChildren) {
  111378. //deliberate for loop! not for each, appended should be processed as well.
  111379. for (var i = 0; i < toSerialize.length; ++i) {
  111380. if (withChildren) {
  111381. toSerialize[i].getDescendants().forEach(function (node) {
  111382. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  111383. toSerialize.push(node);
  111384. }
  111385. });
  111386. }
  111387. //make sure the array doesn't contain the object already
  111388. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  111389. toSerialize.push(toSerialize[i].parent);
  111390. }
  111391. }
  111392. }
  111393. toSerialize.forEach(function (mesh) {
  111394. finalizeSingleMesh(mesh, serializationObject);
  111395. });
  111396. return serializationObject;
  111397. };
  111398. return SceneSerializer;
  111399. }());
  111400. BABYLON.SceneSerializer = SceneSerializer;
  111401. })(BABYLON || (BABYLON = {}));
  111402. //# sourceMappingURL=babylon.sceneSerializer.js.map
  111403. var BABYLON;
  111404. (function (BABYLON) {
  111405. /**
  111406. * Class used to generate realtime reflection / refraction cube textures
  111407. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  111408. */
  111409. var ReflectionProbe = /** @class */ (function () {
  111410. /**
  111411. * Creates a new reflection probe
  111412. * @param name defines the name of the probe
  111413. * @param size defines the texture resolution (for each face)
  111414. * @param scene defines the hosting scene
  111415. * @param generateMipMaps defines if mip maps should be generated automatically (true by default)
  111416. * @param useFloat defines if HDR data (flaot data) should be used to store colors (false by default)
  111417. */
  111418. function ReflectionProbe(
  111419. /** defines the name of the probe */
  111420. name, size, scene, generateMipMaps, useFloat) {
  111421. if (generateMipMaps === void 0) { generateMipMaps = true; }
  111422. if (useFloat === void 0) { useFloat = false; }
  111423. var _this = this;
  111424. this.name = name;
  111425. this._viewMatrix = BABYLON.Matrix.Identity();
  111426. this._target = BABYLON.Vector3.Zero();
  111427. this._add = BABYLON.Vector3.Zero();
  111428. this._invertYAxis = false;
  111429. /** Gets or sets probe position (center of the cube map) */
  111430. this.position = BABYLON.Vector3.Zero();
  111431. this._scene = scene;
  111432. // Create the scene field if not exist.
  111433. if (!this._scene.reflectionProbes) {
  111434. this._scene.reflectionProbes = new Array();
  111435. }
  111436. this._scene.reflectionProbes.push(this);
  111437. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, useFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  111438. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  111439. switch (faceIndex) {
  111440. case 0:
  111441. _this._add.copyFromFloats(1, 0, 0);
  111442. break;
  111443. case 1:
  111444. _this._add.copyFromFloats(-1, 0, 0);
  111445. break;
  111446. case 2:
  111447. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  111448. break;
  111449. case 3:
  111450. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  111451. break;
  111452. case 4:
  111453. _this._add.copyFromFloats(0, 0, 1);
  111454. break;
  111455. case 5:
  111456. _this._add.copyFromFloats(0, 0, -1);
  111457. break;
  111458. }
  111459. if (_this._attachedMesh) {
  111460. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  111461. }
  111462. _this.position.addToRef(_this._add, _this._target);
  111463. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  111464. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  111465. scene._forcedViewPosition = _this.position;
  111466. });
  111467. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  111468. scene._forcedViewPosition = null;
  111469. scene.updateTransformMatrix(true);
  111470. });
  111471. if (scene.activeCamera) {
  111472. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  111473. }
  111474. }
  111475. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  111476. /** Gets or sets the number of samples to use for multi-sampling (0 by default). Required WebGL2 */
  111477. get: function () {
  111478. return this._renderTargetTexture.samples;
  111479. },
  111480. set: function (value) {
  111481. this._renderTargetTexture.samples = value;
  111482. },
  111483. enumerable: true,
  111484. configurable: true
  111485. });
  111486. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  111487. /** Gets or sets the refresh rate to use (on every frame by default) */
  111488. get: function () {
  111489. return this._renderTargetTexture.refreshRate;
  111490. },
  111491. set: function (value) {
  111492. this._renderTargetTexture.refreshRate = value;
  111493. },
  111494. enumerable: true,
  111495. configurable: true
  111496. });
  111497. /**
  111498. * Gets the hosting scene
  111499. * @returns a Scene
  111500. */
  111501. ReflectionProbe.prototype.getScene = function () {
  111502. return this._scene;
  111503. };
  111504. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  111505. /** Gets the internal CubeTexture used to render to */
  111506. get: function () {
  111507. return this._renderTargetTexture;
  111508. },
  111509. enumerable: true,
  111510. configurable: true
  111511. });
  111512. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  111513. /** Gets the list of meshes to render */
  111514. get: function () {
  111515. return this._renderTargetTexture.renderList;
  111516. },
  111517. enumerable: true,
  111518. configurable: true
  111519. });
  111520. /**
  111521. * Attach the probe to a specific mesh (Rendering will be done from attached mesh's position)
  111522. * @param mesh defines the mesh to attach to
  111523. */
  111524. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  111525. this._attachedMesh = mesh;
  111526. };
  111527. /**
  111528. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups
  111529. * @param renderingGroupId The rendering group id corresponding to its index
  111530. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  111531. */
  111532. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  111533. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  111534. };
  111535. /**
  111536. * Clean all associated resources
  111537. */
  111538. ReflectionProbe.prototype.dispose = function () {
  111539. var index = this._scene.reflectionProbes.indexOf(this);
  111540. if (index !== -1) {
  111541. // Remove from the scene if found
  111542. this._scene.reflectionProbes.splice(index, 1);
  111543. }
  111544. if (this._renderTargetTexture) {
  111545. this._renderTargetTexture.dispose();
  111546. this._renderTargetTexture = null;
  111547. }
  111548. };
  111549. return ReflectionProbe;
  111550. }());
  111551. BABYLON.ReflectionProbe = ReflectionProbe;
  111552. })(BABYLON || (BABYLON = {}));
  111553. //# sourceMappingURL=babylon.reflectionProbe.js.map
  111554. var BABYLON;
  111555. (function (BABYLON) {
  111556. /**
  111557. * Defines the layer scene component responsible to manage any layers
  111558. * in a given scene.
  111559. */
  111560. var LayerSceneComponent = /** @class */ (function () {
  111561. /**
  111562. * Creates a new instance of the component for the given scene
  111563. * @param scene Defines the scene to register the component in
  111564. */
  111565. function LayerSceneComponent(scene) {
  111566. /**
  111567. * The component name helpfull to identify the component in the list of scene components.
  111568. */
  111569. this.name = BABYLON.SceneComponentConstants.NAME_LAYER;
  111570. this.scene = scene;
  111571. this._engine = scene.getEngine();
  111572. scene.layers = new Array();
  111573. }
  111574. /**
  111575. * Registers the component in a given scene
  111576. */
  111577. LayerSceneComponent.prototype.register = function () {
  111578. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER, this, this._drawBackground);
  111579. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER, this, this._drawForeground);
  111580. };
  111581. /**
  111582. * Rebuilds the elements related to this component in case of
  111583. * context lost for instance.
  111584. */
  111585. LayerSceneComponent.prototype.rebuild = function () {
  111586. var layers = this.scene.layers;
  111587. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  111588. var layer = layers_1[_i];
  111589. layer._rebuild();
  111590. }
  111591. };
  111592. /**
  111593. * Disposes the component and the associated ressources.
  111594. */
  111595. LayerSceneComponent.prototype.dispose = function () {
  111596. var layers = this.scene.layers;
  111597. while (layers.length) {
  111598. layers[0].dispose();
  111599. }
  111600. };
  111601. LayerSceneComponent.prototype._draw = function (camera, isBackground) {
  111602. var layers = this.scene.layers;
  111603. if (layers.length) {
  111604. this._engine.setDepthBuffer(false);
  111605. var cameraLayerMask = camera.layerMask;
  111606. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  111607. var layer = layers_2[_i];
  111608. if (layer.isBackground === isBackground && ((layer.layerMask & cameraLayerMask) !== 0)) {
  111609. layer.render();
  111610. }
  111611. }
  111612. this._engine.setDepthBuffer(true);
  111613. }
  111614. };
  111615. LayerSceneComponent.prototype._drawBackground = function (camera) {
  111616. this._draw(camera, true);
  111617. };
  111618. LayerSceneComponent.prototype._drawForeground = function (camera) {
  111619. this._draw(camera, false);
  111620. };
  111621. return LayerSceneComponent;
  111622. }());
  111623. BABYLON.LayerSceneComponent = LayerSceneComponent;
  111624. })(BABYLON || (BABYLON = {}));
  111625. //# sourceMappingURL=babylon.layerSceneComponent.js.map
  111626. var BABYLON;
  111627. (function (BABYLON) {
  111628. /**
  111629. * This represents a full screen 2d layer.
  111630. * This can be usefull to display a picture in the background of your scene for instance.
  111631. * @see https://www.babylonjs-playground.com/#08A2BS#1
  111632. */
  111633. var Layer = /** @class */ (function () {
  111634. /**
  111635. * Instantiates a new layer.
  111636. * This represents a full screen 2d layer.
  111637. * This can be usefull to display a picture in the background of your scene for instance.
  111638. * @see https://www.babylonjs-playground.com/#08A2BS#1
  111639. * @param name Define the name of the layer in the scene
  111640. * @param imgUrl Define the url of the texture to display in the layer
  111641. * @param scene Define the scene the layer belongs to
  111642. * @param isBackground Defines whether the layer is displayed in front or behind the scene
  111643. * @param color Defines a color for the layer
  111644. */
  111645. function Layer(
  111646. /**
  111647. * Define the name of the layer.
  111648. */
  111649. name, imgUrl, scene, isBackground, color) {
  111650. this.name = name;
  111651. /**
  111652. * Define the scale of the layer in order to zoom in out of the texture.
  111653. */
  111654. this.scale = new BABYLON.Vector2(1, 1);
  111655. /**
  111656. * Define an offset for the layer in order to shift the texture.
  111657. */
  111658. this.offset = new BABYLON.Vector2(0, 0);
  111659. /**
  111660. * Define the alpha blending mode used in the layer in case the texture or color has an alpha.
  111661. */
  111662. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  111663. /**
  111664. * Define a mask to restrict the layer to only some of the scene cameras.
  111665. */
  111666. this.layerMask = 0x0FFFFFFF;
  111667. this._vertexBuffers = {};
  111668. /**
  111669. * An event triggered when the layer is disposed.
  111670. */
  111671. this.onDisposeObservable = new BABYLON.Observable();
  111672. /**
  111673. * An event triggered before rendering the scene
  111674. */
  111675. this.onBeforeRenderObservable = new BABYLON.Observable();
  111676. /**
  111677. * An event triggered after rendering the scene
  111678. */
  111679. this.onAfterRenderObservable = new BABYLON.Observable();
  111680. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  111681. this.isBackground = isBackground === undefined ? true : isBackground;
  111682. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  111683. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  111684. var layerComponent = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LAYER);
  111685. if (!layerComponent) {
  111686. layerComponent = new BABYLON.LayerSceneComponent(this._scene);
  111687. this._scene._addComponent(layerComponent);
  111688. }
  111689. this._scene.layers.push(this);
  111690. var engine = this._scene.getEngine();
  111691. // VBO
  111692. var vertices = [];
  111693. vertices.push(1, 1);
  111694. vertices.push(-1, 1);
  111695. vertices.push(-1, -1);
  111696. vertices.push(1, -1);
  111697. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  111698. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  111699. this._createIndexBuffer();
  111700. // Effects
  111701. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  111702. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  111703. }
  111704. Object.defineProperty(Layer.prototype, "onDispose", {
  111705. /**
  111706. * Back compatibility with callback before the onDisposeObservable existed.
  111707. * The set callback will be triggered when the layer has been disposed.
  111708. */
  111709. set: function (callback) {
  111710. if (this._onDisposeObserver) {
  111711. this.onDisposeObservable.remove(this._onDisposeObserver);
  111712. }
  111713. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  111714. },
  111715. enumerable: true,
  111716. configurable: true
  111717. });
  111718. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  111719. /**
  111720. * Back compatibility with callback before the onBeforeRenderObservable existed.
  111721. * The set callback will be triggered just before rendering the layer.
  111722. */
  111723. set: function (callback) {
  111724. if (this._onBeforeRenderObserver) {
  111725. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  111726. }
  111727. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  111728. },
  111729. enumerable: true,
  111730. configurable: true
  111731. });
  111732. Object.defineProperty(Layer.prototype, "onAfterRender", {
  111733. /**
  111734. * Back compatibility with callback before the onAfterRenderObservable existed.
  111735. * The set callback will be triggered just after rendering the layer.
  111736. */
  111737. set: function (callback) {
  111738. if (this._onAfterRenderObserver) {
  111739. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  111740. }
  111741. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  111742. },
  111743. enumerable: true,
  111744. configurable: true
  111745. });
  111746. Layer.prototype._createIndexBuffer = function () {
  111747. var engine = this._scene.getEngine();
  111748. // Indices
  111749. var indices = [];
  111750. indices.push(0);
  111751. indices.push(1);
  111752. indices.push(2);
  111753. indices.push(0);
  111754. indices.push(2);
  111755. indices.push(3);
  111756. this._indexBuffer = engine.createIndexBuffer(indices);
  111757. };
  111758. /** @hidden */
  111759. Layer.prototype._rebuild = function () {
  111760. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  111761. if (vb) {
  111762. vb._rebuild();
  111763. }
  111764. this._createIndexBuffer();
  111765. };
  111766. /**
  111767. * Renders the layer in the scene.
  111768. */
  111769. Layer.prototype.render = function () {
  111770. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  111771. // Check
  111772. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  111773. return;
  111774. var engine = this._scene.getEngine();
  111775. this.onBeforeRenderObservable.notifyObservers(this);
  111776. // Render
  111777. engine.enableEffect(currentEffect);
  111778. engine.setState(false);
  111779. // Texture
  111780. currentEffect.setTexture("textureSampler", this.texture);
  111781. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  111782. // Color
  111783. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  111784. // Scale / offset
  111785. currentEffect.setVector2("offset", this.offset);
  111786. currentEffect.setVector2("scale", this.scale);
  111787. // VBOs
  111788. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  111789. // Draw order
  111790. if (!this.alphaTest) {
  111791. engine.setAlphaMode(this.alphaBlendingMode);
  111792. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  111793. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  111794. }
  111795. else {
  111796. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  111797. }
  111798. this.onAfterRenderObservable.notifyObservers(this);
  111799. };
  111800. /**
  111801. * Disposes and releases the associated ressources.
  111802. */
  111803. Layer.prototype.dispose = function () {
  111804. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  111805. if (vertexBuffer) {
  111806. vertexBuffer.dispose();
  111807. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  111808. }
  111809. if (this._indexBuffer) {
  111810. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  111811. this._indexBuffer = null;
  111812. }
  111813. if (this.texture) {
  111814. this.texture.dispose();
  111815. this.texture = null;
  111816. }
  111817. // Remove from scene
  111818. var index = this._scene.layers.indexOf(this);
  111819. this._scene.layers.splice(index, 1);
  111820. // Callback
  111821. this.onDisposeObservable.notifyObservers(this);
  111822. this.onDisposeObservable.clear();
  111823. this.onAfterRenderObservable.clear();
  111824. this.onBeforeRenderObservable.clear();
  111825. };
  111826. return Layer;
  111827. }());
  111828. BABYLON.Layer = Layer;
  111829. })(BABYLON || (BABYLON = {}));
  111830. //# sourceMappingURL=babylon.layer.js.map
  111831. var BABYLON;
  111832. (function (BABYLON) {
  111833. /**
  111834. * Class used to host texture specific utilities
  111835. */
  111836. var TextureTools = /** @class */ (function () {
  111837. function TextureTools() {
  111838. }
  111839. /**
  111840. * Uses the GPU to create a copy texture rescaled at a given size
  111841. * @param texture Texture to copy from
  111842. * @param width defines the desired width
  111843. * @param height defines the desired height
  111844. * @param useBilinearMode defines if bilinear mode has to be used
  111845. * @return the generated texture
  111846. */
  111847. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  111848. if (useBilinearMode === void 0) { useBilinearMode = true; }
  111849. var scene = texture.getScene();
  111850. var engine = scene.getEngine();
  111851. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  111852. rtt.wrapU = texture.wrapU;
  111853. rtt.wrapV = texture.wrapV;
  111854. rtt.uOffset = texture.uOffset;
  111855. rtt.vOffset = texture.vOffset;
  111856. rtt.uScale = texture.uScale;
  111857. rtt.vScale = texture.vScale;
  111858. rtt.uAng = texture.uAng;
  111859. rtt.vAng = texture.vAng;
  111860. rtt.wAng = texture.wAng;
  111861. rtt.coordinatesIndex = texture.coordinatesIndex;
  111862. rtt.level = texture.level;
  111863. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  111864. rtt._texture.isReady = false;
  111865. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  111866. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  111867. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  111868. passPostProcess.getEffect().executeWhenCompiled(function () {
  111869. passPostProcess.onApply = function (effect) {
  111870. effect.setTexture("textureSampler", texture);
  111871. };
  111872. var internalTexture = rtt.getInternalTexture();
  111873. if (internalTexture) {
  111874. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  111875. engine.unBindFramebuffer(internalTexture);
  111876. rtt.disposeFramebufferObjects();
  111877. passPostProcess.dispose();
  111878. internalTexture.isReady = true;
  111879. }
  111880. });
  111881. return rtt;
  111882. };
  111883. /**
  111884. * Gets an environment BRDF texture for a given scene
  111885. * @param scene defines the hosting scene
  111886. * @returns the environment BRDF texture
  111887. */
  111888. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  111889. if (!scene._environmentBRDFTexture) {
  111890. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  111891. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  111892. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  111893. scene._environmentBRDFTexture = texture;
  111894. }
  111895. return scene._environmentBRDFTexture;
  111896. };
  111897. 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=";
  111898. return TextureTools;
  111899. }());
  111900. BABYLON.TextureTools = TextureTools;
  111901. })(BABYLON || (BABYLON = {}));
  111902. //# sourceMappingURL=babylon.textureTools.js.map
  111903. var BABYLON;
  111904. (function (BABYLON) {
  111905. /**
  111906. * The framing behavior (BABYLON.FramingBehavior) is designed to automatically position an ArcRotateCamera when its target is set to a mesh. It is also useful if you want to prevent the camera to go under a virtual horizontal plane.
  111907. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  111908. */
  111909. var FramingBehavior = /** @class */ (function () {
  111910. function FramingBehavior() {
  111911. this._mode = FramingBehavior.FitFrustumSidesMode;
  111912. this._radiusScale = 1.0;
  111913. this._positionScale = 0.5;
  111914. this._defaultElevation = 0.3;
  111915. this._elevationReturnTime = 1500;
  111916. this._elevationReturnWaitTime = 1000;
  111917. this._zoomStopsAnimation = false;
  111918. this._framingTime = 1500;
  111919. /**
  111920. * Define if the behavior should automatically change the configured
  111921. * camera limits and sensibilities.
  111922. */
  111923. this.autoCorrectCameraLimitsAndSensibility = true;
  111924. this._isPointerDown = false;
  111925. this._lastInteractionTime = -Infinity;
  111926. // Framing control
  111927. this._animatables = new Array();
  111928. this._betaIsAnimating = false;
  111929. }
  111930. Object.defineProperty(FramingBehavior.prototype, "name", {
  111931. /**
  111932. * Gets the name of the behavior.
  111933. */
  111934. get: function () {
  111935. return "Framing";
  111936. },
  111937. enumerable: true,
  111938. configurable: true
  111939. });
  111940. Object.defineProperty(FramingBehavior.prototype, "mode", {
  111941. /**
  111942. * Gets current mode used by the behavior.
  111943. */
  111944. get: function () {
  111945. return this._mode;
  111946. },
  111947. /**
  111948. * Sets the current mode used by the behavior
  111949. */
  111950. set: function (mode) {
  111951. this._mode = mode;
  111952. },
  111953. enumerable: true,
  111954. configurable: true
  111955. });
  111956. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  111957. /**
  111958. * Gets the scale applied to the radius
  111959. */
  111960. get: function () {
  111961. return this._radiusScale;
  111962. },
  111963. /**
  111964. * Sets the scale applied to the radius (1 by default)
  111965. */
  111966. set: function (radius) {
  111967. this._radiusScale = radius;
  111968. },
  111969. enumerable: true,
  111970. configurable: true
  111971. });
  111972. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  111973. /**
  111974. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  111975. */
  111976. get: function () {
  111977. return this._positionScale;
  111978. },
  111979. /**
  111980. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  111981. */
  111982. set: function (scale) {
  111983. this._positionScale = scale;
  111984. },
  111985. enumerable: true,
  111986. configurable: true
  111987. });
  111988. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  111989. /**
  111990. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  111991. * behaviour is triggered, in radians.
  111992. */
  111993. get: function () {
  111994. return this._defaultElevation;
  111995. },
  111996. /**
  111997. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  111998. * behaviour is triggered, in radians.
  111999. */
  112000. set: function (elevation) {
  112001. this._defaultElevation = elevation;
  112002. },
  112003. enumerable: true,
  112004. configurable: true
  112005. });
  112006. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  112007. /**
  112008. * Gets the time (in milliseconds) taken to return to the default beta position.
  112009. * Negative value indicates camera should not return to default.
  112010. */
  112011. get: function () {
  112012. return this._elevationReturnTime;
  112013. },
  112014. /**
  112015. * Sets the time (in milliseconds) taken to return to the default beta position.
  112016. * Negative value indicates camera should not return to default.
  112017. */
  112018. set: function (speed) {
  112019. this._elevationReturnTime = speed;
  112020. },
  112021. enumerable: true,
  112022. configurable: true
  112023. });
  112024. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  112025. /**
  112026. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  112027. */
  112028. get: function () {
  112029. return this._elevationReturnWaitTime;
  112030. },
  112031. /**
  112032. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  112033. */
  112034. set: function (time) {
  112035. this._elevationReturnWaitTime = time;
  112036. },
  112037. enumerable: true,
  112038. configurable: true
  112039. });
  112040. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  112041. /**
  112042. * Gets the flag that indicates if user zooming should stop animation.
  112043. */
  112044. get: function () {
  112045. return this._zoomStopsAnimation;
  112046. },
  112047. /**
  112048. * Sets the flag that indicates if user zooming should stop animation.
  112049. */
  112050. set: function (flag) {
  112051. this._zoomStopsAnimation = flag;
  112052. },
  112053. enumerable: true,
  112054. configurable: true
  112055. });
  112056. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  112057. /**
  112058. * Gets the transition time when framing the mesh, in milliseconds
  112059. */
  112060. get: function () {
  112061. return this._framingTime;
  112062. },
  112063. /**
  112064. * Sets the transition time when framing the mesh, in milliseconds
  112065. */
  112066. set: function (time) {
  112067. this._framingTime = time;
  112068. },
  112069. enumerable: true,
  112070. configurable: true
  112071. });
  112072. /**
  112073. * Initializes the behavior.
  112074. */
  112075. FramingBehavior.prototype.init = function () {
  112076. // Do notihng
  112077. };
  112078. /**
  112079. * Attaches the behavior to its arc rotate camera.
  112080. * @param camera Defines the camera to attach the behavior to
  112081. */
  112082. FramingBehavior.prototype.attach = function (camera) {
  112083. var _this = this;
  112084. this._attachedCamera = camera;
  112085. var scene = this._attachedCamera.getScene();
  112086. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  112087. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  112088. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  112089. _this._isPointerDown = true;
  112090. return;
  112091. }
  112092. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  112093. _this._isPointerDown = false;
  112094. }
  112095. });
  112096. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  112097. if (mesh) {
  112098. _this.zoomOnMesh(mesh);
  112099. }
  112100. });
  112101. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  112102. // Stop the animation if there is user interaction and the animation should stop for this interaction
  112103. _this._applyUserInteraction();
  112104. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  112105. // back to the default position after a given timeout
  112106. _this._maintainCameraAboveGround();
  112107. });
  112108. };
  112109. /**
  112110. * Detaches the behavior from its current arc rotate camera.
  112111. */
  112112. FramingBehavior.prototype.detach = function () {
  112113. if (!this._attachedCamera) {
  112114. return;
  112115. }
  112116. var scene = this._attachedCamera.getScene();
  112117. if (this._onPrePointerObservableObserver) {
  112118. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  112119. }
  112120. if (this._onAfterCheckInputsObserver) {
  112121. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  112122. }
  112123. if (this._onMeshTargetChangedObserver) {
  112124. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  112125. }
  112126. this._attachedCamera = null;
  112127. };
  112128. /**
  112129. * Targets the given mesh and updates zoom level accordingly.
  112130. * @param mesh The mesh to target.
  112131. * @param radius Optional. If a cached radius position already exists, overrides default.
  112132. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  112133. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  112134. * @param onAnimationEnd Callback triggered at the end of the framing animation
  112135. */
  112136. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  112137. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  112138. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  112139. mesh.computeWorldMatrix(true);
  112140. var boundingBox = mesh.getBoundingInfo().boundingBox;
  112141. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  112142. };
  112143. /**
  112144. * Targets the given mesh with its children and updates zoom level accordingly.
  112145. * @param mesh The mesh to target.
  112146. * @param radius Optional. If a cached radius position already exists, overrides default.
  112147. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  112148. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  112149. * @param onAnimationEnd Callback triggered at the end of the framing animation
  112150. */
  112151. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  112152. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  112153. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  112154. mesh.computeWorldMatrix(true);
  112155. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  112156. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  112157. };
  112158. /**
  112159. * Targets the given meshes with their children and updates zoom level accordingly.
  112160. * @param meshes The mesh to target.
  112161. * @param radius Optional. If a cached radius position already exists, overrides default.
  112162. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  112163. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  112164. * @param onAnimationEnd Callback triggered at the end of the framing animation
  112165. */
  112166. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  112167. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  112168. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  112169. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  112170. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  112171. for (var i = 0; i < meshes.length; i++) {
  112172. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  112173. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  112174. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  112175. }
  112176. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  112177. };
  112178. /**
  112179. * Targets the bounding box info defined by its extends and updates zoom level accordingly.
  112180. * @param minimumWorld Determines the smaller position of the bounding box extend
  112181. * @param maximumWorld Determines the bigger position of the bounding box extend
  112182. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  112183. * @param onAnimationEnd Callback triggered at the end of the framing animation
  112184. */
  112185. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  112186. var _this = this;
  112187. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  112188. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  112189. var zoomTarget;
  112190. if (!this._attachedCamera) {
  112191. return;
  112192. }
  112193. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  112194. var bottom = minimumWorld.y;
  112195. var top = maximumWorld.y;
  112196. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  112197. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  112198. if (focusOnOriginXZ) {
  112199. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  112200. }
  112201. else {
  112202. var centerWorld = minimumWorld.add(radiusWorld);
  112203. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  112204. }
  112205. if (!this._vectorTransition) {
  112206. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  112207. }
  112208. this._betaIsAnimating = true;
  112209. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  112210. if (animatable) {
  112211. this._animatables.push(animatable);
  112212. }
  112213. // sets the radius and lower radius bounds
  112214. // Small delta ensures camera is not always at lower zoom limit.
  112215. var radius = 0;
  112216. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  112217. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  112218. if (this.autoCorrectCameraLimitsAndSensibility) {
  112219. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  112220. }
  112221. radius = position;
  112222. }
  112223. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  112224. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  112225. if (this.autoCorrectCameraLimitsAndSensibility && this._attachedCamera.lowerRadiusLimit === null) {
  112226. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  112227. }
  112228. }
  112229. // Set sensibilities
  112230. if (this.autoCorrectCameraLimitsAndSensibility) {
  112231. var extend = maximumWorld.subtract(minimumWorld).length();
  112232. this._attachedCamera.panningSensibility = 5000 / extend;
  112233. this._attachedCamera.wheelPrecision = 100 / radius;
  112234. }
  112235. // transition to new radius
  112236. if (!this._radiusTransition) {
  112237. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  112238. }
  112239. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  112240. _this.stopAllAnimations();
  112241. if (onAnimationEnd) {
  112242. onAnimationEnd();
  112243. }
  112244. if (_this._attachedCamera && _this._attachedCamera.useInputToRestoreState) {
  112245. _this._attachedCamera.storeState();
  112246. }
  112247. });
  112248. if (animatable) {
  112249. this._animatables.push(animatable);
  112250. }
  112251. };
  112252. /**
  112253. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  112254. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  112255. * frustum width.
  112256. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  112257. * to fully enclose the mesh in the viewing frustum.
  112258. */
  112259. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  112260. var size = maximumWorld.subtract(minimumWorld);
  112261. var boxVectorGlobalDiagonal = size.length();
  112262. var frustumSlope = this._getFrustumSlope();
  112263. // Formula for setting distance
  112264. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  112265. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  112266. // Horizon distance
  112267. var radius = radiusWithoutFraming * this._radiusScale;
  112268. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  112269. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  112270. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  112271. var camera = this._attachedCamera;
  112272. if (!camera) {
  112273. return 0;
  112274. }
  112275. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  112276. // Don't exceed the requested limit
  112277. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  112278. }
  112279. // Don't exceed the upper radius limit
  112280. if (camera.upperRadiusLimit) {
  112281. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  112282. }
  112283. return distance;
  112284. };
  112285. /**
  112286. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  112287. * is automatically returned to its default position (expected to be above ground plane).
  112288. */
  112289. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  112290. var _this = this;
  112291. if (this._elevationReturnTime < 0) {
  112292. return;
  112293. }
  112294. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  112295. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  112296. var limitBeta = Math.PI * 0.5;
  112297. // Bring the camera back up if below the ground plane
  112298. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  112299. this._betaIsAnimating = true;
  112300. //Transition to new position
  112301. this.stopAllAnimations();
  112302. if (!this._betaTransition) {
  112303. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  112304. }
  112305. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  112306. _this._clearAnimationLocks();
  112307. _this.stopAllAnimations();
  112308. });
  112309. if (animatabe) {
  112310. this._animatables.push(animatabe);
  112311. }
  112312. }
  112313. };
  112314. /**
  112315. * Returns the frustum slope based on the canvas ratio and camera FOV
  112316. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  112317. */
  112318. FramingBehavior.prototype._getFrustumSlope = function () {
  112319. // Calculate the viewport ratio
  112320. // Aspect Ratio is Height/Width.
  112321. var camera = this._attachedCamera;
  112322. if (!camera) {
  112323. return BABYLON.Vector2.Zero();
  112324. }
  112325. var engine = camera.getScene().getEngine();
  112326. var aspectRatio = engine.getAspectRatio(camera);
  112327. // Camera FOV is the vertical field of view (top-bottom) in radians.
  112328. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  112329. var frustumSlopeY = Math.tan(camera.fov / 2);
  112330. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  112331. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  112332. // along the forward vector.
  112333. var frustumSlopeX = frustumSlopeY * aspectRatio;
  112334. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  112335. };
  112336. /**
  112337. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  112338. */
  112339. FramingBehavior.prototype._clearAnimationLocks = function () {
  112340. this._betaIsAnimating = false;
  112341. };
  112342. /**
  112343. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  112344. */
  112345. FramingBehavior.prototype._applyUserInteraction = function () {
  112346. if (this.isUserIsMoving) {
  112347. this._lastInteractionTime = BABYLON.Tools.Now;
  112348. this.stopAllAnimations();
  112349. this._clearAnimationLocks();
  112350. }
  112351. };
  112352. /**
  112353. * Stops and removes all animations that have been applied to the camera
  112354. */
  112355. FramingBehavior.prototype.stopAllAnimations = function () {
  112356. if (this._attachedCamera) {
  112357. this._attachedCamera.animations = [];
  112358. }
  112359. while (this._animatables.length) {
  112360. if (this._animatables[0]) {
  112361. this._animatables[0].onAnimationEnd = null;
  112362. this._animatables[0].stop();
  112363. }
  112364. this._animatables.shift();
  112365. }
  112366. };
  112367. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  112368. /**
  112369. * Gets a value indicating if the user is moving the camera
  112370. */
  112371. get: function () {
  112372. if (!this._attachedCamera) {
  112373. return false;
  112374. }
  112375. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  112376. this._attachedCamera.inertialBetaOffset !== 0 ||
  112377. this._attachedCamera.inertialRadiusOffset !== 0 ||
  112378. this._attachedCamera.inertialPanningX !== 0 ||
  112379. this._attachedCamera.inertialPanningY !== 0 ||
  112380. this._isPointerDown;
  112381. },
  112382. enumerable: true,
  112383. configurable: true
  112384. });
  112385. /**
  112386. * The easing function used by animations
  112387. */
  112388. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  112389. /**
  112390. * The easing mode used by animations
  112391. */
  112392. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  112393. // Statics
  112394. /**
  112395. * The camera can move all the way towards the mesh.
  112396. */
  112397. FramingBehavior.IgnoreBoundsSizeMode = 0;
  112398. /**
  112399. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  112400. */
  112401. FramingBehavior.FitFrustumSidesMode = 1;
  112402. return FramingBehavior;
  112403. }());
  112404. BABYLON.FramingBehavior = FramingBehavior;
  112405. })(BABYLON || (BABYLON = {}));
  112406. //# sourceMappingURL=babylon.framingBehavior.js.map
  112407. var BABYLON;
  112408. (function (BABYLON) {
  112409. /**
  112410. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  112411. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  112412. */
  112413. var BouncingBehavior = /** @class */ (function () {
  112414. function BouncingBehavior() {
  112415. /**
  112416. * The duration of the animation, in milliseconds
  112417. */
  112418. this.transitionDuration = 450;
  112419. /**
  112420. * Length of the distance animated by the transition when lower radius is reached
  112421. */
  112422. this.lowerRadiusTransitionRange = 2;
  112423. /**
  112424. * Length of the distance animated by the transition when upper radius is reached
  112425. */
  112426. this.upperRadiusTransitionRange = -2;
  112427. this._autoTransitionRange = false;
  112428. // Animations
  112429. this._radiusIsAnimating = false;
  112430. this._radiusBounceTransition = null;
  112431. this._animatables = new Array();
  112432. }
  112433. Object.defineProperty(BouncingBehavior.prototype, "name", {
  112434. /**
  112435. * Gets the name of the behavior.
  112436. */
  112437. get: function () {
  112438. return "Bouncing";
  112439. },
  112440. enumerable: true,
  112441. configurable: true
  112442. });
  112443. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  112444. /**
  112445. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  112446. */
  112447. get: function () {
  112448. return this._autoTransitionRange;
  112449. },
  112450. /**
  112451. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  112452. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  112453. */
  112454. set: function (value) {
  112455. var _this = this;
  112456. if (this._autoTransitionRange === value) {
  112457. return;
  112458. }
  112459. this._autoTransitionRange = value;
  112460. var camera = this._attachedCamera;
  112461. if (!camera) {
  112462. return;
  112463. }
  112464. if (value) {
  112465. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  112466. if (!mesh) {
  112467. return;
  112468. }
  112469. mesh.computeWorldMatrix(true);
  112470. var diagonal = mesh.getBoundingInfo().diagonalLength;
  112471. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  112472. _this.upperRadiusTransitionRange = diagonal * 0.05;
  112473. });
  112474. }
  112475. else if (this._onMeshTargetChangedObserver) {
  112476. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  112477. }
  112478. },
  112479. enumerable: true,
  112480. configurable: true
  112481. });
  112482. /**
  112483. * Initializes the behavior.
  112484. */
  112485. BouncingBehavior.prototype.init = function () {
  112486. // Do notihng
  112487. };
  112488. /**
  112489. * Attaches the behavior to its arc rotate camera.
  112490. * @param camera Defines the camera to attach the behavior to
  112491. */
  112492. BouncingBehavior.prototype.attach = function (camera) {
  112493. var _this = this;
  112494. this._attachedCamera = camera;
  112495. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  112496. if (!_this._attachedCamera) {
  112497. return;
  112498. }
  112499. // Add the bounce animation to the lower radius limit
  112500. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  112501. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  112502. }
  112503. // Add the bounce animation to the upper radius limit
  112504. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  112505. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  112506. }
  112507. });
  112508. };
  112509. /**
  112510. * Detaches the behavior from its current arc rotate camera.
  112511. */
  112512. BouncingBehavior.prototype.detach = function () {
  112513. if (!this._attachedCamera) {
  112514. return;
  112515. }
  112516. if (this._onAfterCheckInputsObserver) {
  112517. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  112518. }
  112519. if (this._onMeshTargetChangedObserver) {
  112520. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  112521. }
  112522. this._attachedCamera = null;
  112523. };
  112524. /**
  112525. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  112526. * @param radiusLimit The limit to check against.
  112527. * @return Bool to indicate if at limit.
  112528. */
  112529. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  112530. if (!this._attachedCamera) {
  112531. return false;
  112532. }
  112533. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  112534. return true;
  112535. }
  112536. return false;
  112537. };
  112538. /**
  112539. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  112540. * @param radiusDelta The delta by which to animate to. Can be negative.
  112541. */
  112542. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  112543. var _this = this;
  112544. if (!this._attachedCamera) {
  112545. return;
  112546. }
  112547. if (!this._radiusBounceTransition) {
  112548. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  112549. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  112550. }
  112551. // Prevent zoom until bounce has completed
  112552. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  112553. this._attachedCamera.wheelPrecision = Infinity;
  112554. this._attachedCamera.inertialRadiusOffset = 0;
  112555. // Animate to the radius limit
  112556. this.stopAllAnimations();
  112557. this._radiusIsAnimating = true;
  112558. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  112559. if (animatable) {
  112560. this._animatables.push(animatable);
  112561. }
  112562. };
  112563. /**
  112564. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  112565. */
  112566. BouncingBehavior.prototype._clearAnimationLocks = function () {
  112567. this._radiusIsAnimating = false;
  112568. if (this._attachedCamera) {
  112569. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  112570. }
  112571. };
  112572. /**
  112573. * Stops and removes all animations that have been applied to the camera
  112574. */
  112575. BouncingBehavior.prototype.stopAllAnimations = function () {
  112576. if (this._attachedCamera) {
  112577. this._attachedCamera.animations = [];
  112578. }
  112579. while (this._animatables.length) {
  112580. this._animatables[0].onAnimationEnd = null;
  112581. this._animatables[0].stop();
  112582. this._animatables.shift();
  112583. }
  112584. };
  112585. /**
  112586. * The easing function used by animations
  112587. */
  112588. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  112589. /**
  112590. * The easing mode used by animations
  112591. */
  112592. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  112593. return BouncingBehavior;
  112594. }());
  112595. BABYLON.BouncingBehavior = BouncingBehavior;
  112596. })(BABYLON || (BABYLON = {}));
  112597. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  112598. var BABYLON;
  112599. (function (BABYLON) {
  112600. /**
  112601. * The autoRotation behavior (BABYLON.AutoRotationBehavior) is designed to create a smooth rotation of an ArcRotateCamera when there is no user interaction.
  112602. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  112603. */
  112604. var AutoRotationBehavior = /** @class */ (function () {
  112605. function AutoRotationBehavior() {
  112606. this._zoomStopsAnimation = false;
  112607. this._idleRotationSpeed = 0.05;
  112608. this._idleRotationWaitTime = 2000;
  112609. this._idleRotationSpinupTime = 2000;
  112610. this._isPointerDown = false;
  112611. this._lastFrameTime = null;
  112612. this._lastInteractionTime = -Infinity;
  112613. this._cameraRotationSpeed = 0;
  112614. this._lastFrameRadius = 0;
  112615. }
  112616. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  112617. /**
  112618. * Gets the name of the behavior.
  112619. */
  112620. get: function () {
  112621. return "AutoRotation";
  112622. },
  112623. enumerable: true,
  112624. configurable: true
  112625. });
  112626. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  112627. /**
  112628. * Gets the flag that indicates if user zooming should stop animation.
  112629. */
  112630. get: function () {
  112631. return this._zoomStopsAnimation;
  112632. },
  112633. /**
  112634. * Sets the flag that indicates if user zooming should stop animation.
  112635. */
  112636. set: function (flag) {
  112637. this._zoomStopsAnimation = flag;
  112638. },
  112639. enumerable: true,
  112640. configurable: true
  112641. });
  112642. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  112643. /**
  112644. * Gets the default speed at which the camera rotates around the model.
  112645. */
  112646. get: function () {
  112647. return this._idleRotationSpeed;
  112648. },
  112649. /**
  112650. * Sets the default speed at which the camera rotates around the model.
  112651. */
  112652. set: function (speed) {
  112653. this._idleRotationSpeed = speed;
  112654. },
  112655. enumerable: true,
  112656. configurable: true
  112657. });
  112658. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  112659. /**
  112660. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  112661. */
  112662. get: function () {
  112663. return this._idleRotationWaitTime;
  112664. },
  112665. /**
  112666. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  112667. */
  112668. set: function (time) {
  112669. this._idleRotationWaitTime = time;
  112670. },
  112671. enumerable: true,
  112672. configurable: true
  112673. });
  112674. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  112675. /**
  112676. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  112677. */
  112678. get: function () {
  112679. return this._idleRotationSpinupTime;
  112680. },
  112681. /**
  112682. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  112683. */
  112684. set: function (time) {
  112685. this._idleRotationSpinupTime = time;
  112686. },
  112687. enumerable: true,
  112688. configurable: true
  112689. });
  112690. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  112691. /**
  112692. * Gets a value indicating if the camera is currently rotating because of this behavior
  112693. */
  112694. get: function () {
  112695. return Math.abs(this._cameraRotationSpeed) > 0;
  112696. },
  112697. enumerable: true,
  112698. configurable: true
  112699. });
  112700. /**
  112701. * Initializes the behavior.
  112702. */
  112703. AutoRotationBehavior.prototype.init = function () {
  112704. // Do notihng
  112705. };
  112706. /**
  112707. * Attaches the behavior to its arc rotate camera.
  112708. * @param camera Defines the camera to attach the behavior to
  112709. */
  112710. AutoRotationBehavior.prototype.attach = function (camera) {
  112711. var _this = this;
  112712. this._attachedCamera = camera;
  112713. var scene = this._attachedCamera.getScene();
  112714. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  112715. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  112716. _this._isPointerDown = true;
  112717. return;
  112718. }
  112719. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  112720. _this._isPointerDown = false;
  112721. }
  112722. });
  112723. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  112724. var now = BABYLON.Tools.Now;
  112725. var dt = 0;
  112726. if (_this._lastFrameTime != null) {
  112727. dt = now - _this._lastFrameTime;
  112728. }
  112729. _this._lastFrameTime = now;
  112730. // Stop the animation if there is user interaction and the animation should stop for this interaction
  112731. _this._applyUserInteraction();
  112732. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  112733. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  112734. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  112735. // Step camera rotation by rotation speed
  112736. if (_this._attachedCamera) {
  112737. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  112738. }
  112739. });
  112740. };
  112741. /**
  112742. * Detaches the behavior from its current arc rotate camera.
  112743. */
  112744. AutoRotationBehavior.prototype.detach = function () {
  112745. if (!this._attachedCamera) {
  112746. return;
  112747. }
  112748. var scene = this._attachedCamera.getScene();
  112749. if (this._onPrePointerObservableObserver) {
  112750. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  112751. }
  112752. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  112753. this._attachedCamera = null;
  112754. };
  112755. /**
  112756. * Returns true if user is scrolling.
  112757. * @return true if user is scrolling.
  112758. */
  112759. AutoRotationBehavior.prototype._userIsZooming = function () {
  112760. if (!this._attachedCamera) {
  112761. return false;
  112762. }
  112763. return this._attachedCamera.inertialRadiusOffset !== 0;
  112764. };
  112765. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  112766. if (!this._attachedCamera) {
  112767. return false;
  112768. }
  112769. var zoomHasHitLimit = false;
  112770. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  112771. zoomHasHitLimit = true;
  112772. }
  112773. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  112774. this._lastFrameRadius = this._attachedCamera.radius;
  112775. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  112776. };
  112777. /**
  112778. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  112779. */
  112780. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  112781. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  112782. this._lastInteractionTime = BABYLON.Tools.Now;
  112783. }
  112784. };
  112785. // Tools
  112786. AutoRotationBehavior.prototype._userIsMoving = function () {
  112787. if (!this._attachedCamera) {
  112788. return false;
  112789. }
  112790. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  112791. this._attachedCamera.inertialBetaOffset !== 0 ||
  112792. this._attachedCamera.inertialRadiusOffset !== 0 ||
  112793. this._attachedCamera.inertialPanningX !== 0 ||
  112794. this._attachedCamera.inertialPanningY !== 0 ||
  112795. this._isPointerDown;
  112796. };
  112797. return AutoRotationBehavior;
  112798. }());
  112799. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  112800. })(BABYLON || (BABYLON = {}));
  112801. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  112802. var BABYLON;
  112803. (function (BABYLON) {
  112804. /**
  112805. * Options to create the null engine
  112806. */
  112807. var NullEngineOptions = /** @class */ (function () {
  112808. function NullEngineOptions() {
  112809. /**
  112810. * Render width (Default: 512)
  112811. */
  112812. this.renderWidth = 512;
  112813. /**
  112814. * Render height (Default: 256)
  112815. */
  112816. this.renderHeight = 256;
  112817. /**
  112818. * Texture size (Default: 512)
  112819. */
  112820. this.textureSize = 512;
  112821. /**
  112822. * If delta time between frames should be constant
  112823. * @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  112824. */
  112825. this.deterministicLockstep = false;
  112826. /**
  112827. * Maximum about of steps between frames (Default: 4)
  112828. * @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  112829. */
  112830. this.lockstepMaxSteps = 4;
  112831. }
  112832. return NullEngineOptions;
  112833. }());
  112834. BABYLON.NullEngineOptions = NullEngineOptions;
  112835. /**
  112836. * The null engine class provides support for headless version of babylon.js.
  112837. * This can be used in server side scenario or for testing purposes
  112838. */
  112839. var NullEngine = /** @class */ (function (_super) {
  112840. __extends(NullEngine, _super);
  112841. function NullEngine(options) {
  112842. if (options === void 0) { options = new NullEngineOptions(); }
  112843. var _this = _super.call(this, null) || this;
  112844. if (options.deterministicLockstep === undefined) {
  112845. options.deterministicLockstep = false;
  112846. }
  112847. if (options.lockstepMaxSteps === undefined) {
  112848. options.lockstepMaxSteps = 4;
  112849. }
  112850. _this._options = options;
  112851. // Init caps
  112852. // We consider we are on a webgl1 capable device
  112853. _this._caps = new BABYLON.EngineCapabilities();
  112854. _this._caps.maxTexturesImageUnits = 16;
  112855. _this._caps.maxVertexTextureImageUnits = 16;
  112856. _this._caps.maxTextureSize = 512;
  112857. _this._caps.maxCubemapTextureSize = 512;
  112858. _this._caps.maxRenderTextureSize = 512;
  112859. _this._caps.maxVertexAttribs = 16;
  112860. _this._caps.maxVaryingVectors = 16;
  112861. _this._caps.maxFragmentUniformVectors = 16;
  112862. _this._caps.maxVertexUniformVectors = 16;
  112863. // Extensions
  112864. _this._caps.standardDerivatives = false;
  112865. _this._caps.astc = null;
  112866. _this._caps.s3tc = null;
  112867. _this._caps.pvrtc = null;
  112868. _this._caps.etc1 = null;
  112869. _this._caps.etc2 = null;
  112870. _this._caps.textureAnisotropicFilterExtension = null;
  112871. _this._caps.maxAnisotropy = 0;
  112872. _this._caps.uintIndices = false;
  112873. _this._caps.fragmentDepthSupported = false;
  112874. _this._caps.highPrecisionShaderSupported = true;
  112875. _this._caps.colorBufferFloat = false;
  112876. _this._caps.textureFloat = false;
  112877. _this._caps.textureFloatLinearFiltering = false;
  112878. _this._caps.textureFloatRender = false;
  112879. _this._caps.textureHalfFloat = false;
  112880. _this._caps.textureHalfFloatLinearFiltering = false;
  112881. _this._caps.textureHalfFloatRender = false;
  112882. _this._caps.textureLOD = false;
  112883. _this._caps.drawBuffersExtension = false;
  112884. _this._caps.depthTextureExtension = false;
  112885. _this._caps.vertexArrayObject = false;
  112886. _this._caps.instancedArrays = false;
  112887. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  112888. // Wrappers
  112889. if (typeof URL === "undefined") {
  112890. URL = {
  112891. createObjectURL: function () { },
  112892. revokeObjectURL: function () { }
  112893. };
  112894. }
  112895. if (typeof Blob === "undefined") {
  112896. Blob = function () { };
  112897. }
  112898. return _this;
  112899. }
  112900. /**
  112901. * @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  112902. */
  112903. NullEngine.prototype.isDeterministicLockStep = function () {
  112904. return this._options.deterministicLockstep;
  112905. };
  112906. /** @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep */
  112907. NullEngine.prototype.getLockstepMaxSteps = function () {
  112908. return this._options.lockstepMaxSteps;
  112909. };
  112910. /**
  112911. * Sets hardware scaling, used to save performance if needed
  112912. * @see https://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  112913. */
  112914. NullEngine.prototype.getHardwareScalingLevel = function () {
  112915. return 1.0;
  112916. };
  112917. NullEngine.prototype.createVertexBuffer = function (vertices) {
  112918. return {
  112919. capacity: 0,
  112920. references: 1,
  112921. is32Bits: false
  112922. };
  112923. };
  112924. NullEngine.prototype.createIndexBuffer = function (indices) {
  112925. return {
  112926. capacity: 0,
  112927. references: 1,
  112928. is32Bits: false
  112929. };
  112930. };
  112931. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  112932. if (stencil === void 0) { stencil = false; }
  112933. };
  112934. NullEngine.prototype.getRenderWidth = function (useScreen) {
  112935. if (useScreen === void 0) { useScreen = false; }
  112936. if (!useScreen && this._currentRenderTarget) {
  112937. return this._currentRenderTarget.width;
  112938. }
  112939. return this._options.renderWidth;
  112940. };
  112941. NullEngine.prototype.getRenderHeight = function (useScreen) {
  112942. if (useScreen === void 0) { useScreen = false; }
  112943. if (!useScreen && this._currentRenderTarget) {
  112944. return this._currentRenderTarget.height;
  112945. }
  112946. return this._options.renderHeight;
  112947. };
  112948. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  112949. this._cachedViewport = viewport;
  112950. };
  112951. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  112952. return {
  112953. transformFeedback: null,
  112954. __SPECTOR_rebuildProgram: null
  112955. };
  112956. };
  112957. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  112958. return [];
  112959. };
  112960. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  112961. return [];
  112962. };
  112963. NullEngine.prototype.bindSamplers = function (effect) {
  112964. this._currentEffect = null;
  112965. };
  112966. NullEngine.prototype.enableEffect = function (effect) {
  112967. this._currentEffect = effect;
  112968. if (effect.onBind) {
  112969. effect.onBind(effect);
  112970. }
  112971. if (effect._onBindObservable) {
  112972. effect._onBindObservable.notifyObservers(effect);
  112973. }
  112974. };
  112975. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  112976. if (zOffset === void 0) { zOffset = 0; }
  112977. if (reverseSide === void 0) { reverseSide = false; }
  112978. };
  112979. NullEngine.prototype.setIntArray = function (uniform, array) {
  112980. };
  112981. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  112982. };
  112983. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  112984. };
  112985. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  112986. };
  112987. NullEngine.prototype.setFloatArray = function (uniform, array) {
  112988. };
  112989. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  112990. };
  112991. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  112992. };
  112993. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  112994. };
  112995. NullEngine.prototype.setArray = function (uniform, array) {
  112996. };
  112997. NullEngine.prototype.setArray2 = function (uniform, array) {
  112998. };
  112999. NullEngine.prototype.setArray3 = function (uniform, array) {
  113000. };
  113001. NullEngine.prototype.setArray4 = function (uniform, array) {
  113002. };
  113003. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  113004. };
  113005. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  113006. };
  113007. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  113008. };
  113009. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  113010. };
  113011. NullEngine.prototype.setFloat = function (uniform, value) {
  113012. };
  113013. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  113014. };
  113015. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  113016. };
  113017. NullEngine.prototype.setBool = function (uniform, bool) {
  113018. };
  113019. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  113020. };
  113021. NullEngine.prototype.setColor3 = function (uniform, color3) {
  113022. };
  113023. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  113024. };
  113025. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  113026. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  113027. if (this._alphaMode === mode) {
  113028. return;
  113029. }
  113030. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  113031. if (!noDepthWriteChange) {
  113032. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  113033. }
  113034. this._alphaMode = mode;
  113035. };
  113036. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  113037. };
  113038. NullEngine.prototype.wipeCaches = function (bruteForce) {
  113039. if (this.preventCacheWipeBetweenFrames) {
  113040. return;
  113041. }
  113042. this.resetTextureCache();
  113043. this._currentEffect = null;
  113044. if (bruteForce) {
  113045. this._currentProgram = null;
  113046. this._stencilState.reset();
  113047. this._depthCullingState.reset();
  113048. this._alphaState.reset();
  113049. }
  113050. this._cachedVertexBuffers = null;
  113051. this._cachedIndexBuffer = null;
  113052. this._cachedEffectForVertexBuffers = null;
  113053. };
  113054. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  113055. };
  113056. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  113057. };
  113058. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  113059. };
  113060. /** @hidden */
  113061. NullEngine.prototype._createTexture = function () {
  113062. return {};
  113063. };
  113064. /** @hidden */
  113065. NullEngine.prototype._releaseTexture = function (texture) {
  113066. };
  113067. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  113068. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  113069. if (onLoad === void 0) { onLoad = null; }
  113070. if (onError === void 0) { onError = null; }
  113071. if (buffer === void 0) { buffer = null; }
  113072. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  113073. var url = String(urlArg);
  113074. texture.url = url;
  113075. texture.generateMipMaps = !noMipmap;
  113076. texture.samplingMode = samplingMode;
  113077. texture.invertY = invertY;
  113078. texture.baseWidth = this._options.textureSize;
  113079. texture.baseHeight = this._options.textureSize;
  113080. texture.width = this._options.textureSize;
  113081. texture.height = this._options.textureSize;
  113082. if (format) {
  113083. texture.format = format;
  113084. }
  113085. texture.isReady = true;
  113086. if (onLoad) {
  113087. onLoad();
  113088. }
  113089. this._internalTexturesCache.push(texture);
  113090. return texture;
  113091. };
  113092. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  113093. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  113094. if (options !== undefined && typeof options === "object") {
  113095. fullOptions.generateMipMaps = options.generateMipMaps;
  113096. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  113097. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  113098. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  113099. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  113100. }
  113101. else {
  113102. fullOptions.generateMipMaps = options;
  113103. fullOptions.generateDepthBuffer = true;
  113104. fullOptions.generateStencilBuffer = false;
  113105. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  113106. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  113107. }
  113108. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  113109. var width = size.width || size;
  113110. var height = size.height || size;
  113111. texture._depthStencilBuffer = {};
  113112. texture._framebuffer = {};
  113113. texture.baseWidth = width;
  113114. texture.baseHeight = height;
  113115. texture.width = width;
  113116. texture.height = height;
  113117. texture.isReady = true;
  113118. texture.samples = 1;
  113119. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  113120. texture.samplingMode = fullOptions.samplingMode;
  113121. texture.type = fullOptions.type;
  113122. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  113123. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  113124. this._internalTexturesCache.push(texture);
  113125. return texture;
  113126. };
  113127. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  113128. texture.samplingMode = samplingMode;
  113129. };
  113130. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  113131. if (this._currentRenderTarget) {
  113132. this.unBindFramebuffer(this._currentRenderTarget);
  113133. }
  113134. this._currentRenderTarget = texture;
  113135. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  113136. if (this._cachedViewport && !forceFullscreenViewport) {
  113137. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  113138. }
  113139. };
  113140. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  113141. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  113142. this._currentRenderTarget = null;
  113143. if (onBeforeUnbind) {
  113144. if (texture._MSAAFramebuffer) {
  113145. this._currentFramebuffer = texture._framebuffer;
  113146. }
  113147. onBeforeUnbind();
  113148. }
  113149. this._currentFramebuffer = null;
  113150. };
  113151. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  113152. var vbo = {
  113153. capacity: 1,
  113154. references: 1,
  113155. is32Bits: false
  113156. };
  113157. return vbo;
  113158. };
  113159. NullEngine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  113160. if (premulAlpha === void 0) { premulAlpha = false; }
  113161. };
  113162. /**
  113163. * @hidden
  113164. * Get the current error code of the webGL context
  113165. * @returns the error code
  113166. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  113167. */
  113168. NullEngine.prototype.getError = function () {
  113169. return 0;
  113170. };
  113171. /** @hidden */
  113172. NullEngine.prototype._getUnpackAlignement = function () {
  113173. return 1;
  113174. };
  113175. /** @hidden */
  113176. NullEngine.prototype._unpackFlipY = function (value) {
  113177. };
  113178. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  113179. if (offset === void 0) { offset = 0; }
  113180. };
  113181. /**
  113182. * Updates a dynamic vertex buffer.
  113183. * @param vertexBuffer the vertex buffer to update
  113184. * @param data the data used to update the vertex buffer
  113185. * @param byteOffset the byte offset of the data (optional)
  113186. * @param byteLength the byte length of the data (optional)
  113187. */
  113188. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  113189. };
  113190. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  113191. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  113192. this._boundTexturesCache[this._activeChannel] = texture;
  113193. return true;
  113194. }
  113195. return false;
  113196. };
  113197. /** @hidden */
  113198. NullEngine.prototype._bindTexture = function (channel, texture) {
  113199. if (channel < 0) {
  113200. return;
  113201. }
  113202. this._bindTextureDirectly(0, texture);
  113203. };
  113204. /** @hidden */
  113205. NullEngine.prototype._releaseBuffer = function (buffer) {
  113206. buffer.references--;
  113207. if (buffer.references === 0) {
  113208. return true;
  113209. }
  113210. return false;
  113211. };
  113212. NullEngine.prototype.releaseEffects = function () {
  113213. };
  113214. NullEngine.prototype.displayLoadingUI = function () {
  113215. };
  113216. NullEngine.prototype.hideLoadingUI = function () {
  113217. };
  113218. /** @hidden */
  113219. NullEngine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  113220. if (faceIndex === void 0) { faceIndex = 0; }
  113221. if (lod === void 0) { lod = 0; }
  113222. };
  113223. /** @hidden */
  113224. NullEngine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  113225. if (faceIndex === void 0) { faceIndex = 0; }
  113226. if (lod === void 0) { lod = 0; }
  113227. };
  113228. /** @hidden */
  113229. NullEngine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  113230. if (faceIndex === void 0) { faceIndex = 0; }
  113231. if (lod === void 0) { lod = 0; }
  113232. };
  113233. /** @hidden */
  113234. NullEngine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  113235. if (faceIndex === void 0) { faceIndex = 0; }
  113236. if (lod === void 0) { lod = 0; }
  113237. };
  113238. return NullEngine;
  113239. }(BABYLON.Engine));
  113240. BABYLON.NullEngine = NullEngine;
  113241. })(BABYLON || (BABYLON = {}));
  113242. //# sourceMappingURL=babylon.nullEngine.js.map
  113243. var BABYLON;
  113244. (function (BABYLON) {
  113245. /**
  113246. * This class can be used to get instrumentation data from a Babylon engine
  113247. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  113248. */
  113249. var EngineInstrumentation = /** @class */ (function () {
  113250. /**
  113251. * Instantiates a new engine instrumentation.
  113252. * This class can be used to get instrumentation data from a Babylon engine
  113253. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  113254. * @param engine Defines the engine to instrument
  113255. */
  113256. function EngineInstrumentation(
  113257. /**
  113258. * Define the instrumented engine.
  113259. */
  113260. engine) {
  113261. this.engine = engine;
  113262. this._captureGPUFrameTime = false;
  113263. this._gpuFrameTime = new BABYLON.PerfCounter();
  113264. this._captureShaderCompilationTime = false;
  113265. this._shaderCompilationTime = new BABYLON.PerfCounter();
  113266. // Observers
  113267. this._onBeginFrameObserver = null;
  113268. this._onEndFrameObserver = null;
  113269. this._onBeforeShaderCompilationObserver = null;
  113270. this._onAfterShaderCompilationObserver = null;
  113271. }
  113272. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  113273. // Properties
  113274. /**
  113275. * Gets the perf counter used for GPU frame time
  113276. */
  113277. get: function () {
  113278. return this._gpuFrameTime;
  113279. },
  113280. enumerable: true,
  113281. configurable: true
  113282. });
  113283. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  113284. /**
  113285. * Gets the GPU frame time capture status
  113286. */
  113287. get: function () {
  113288. return this._captureGPUFrameTime;
  113289. },
  113290. /**
  113291. * Enable or disable the GPU frame time capture
  113292. */
  113293. set: function (value) {
  113294. var _this = this;
  113295. if (value === this._captureGPUFrameTime) {
  113296. return;
  113297. }
  113298. this._captureGPUFrameTime = value;
  113299. if (value) {
  113300. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  113301. if (!_this._gpuFrameTimeToken) {
  113302. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  113303. }
  113304. });
  113305. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  113306. if (!_this._gpuFrameTimeToken) {
  113307. return;
  113308. }
  113309. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  113310. if (time > -1) {
  113311. _this._gpuFrameTimeToken = null;
  113312. _this._gpuFrameTime.fetchNewFrame();
  113313. _this._gpuFrameTime.addCount(time, true);
  113314. }
  113315. });
  113316. }
  113317. else {
  113318. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  113319. this._onBeginFrameObserver = null;
  113320. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  113321. this._onEndFrameObserver = null;
  113322. }
  113323. },
  113324. enumerable: true,
  113325. configurable: true
  113326. });
  113327. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  113328. /**
  113329. * Gets the perf counter used for shader compilation time
  113330. */
  113331. get: function () {
  113332. return this._shaderCompilationTime;
  113333. },
  113334. enumerable: true,
  113335. configurable: true
  113336. });
  113337. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  113338. /**
  113339. * Gets the shader compilation time capture status
  113340. */
  113341. get: function () {
  113342. return this._captureShaderCompilationTime;
  113343. },
  113344. /**
  113345. * Enable or disable the shader compilation time capture
  113346. */
  113347. set: function (value) {
  113348. var _this = this;
  113349. if (value === this._captureShaderCompilationTime) {
  113350. return;
  113351. }
  113352. this._captureShaderCompilationTime = value;
  113353. if (value) {
  113354. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  113355. _this._shaderCompilationTime.fetchNewFrame();
  113356. _this._shaderCompilationTime.beginMonitoring();
  113357. });
  113358. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  113359. _this._shaderCompilationTime.endMonitoring();
  113360. });
  113361. }
  113362. else {
  113363. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  113364. this._onBeforeShaderCompilationObserver = null;
  113365. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  113366. this._onAfterShaderCompilationObserver = null;
  113367. }
  113368. },
  113369. enumerable: true,
  113370. configurable: true
  113371. });
  113372. /**
  113373. * Dispose and release associated resources.
  113374. */
  113375. EngineInstrumentation.prototype.dispose = function () {
  113376. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  113377. this._onBeginFrameObserver = null;
  113378. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  113379. this._onEndFrameObserver = null;
  113380. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  113381. this._onBeforeShaderCompilationObserver = null;
  113382. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  113383. this._onAfterShaderCompilationObserver = null;
  113384. this.engine = null;
  113385. };
  113386. return EngineInstrumentation;
  113387. }());
  113388. BABYLON.EngineInstrumentation = EngineInstrumentation;
  113389. })(BABYLON || (BABYLON = {}));
  113390. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  113391. var BABYLON;
  113392. (function (BABYLON) {
  113393. /**
  113394. * This class can be used to get instrumentation data from a Babylon engine
  113395. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#sceneinstrumentation
  113396. */
  113397. var SceneInstrumentation = /** @class */ (function () {
  113398. /**
  113399. * Instantiates a new scene instrumentation.
  113400. * This class can be used to get instrumentation data from a Babylon engine
  113401. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#sceneinstrumentation
  113402. * @param scene Defines the scene to instrument
  113403. */
  113404. function SceneInstrumentation(
  113405. /**
  113406. * Defines the scene to instrument
  113407. */
  113408. scene) {
  113409. var _this = this;
  113410. this.scene = scene;
  113411. this._captureActiveMeshesEvaluationTime = false;
  113412. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  113413. this._captureRenderTargetsRenderTime = false;
  113414. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  113415. this._captureFrameTime = false;
  113416. this._frameTime = new BABYLON.PerfCounter();
  113417. this._captureRenderTime = false;
  113418. this._renderTime = new BABYLON.PerfCounter();
  113419. this._captureInterFrameTime = false;
  113420. this._interFrameTime = new BABYLON.PerfCounter();
  113421. this._captureParticlesRenderTime = false;
  113422. this._particlesRenderTime = new BABYLON.PerfCounter();
  113423. this._captureSpritesRenderTime = false;
  113424. this._spritesRenderTime = new BABYLON.PerfCounter();
  113425. this._capturePhysicsTime = false;
  113426. this._physicsTime = new BABYLON.PerfCounter();
  113427. this._captureAnimationsTime = false;
  113428. this._animationsTime = new BABYLON.PerfCounter();
  113429. this._captureCameraRenderTime = false;
  113430. this._cameraRenderTime = new BABYLON.PerfCounter();
  113431. // Observers
  113432. this._onBeforeActiveMeshesEvaluationObserver = null;
  113433. this._onAfterActiveMeshesEvaluationObserver = null;
  113434. this._onBeforeRenderTargetsRenderObserver = null;
  113435. this._onAfterRenderTargetsRenderObserver = null;
  113436. this._onAfterRenderObserver = null;
  113437. this._onBeforeDrawPhaseObserver = null;
  113438. this._onAfterDrawPhaseObserver = null;
  113439. this._onBeforeAnimationsObserver = null;
  113440. this._onBeforeParticlesRenderingObserver = null;
  113441. this._onAfterParticlesRenderingObserver = null;
  113442. this._onBeforeSpritesRenderingObserver = null;
  113443. this._onAfterSpritesRenderingObserver = null;
  113444. this._onBeforePhysicsObserver = null;
  113445. this._onAfterPhysicsObserver = null;
  113446. this._onAfterAnimationsObserver = null;
  113447. this._onBeforeCameraRenderObserver = null;
  113448. this._onAfterCameraRenderObserver = null;
  113449. // Before render
  113450. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  113451. if (_this._captureActiveMeshesEvaluationTime) {
  113452. _this._activeMeshesEvaluationTime.fetchNewFrame();
  113453. }
  113454. if (_this._captureRenderTargetsRenderTime) {
  113455. _this._renderTargetsRenderTime.fetchNewFrame();
  113456. }
  113457. if (_this._captureFrameTime) {
  113458. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  113459. _this._frameTime.beginMonitoring();
  113460. }
  113461. if (_this._captureInterFrameTime) {
  113462. _this._interFrameTime.endMonitoring();
  113463. }
  113464. if (_this._captureParticlesRenderTime) {
  113465. _this._particlesRenderTime.fetchNewFrame();
  113466. }
  113467. if (_this._captureSpritesRenderTime) {
  113468. _this._spritesRenderTime.fetchNewFrame();
  113469. }
  113470. if (_this._captureAnimationsTime) {
  113471. _this._animationsTime.beginMonitoring();
  113472. }
  113473. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  113474. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  113475. });
  113476. // After render
  113477. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  113478. if (_this._captureFrameTime) {
  113479. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  113480. _this._frameTime.endMonitoring();
  113481. }
  113482. if (_this._captureRenderTime) {
  113483. _this._renderTime.endMonitoring(false);
  113484. }
  113485. if (_this._captureInterFrameTime) {
  113486. _this._interFrameTime.beginMonitoring();
  113487. }
  113488. });
  113489. }
  113490. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  113491. // Properties
  113492. /**
  113493. * Gets the perf counter used for active meshes evaluation time
  113494. */
  113495. get: function () {
  113496. return this._activeMeshesEvaluationTime;
  113497. },
  113498. enumerable: true,
  113499. configurable: true
  113500. });
  113501. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  113502. /**
  113503. * Gets the active meshes evaluation time capture status
  113504. */
  113505. get: function () {
  113506. return this._captureActiveMeshesEvaluationTime;
  113507. },
  113508. /**
  113509. * Enable or disable the active meshes evaluation time capture
  113510. */
  113511. set: function (value) {
  113512. var _this = this;
  113513. if (value === this._captureActiveMeshesEvaluationTime) {
  113514. return;
  113515. }
  113516. this._captureActiveMeshesEvaluationTime = value;
  113517. if (value) {
  113518. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  113519. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  113520. _this._activeMeshesEvaluationTime.beginMonitoring();
  113521. });
  113522. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  113523. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  113524. _this._activeMeshesEvaluationTime.endMonitoring();
  113525. });
  113526. }
  113527. else {
  113528. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  113529. this._onBeforeActiveMeshesEvaluationObserver = null;
  113530. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  113531. this._onAfterActiveMeshesEvaluationObserver = null;
  113532. }
  113533. },
  113534. enumerable: true,
  113535. configurable: true
  113536. });
  113537. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  113538. /**
  113539. * Gets the perf counter used for render targets render time
  113540. */
  113541. get: function () {
  113542. return this._renderTargetsRenderTime;
  113543. },
  113544. enumerable: true,
  113545. configurable: true
  113546. });
  113547. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  113548. /**
  113549. * Gets the render targets render time capture status
  113550. */
  113551. get: function () {
  113552. return this._captureRenderTargetsRenderTime;
  113553. },
  113554. /**
  113555. * Enable or disable the render targets render time capture
  113556. */
  113557. set: function (value) {
  113558. var _this = this;
  113559. if (value === this._captureRenderTargetsRenderTime) {
  113560. return;
  113561. }
  113562. this._captureRenderTargetsRenderTime = value;
  113563. if (value) {
  113564. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  113565. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  113566. _this._renderTargetsRenderTime.beginMonitoring();
  113567. });
  113568. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  113569. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  113570. _this._renderTargetsRenderTime.endMonitoring(false);
  113571. });
  113572. }
  113573. else {
  113574. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  113575. this._onBeforeRenderTargetsRenderObserver = null;
  113576. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  113577. this._onAfterRenderTargetsRenderObserver = null;
  113578. }
  113579. },
  113580. enumerable: true,
  113581. configurable: true
  113582. });
  113583. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  113584. /**
  113585. * Gets the perf counter used for particles render time
  113586. */
  113587. get: function () {
  113588. return this._particlesRenderTime;
  113589. },
  113590. enumerable: true,
  113591. configurable: true
  113592. });
  113593. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  113594. /**
  113595. * Gets the particles render time capture status
  113596. */
  113597. get: function () {
  113598. return this._captureParticlesRenderTime;
  113599. },
  113600. /**
  113601. * Enable or disable the particles render time capture
  113602. */
  113603. set: function (value) {
  113604. var _this = this;
  113605. if (value === this._captureParticlesRenderTime) {
  113606. return;
  113607. }
  113608. this._captureParticlesRenderTime = value;
  113609. if (value) {
  113610. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  113611. BABYLON.Tools.StartPerformanceCounter("Particles");
  113612. _this._particlesRenderTime.beginMonitoring();
  113613. });
  113614. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  113615. BABYLON.Tools.EndPerformanceCounter("Particles");
  113616. _this._particlesRenderTime.endMonitoring(false);
  113617. });
  113618. }
  113619. else {
  113620. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  113621. this._onBeforeParticlesRenderingObserver = null;
  113622. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  113623. this._onAfterParticlesRenderingObserver = null;
  113624. }
  113625. },
  113626. enumerable: true,
  113627. configurable: true
  113628. });
  113629. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  113630. /**
  113631. * Gets the perf counter used for sprites render time
  113632. */
  113633. get: function () {
  113634. return this._spritesRenderTime;
  113635. },
  113636. enumerable: true,
  113637. configurable: true
  113638. });
  113639. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  113640. /**
  113641. * Gets the sprites render time capture status
  113642. */
  113643. get: function () {
  113644. return this._captureSpritesRenderTime;
  113645. },
  113646. /**
  113647. * Enable or disable the sprites render time capture
  113648. */
  113649. set: function (value) {
  113650. var _this = this;
  113651. if (value === this._captureSpritesRenderTime) {
  113652. return;
  113653. }
  113654. this._captureSpritesRenderTime = value;
  113655. if (!this.scene.spriteManagers) {
  113656. return;
  113657. }
  113658. if (value) {
  113659. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  113660. BABYLON.Tools.StartPerformanceCounter("Sprites");
  113661. _this._spritesRenderTime.beginMonitoring();
  113662. });
  113663. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  113664. BABYLON.Tools.EndPerformanceCounter("Sprites");
  113665. _this._spritesRenderTime.endMonitoring(false);
  113666. });
  113667. }
  113668. else {
  113669. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  113670. this._onBeforeSpritesRenderingObserver = null;
  113671. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  113672. this._onAfterSpritesRenderingObserver = null;
  113673. }
  113674. },
  113675. enumerable: true,
  113676. configurable: true
  113677. });
  113678. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  113679. /**
  113680. * Gets the perf counter used for physics time
  113681. */
  113682. get: function () {
  113683. return this._physicsTime;
  113684. },
  113685. enumerable: true,
  113686. configurable: true
  113687. });
  113688. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  113689. /**
  113690. * Gets the physics time capture status
  113691. */
  113692. get: function () {
  113693. return this._capturePhysicsTime;
  113694. },
  113695. /**
  113696. * Enable or disable the physics time capture
  113697. */
  113698. set: function (value) {
  113699. var _this = this;
  113700. if (value === this._capturePhysicsTime) {
  113701. return;
  113702. }
  113703. if (!this.scene.onBeforePhysicsObservable) {
  113704. return;
  113705. }
  113706. this._capturePhysicsTime = value;
  113707. if (value) {
  113708. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  113709. BABYLON.Tools.StartPerformanceCounter("Physics");
  113710. _this._physicsTime.beginMonitoring();
  113711. });
  113712. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  113713. BABYLON.Tools.EndPerformanceCounter("Physics");
  113714. _this._physicsTime.endMonitoring();
  113715. });
  113716. }
  113717. else {
  113718. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  113719. this._onBeforePhysicsObserver = null;
  113720. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  113721. this._onAfterPhysicsObserver = null;
  113722. }
  113723. },
  113724. enumerable: true,
  113725. configurable: true
  113726. });
  113727. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  113728. /**
  113729. * Gets the perf counter used for animations time
  113730. */
  113731. get: function () {
  113732. return this._animationsTime;
  113733. },
  113734. enumerable: true,
  113735. configurable: true
  113736. });
  113737. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  113738. /**
  113739. * Gets the animations time capture status
  113740. */
  113741. get: function () {
  113742. return this._captureAnimationsTime;
  113743. },
  113744. /**
  113745. * Enable or disable the animations time capture
  113746. */
  113747. set: function (value) {
  113748. var _this = this;
  113749. if (value === this._captureAnimationsTime) {
  113750. return;
  113751. }
  113752. this._captureAnimationsTime = value;
  113753. if (value) {
  113754. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  113755. _this._animationsTime.endMonitoring();
  113756. });
  113757. }
  113758. else {
  113759. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  113760. this._onAfterAnimationsObserver = null;
  113761. }
  113762. },
  113763. enumerable: true,
  113764. configurable: true
  113765. });
  113766. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  113767. /**
  113768. * Gets the perf counter used for frame time capture
  113769. */
  113770. get: function () {
  113771. return this._frameTime;
  113772. },
  113773. enumerable: true,
  113774. configurable: true
  113775. });
  113776. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  113777. /**
  113778. * Gets the frame time capture status
  113779. */
  113780. get: function () {
  113781. return this._captureFrameTime;
  113782. },
  113783. /**
  113784. * Enable or disable the frame time capture
  113785. */
  113786. set: function (value) {
  113787. this._captureFrameTime = value;
  113788. },
  113789. enumerable: true,
  113790. configurable: true
  113791. });
  113792. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  113793. /**
  113794. * Gets the perf counter used for inter-frames time capture
  113795. */
  113796. get: function () {
  113797. return this._interFrameTime;
  113798. },
  113799. enumerable: true,
  113800. configurable: true
  113801. });
  113802. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  113803. /**
  113804. * Gets the inter-frames time capture status
  113805. */
  113806. get: function () {
  113807. return this._captureInterFrameTime;
  113808. },
  113809. /**
  113810. * Enable or disable the inter-frames time capture
  113811. */
  113812. set: function (value) {
  113813. this._captureInterFrameTime = value;
  113814. },
  113815. enumerable: true,
  113816. configurable: true
  113817. });
  113818. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  113819. /**
  113820. * Gets the perf counter used for render time capture
  113821. */
  113822. get: function () {
  113823. return this._renderTime;
  113824. },
  113825. enumerable: true,
  113826. configurable: true
  113827. });
  113828. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  113829. /**
  113830. * Gets the render time capture status
  113831. */
  113832. get: function () {
  113833. return this._captureRenderTime;
  113834. },
  113835. /**
  113836. * Enable or disable the render time capture
  113837. */
  113838. set: function (value) {
  113839. var _this = this;
  113840. if (value === this._captureRenderTime) {
  113841. return;
  113842. }
  113843. this._captureRenderTime = value;
  113844. if (value) {
  113845. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  113846. _this._renderTime.beginMonitoring();
  113847. BABYLON.Tools.StartPerformanceCounter("Main render");
  113848. });
  113849. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  113850. _this._renderTime.endMonitoring(false);
  113851. BABYLON.Tools.EndPerformanceCounter("Main render");
  113852. });
  113853. }
  113854. else {
  113855. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  113856. this._onBeforeDrawPhaseObserver = null;
  113857. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  113858. this._onAfterDrawPhaseObserver = null;
  113859. }
  113860. },
  113861. enumerable: true,
  113862. configurable: true
  113863. });
  113864. Object.defineProperty(SceneInstrumentation.prototype, "cameraRenderTimeCounter", {
  113865. /**
  113866. * Gets the perf counter used for camera render time capture
  113867. */
  113868. get: function () {
  113869. return this._cameraRenderTime;
  113870. },
  113871. enumerable: true,
  113872. configurable: true
  113873. });
  113874. Object.defineProperty(SceneInstrumentation.prototype, "captureCameraRenderTime", {
  113875. /**
  113876. * Gets the camera render time capture status
  113877. */
  113878. get: function () {
  113879. return this._captureCameraRenderTime;
  113880. },
  113881. /**
  113882. * Enable or disable the camera render time capture
  113883. */
  113884. set: function (value) {
  113885. var _this = this;
  113886. if (value === this._captureCameraRenderTime) {
  113887. return;
  113888. }
  113889. this._captureCameraRenderTime = value;
  113890. if (value) {
  113891. this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function (camera) {
  113892. _this._cameraRenderTime.beginMonitoring();
  113893. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + camera.name);
  113894. });
  113895. this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function (camera) {
  113896. _this._cameraRenderTime.endMonitoring(false);
  113897. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + camera.name);
  113898. });
  113899. }
  113900. else {
  113901. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  113902. this._onBeforeCameraRenderObserver = null;
  113903. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  113904. this._onAfterCameraRenderObserver = null;
  113905. }
  113906. },
  113907. enumerable: true,
  113908. configurable: true
  113909. });
  113910. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  113911. /**
  113912. * Gets the perf counter used for draw calls
  113913. */
  113914. get: function () {
  113915. return this.scene.getEngine()._drawCalls;
  113916. },
  113917. enumerable: true,
  113918. configurable: true
  113919. });
  113920. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  113921. /**
  113922. * Gets the perf counter used for texture collisions
  113923. */
  113924. get: function () {
  113925. return this.scene.getEngine()._textureCollisions;
  113926. },
  113927. enumerable: true,
  113928. configurable: true
  113929. });
  113930. /**
  113931. * Dispose and release associated resources.
  113932. */
  113933. SceneInstrumentation.prototype.dispose = function () {
  113934. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  113935. this._onAfterRenderObserver = null;
  113936. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  113937. this._onBeforeActiveMeshesEvaluationObserver = null;
  113938. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  113939. this._onAfterActiveMeshesEvaluationObserver = null;
  113940. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  113941. this._onBeforeRenderTargetsRenderObserver = null;
  113942. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  113943. this._onAfterRenderTargetsRenderObserver = null;
  113944. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  113945. this._onBeforeAnimationsObserver = null;
  113946. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  113947. this._onBeforeParticlesRenderingObserver = null;
  113948. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  113949. this._onAfterParticlesRenderingObserver = null;
  113950. if (this._onBeforeSpritesRenderingObserver) {
  113951. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  113952. this._onBeforeSpritesRenderingObserver = null;
  113953. }
  113954. if (this._onAfterSpritesRenderingObserver) {
  113955. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  113956. this._onAfterSpritesRenderingObserver = null;
  113957. }
  113958. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  113959. this._onBeforeDrawPhaseObserver = null;
  113960. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  113961. this._onAfterDrawPhaseObserver = null;
  113962. if (this._onBeforePhysicsObserver) {
  113963. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  113964. this._onBeforePhysicsObserver = null;
  113965. }
  113966. if (this._onAfterPhysicsObserver) {
  113967. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  113968. this._onAfterPhysicsObserver = null;
  113969. }
  113970. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  113971. this._onAfterAnimationsObserver = null;
  113972. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  113973. this._onBeforeCameraRenderObserver = null;
  113974. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  113975. this._onAfterCameraRenderObserver = null;
  113976. this.scene = null;
  113977. };
  113978. return SceneInstrumentation;
  113979. }());
  113980. BABYLON.SceneInstrumentation = SceneInstrumentation;
  113981. })(BABYLON || (BABYLON = {}));
  113982. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  113983. var BABYLON;
  113984. (function (BABYLON) {
  113985. /**
  113986. * @hidden
  113987. **/
  113988. var _TimeToken = /** @class */ (function () {
  113989. function _TimeToken() {
  113990. this._timeElapsedQueryEnded = false;
  113991. }
  113992. return _TimeToken;
  113993. }());
  113994. BABYLON._TimeToken = _TimeToken;
  113995. })(BABYLON || (BABYLON = {}));
  113996. //# sourceMappingURL=babylon.timeToken.js.map
  113997. var BABYLON;
  113998. (function (BABYLON) {
  113999. /**
  114000. * Background material defines definition.
  114001. * @hidden Mainly internal Use
  114002. */
  114003. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  114004. __extends(BackgroundMaterialDefines, _super);
  114005. /**
  114006. * Constructor of the defines.
  114007. */
  114008. function BackgroundMaterialDefines() {
  114009. var _this = _super.call(this) || this;
  114010. /**
  114011. * True if the diffuse texture is in use.
  114012. */
  114013. _this.DIFFUSE = false;
  114014. /**
  114015. * The direct UV channel to use.
  114016. */
  114017. _this.DIFFUSEDIRECTUV = 0;
  114018. /**
  114019. * True if the diffuse texture is in gamma space.
  114020. */
  114021. _this.GAMMADIFFUSE = false;
  114022. /**
  114023. * True if the diffuse texture has opacity in the alpha channel.
  114024. */
  114025. _this.DIFFUSEHASALPHA = false;
  114026. /**
  114027. * True if you want the material to fade to transparent at grazing angle.
  114028. */
  114029. _this.OPACITYFRESNEL = false;
  114030. /**
  114031. * True if an extra blur needs to be added in the reflection.
  114032. */
  114033. _this.REFLECTIONBLUR = false;
  114034. /**
  114035. * True if you want the material to fade to reflection at grazing angle.
  114036. */
  114037. _this.REFLECTIONFRESNEL = false;
  114038. /**
  114039. * True if you want the material to falloff as far as you move away from the scene center.
  114040. */
  114041. _this.REFLECTIONFALLOFF = false;
  114042. /**
  114043. * False if the current Webgl implementation does not support the texture lod extension.
  114044. */
  114045. _this.TEXTURELODSUPPORT = false;
  114046. /**
  114047. * True to ensure the data are premultiplied.
  114048. */
  114049. _this.PREMULTIPLYALPHA = false;
  114050. /**
  114051. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  114052. */
  114053. _this.USERGBCOLOR = false;
  114054. /**
  114055. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  114056. * stays aligned with the desired configuration.
  114057. */
  114058. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  114059. /**
  114060. * True to add noise in order to reduce the banding effect.
  114061. */
  114062. _this.NOISE = false;
  114063. /**
  114064. * is the reflection texture in BGR color scheme?
  114065. * Mainly used to solve a bug in ios10 video tag
  114066. */
  114067. _this.REFLECTIONBGR = false;
  114068. _this.IMAGEPROCESSING = false;
  114069. _this.VIGNETTE = false;
  114070. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  114071. _this.VIGNETTEBLENDMODEOPAQUE = false;
  114072. _this.TONEMAPPING = false;
  114073. _this.TONEMAPPING_ACES = false;
  114074. _this.CONTRAST = false;
  114075. _this.COLORCURVES = false;
  114076. _this.COLORGRADING = false;
  114077. _this.COLORGRADING3D = false;
  114078. _this.SAMPLER3DGREENDEPTH = false;
  114079. _this.SAMPLER3DBGRMAP = false;
  114080. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  114081. _this.EXPOSURE = false;
  114082. // Reflection.
  114083. _this.REFLECTION = false;
  114084. _this.REFLECTIONMAP_3D = false;
  114085. _this.REFLECTIONMAP_SPHERICAL = false;
  114086. _this.REFLECTIONMAP_PLANAR = false;
  114087. _this.REFLECTIONMAP_CUBIC = false;
  114088. _this.REFLECTIONMAP_PROJECTION = false;
  114089. _this.REFLECTIONMAP_SKYBOX = false;
  114090. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  114091. _this.REFLECTIONMAP_EXPLICIT = false;
  114092. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  114093. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  114094. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  114095. _this.INVERTCUBICMAP = false;
  114096. _this.REFLECTIONMAP_OPPOSITEZ = false;
  114097. _this.LODINREFLECTIONALPHA = false;
  114098. _this.GAMMAREFLECTION = false;
  114099. _this.RGBDREFLECTION = false;
  114100. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  114101. // Default BJS.
  114102. _this.MAINUV1 = false;
  114103. _this.MAINUV2 = false;
  114104. _this.UV1 = false;
  114105. _this.UV2 = false;
  114106. _this.CLIPPLANE = false;
  114107. _this.CLIPPLANE2 = false;
  114108. _this.CLIPPLANE3 = false;
  114109. _this.CLIPPLANE4 = false;
  114110. _this.POINTSIZE = false;
  114111. _this.FOG = false;
  114112. _this.NORMAL = false;
  114113. _this.NUM_BONE_INFLUENCERS = 0;
  114114. _this.BonesPerMesh = 0;
  114115. _this.INSTANCES = false;
  114116. _this.SHADOWFLOAT = false;
  114117. _this.rebuild();
  114118. return _this;
  114119. }
  114120. return BackgroundMaterialDefines;
  114121. }(BABYLON.MaterialDefines));
  114122. /**
  114123. * Background material used to create an efficient environement around your scene.
  114124. */
  114125. var BackgroundMaterial = /** @class */ (function (_super) {
  114126. __extends(BackgroundMaterial, _super);
  114127. /**
  114128. * Instantiates a Background Material in the given scene
  114129. * @param name The friendly name of the material
  114130. * @param scene The scene to add the material to
  114131. */
  114132. function BackgroundMaterial(name, scene) {
  114133. var _this = _super.call(this, name, scene) || this;
  114134. /**
  114135. * Key light Color (multiply against the environement texture)
  114136. */
  114137. _this.primaryColor = BABYLON.Color3.White();
  114138. _this._primaryColorShadowLevel = 0;
  114139. _this._primaryColorHighlightLevel = 0;
  114140. /**
  114141. * Reflection Texture used in the material.
  114142. * Should be author in a specific way for the best result (refer to the documentation).
  114143. */
  114144. _this.reflectionTexture = null;
  114145. /**
  114146. * Reflection Texture level of blur.
  114147. *
  114148. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  114149. * texture twice.
  114150. */
  114151. _this.reflectionBlur = 0;
  114152. /**
  114153. * Diffuse Texture used in the material.
  114154. * Should be author in a specific way for the best result (refer to the documentation).
  114155. */
  114156. _this.diffuseTexture = null;
  114157. _this._shadowLights = null;
  114158. /**
  114159. * Specify the list of lights casting shadow on the material.
  114160. * All scene shadow lights will be included if null.
  114161. */
  114162. _this.shadowLights = null;
  114163. /**
  114164. * Helps adjusting the shadow to a softer level if required.
  114165. * 0 means black shadows and 1 means no shadows.
  114166. */
  114167. _this.shadowLevel = 0;
  114168. /**
  114169. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  114170. * It is usually zero but might be interesting to modify according to your setup.
  114171. */
  114172. _this.sceneCenter = BABYLON.Vector3.Zero();
  114173. /**
  114174. * This helps specifying that the material is falling off to the sky box at grazing angle.
  114175. * This helps ensuring a nice transition when the camera goes under the ground.
  114176. */
  114177. _this.opacityFresnel = true;
  114178. /**
  114179. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  114180. * This helps adding a mirror texture on the ground.
  114181. */
  114182. _this.reflectionFresnel = false;
  114183. /**
  114184. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  114185. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  114186. */
  114187. _this.reflectionFalloffDistance = 0.0;
  114188. /**
  114189. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  114190. */
  114191. _this.reflectionAmount = 1.0;
  114192. /**
  114193. * This specifies the weight of the reflection at grazing angle.
  114194. */
  114195. _this.reflectionReflectance0 = 0.05;
  114196. /**
  114197. * This specifies the weight of the reflection at a perpendicular point of view.
  114198. */
  114199. _this.reflectionReflectance90 = 0.5;
  114200. /**
  114201. * Helps to directly use the maps channels instead of their level.
  114202. */
  114203. _this.useRGBColor = true;
  114204. /**
  114205. * This helps reducing the banding effect that could occur on the background.
  114206. */
  114207. _this.enableNoise = false;
  114208. _this._fovMultiplier = 1.0;
  114209. /**
  114210. * Enable the FOV adjustment feature controlled by fovMultiplier.
  114211. */
  114212. _this.useEquirectangularFOV = false;
  114213. _this._maxSimultaneousLights = 4;
  114214. /**
  114215. * Number of Simultaneous lights allowed on the material.
  114216. */
  114217. _this.maxSimultaneousLights = 4;
  114218. /**
  114219. * Keep track of the image processing observer to allow dispose and replace.
  114220. */
  114221. _this._imageProcessingObserver = null;
  114222. /**
  114223. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  114224. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  114225. */
  114226. _this.switchToBGR = false;
  114227. // Temp values kept as cache in the material.
  114228. _this._renderTargets = new BABYLON.SmartArray(16);
  114229. _this._reflectionControls = BABYLON.Vector4.Zero();
  114230. _this._white = BABYLON.Color3.White();
  114231. _this._primaryShadowColor = BABYLON.Color3.Black();
  114232. _this._primaryHighlightColor = BABYLON.Color3.Black();
  114233. // Setup the default processing configuration to the scene.
  114234. _this._attachImageProcessingConfiguration(null);
  114235. _this.getRenderTargetTextures = function () {
  114236. _this._renderTargets.reset();
  114237. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  114238. _this._renderTargets.push(_this._diffuseTexture);
  114239. }
  114240. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  114241. _this._renderTargets.push(_this._reflectionTexture);
  114242. }
  114243. return _this._renderTargets;
  114244. };
  114245. return _this;
  114246. }
  114247. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  114248. /**
  114249. * Experimental Internal Use Only.
  114250. *
  114251. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  114252. * This acts as a helper to set the primary color to a more "human friendly" value.
  114253. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  114254. * output color as close as possible from the chosen value.
  114255. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  114256. * part of lighting setup.)
  114257. */
  114258. get: function () {
  114259. return this.__perceptualColor;
  114260. },
  114261. set: function (value) {
  114262. this.__perceptualColor = value;
  114263. this._computePrimaryColorFromPerceptualColor();
  114264. this._markAllSubMeshesAsLightsDirty();
  114265. },
  114266. enumerable: true,
  114267. configurable: true
  114268. });
  114269. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  114270. /**
  114271. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  114272. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  114273. */
  114274. get: function () {
  114275. return this._primaryColorShadowLevel;
  114276. },
  114277. set: function (value) {
  114278. this._primaryColorShadowLevel = value;
  114279. this._computePrimaryColors();
  114280. this._markAllSubMeshesAsLightsDirty();
  114281. },
  114282. enumerable: true,
  114283. configurable: true
  114284. });
  114285. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  114286. /**
  114287. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  114288. * The primary color is used at the level chosen to define what the white area would look.
  114289. */
  114290. get: function () {
  114291. return this._primaryColorHighlightLevel;
  114292. },
  114293. set: function (value) {
  114294. this._primaryColorHighlightLevel = value;
  114295. this._computePrimaryColors();
  114296. this._markAllSubMeshesAsLightsDirty();
  114297. },
  114298. enumerable: true,
  114299. configurable: true
  114300. });
  114301. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  114302. /**
  114303. * Sets the reflection reflectance fresnel values according to the default standard
  114304. * empirically know to work well :-)
  114305. */
  114306. set: function (value) {
  114307. var reflectionWeight = value;
  114308. if (reflectionWeight < 0.5) {
  114309. reflectionWeight = reflectionWeight * 2.0;
  114310. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  114311. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  114312. }
  114313. else {
  114314. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  114315. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  114316. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  114317. }
  114318. },
  114319. enumerable: true,
  114320. configurable: true
  114321. });
  114322. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  114323. /**
  114324. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  114325. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  114326. * Recommended to be keep at 1.0 except for special cases.
  114327. */
  114328. get: function () {
  114329. return this._fovMultiplier;
  114330. },
  114331. set: function (value) {
  114332. if (isNaN(value)) {
  114333. value = 1.0;
  114334. }
  114335. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  114336. },
  114337. enumerable: true,
  114338. configurable: true
  114339. });
  114340. /**
  114341. * Attaches a new image processing configuration to the PBR Material.
  114342. * @param configuration (if null the scene configuration will be use)
  114343. */
  114344. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  114345. var _this = this;
  114346. if (configuration === this._imageProcessingConfiguration) {
  114347. return;
  114348. }
  114349. // Detaches observer.
  114350. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  114351. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  114352. }
  114353. // Pick the scene configuration if needed.
  114354. if (!configuration) {
  114355. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  114356. }
  114357. else {
  114358. this._imageProcessingConfiguration = configuration;
  114359. }
  114360. // Attaches observer.
  114361. if (this._imageProcessingConfiguration) {
  114362. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  114363. _this._computePrimaryColorFromPerceptualColor();
  114364. _this._markAllSubMeshesAsImageProcessingDirty();
  114365. });
  114366. }
  114367. };
  114368. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  114369. /**
  114370. * Gets the image processing configuration used either in this material.
  114371. */
  114372. get: function () {
  114373. return this._imageProcessingConfiguration;
  114374. },
  114375. /**
  114376. * Sets the Default image processing configuration used either in the this material.
  114377. *
  114378. * If sets to null, the scene one is in use.
  114379. */
  114380. set: function (value) {
  114381. this._attachImageProcessingConfiguration(value);
  114382. // Ensure the effect will be rebuilt.
  114383. this._markAllSubMeshesAsTexturesDirty();
  114384. },
  114385. enumerable: true,
  114386. configurable: true
  114387. });
  114388. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  114389. /**
  114390. * Gets wether the color curves effect is enabled.
  114391. */
  114392. get: function () {
  114393. return this.imageProcessingConfiguration.colorCurvesEnabled;
  114394. },
  114395. /**
  114396. * Sets wether the color curves effect is enabled.
  114397. */
  114398. set: function (value) {
  114399. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  114400. },
  114401. enumerable: true,
  114402. configurable: true
  114403. });
  114404. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  114405. /**
  114406. * Gets wether the color grading effect is enabled.
  114407. */
  114408. get: function () {
  114409. return this.imageProcessingConfiguration.colorGradingEnabled;
  114410. },
  114411. /**
  114412. * Gets wether the color grading effect is enabled.
  114413. */
  114414. set: function (value) {
  114415. this.imageProcessingConfiguration.colorGradingEnabled = value;
  114416. },
  114417. enumerable: true,
  114418. configurable: true
  114419. });
  114420. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  114421. /**
  114422. * Gets wether tonemapping is enabled or not.
  114423. */
  114424. get: function () {
  114425. return this._imageProcessingConfiguration.toneMappingEnabled;
  114426. },
  114427. /**
  114428. * Sets wether tonemapping is enabled or not
  114429. */
  114430. set: function (value) {
  114431. this._imageProcessingConfiguration.toneMappingEnabled = value;
  114432. },
  114433. enumerable: true,
  114434. configurable: true
  114435. });
  114436. ;
  114437. ;
  114438. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  114439. /**
  114440. * The camera exposure used on this material.
  114441. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  114442. * This corresponds to a photographic exposure.
  114443. */
  114444. get: function () {
  114445. return this._imageProcessingConfiguration.exposure;
  114446. },
  114447. /**
  114448. * The camera exposure used on this material.
  114449. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  114450. * This corresponds to a photographic exposure.
  114451. */
  114452. set: function (value) {
  114453. this._imageProcessingConfiguration.exposure = value;
  114454. },
  114455. enumerable: true,
  114456. configurable: true
  114457. });
  114458. ;
  114459. ;
  114460. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  114461. /**
  114462. * Gets The camera contrast used on this material.
  114463. */
  114464. get: function () {
  114465. return this._imageProcessingConfiguration.contrast;
  114466. },
  114467. /**
  114468. * Sets The camera contrast used on this material.
  114469. */
  114470. set: function (value) {
  114471. this._imageProcessingConfiguration.contrast = value;
  114472. },
  114473. enumerable: true,
  114474. configurable: true
  114475. });
  114476. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  114477. /**
  114478. * Gets the Color Grading 2D Lookup Texture.
  114479. */
  114480. get: function () {
  114481. return this._imageProcessingConfiguration.colorGradingTexture;
  114482. },
  114483. /**
  114484. * Sets the Color Grading 2D Lookup Texture.
  114485. */
  114486. set: function (value) {
  114487. this.imageProcessingConfiguration.colorGradingTexture = value;
  114488. },
  114489. enumerable: true,
  114490. configurable: true
  114491. });
  114492. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  114493. /**
  114494. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  114495. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  114496. * 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;
  114497. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  114498. */
  114499. get: function () {
  114500. return this.imageProcessingConfiguration.colorCurves;
  114501. },
  114502. /**
  114503. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  114504. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  114505. * 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;
  114506. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  114507. */
  114508. set: function (value) {
  114509. this.imageProcessingConfiguration.colorCurves = value;
  114510. },
  114511. enumerable: true,
  114512. configurable: true
  114513. });
  114514. Object.defineProperty(BackgroundMaterial.prototype, "hasRenderTargetTextures", {
  114515. /**
  114516. * Gets a boolean indicating that current material needs to register RTT
  114517. */
  114518. get: function () {
  114519. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  114520. return true;
  114521. }
  114522. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  114523. return true;
  114524. }
  114525. return false;
  114526. },
  114527. enumerable: true,
  114528. configurable: true
  114529. });
  114530. /**
  114531. * The entire material has been created in order to prevent overdraw.
  114532. * @returns false
  114533. */
  114534. BackgroundMaterial.prototype.needAlphaTesting = function () {
  114535. return true;
  114536. };
  114537. /**
  114538. * The entire material has been created in order to prevent overdraw.
  114539. * @returns true if blending is enable
  114540. */
  114541. BackgroundMaterial.prototype.needAlphaBlending = function () {
  114542. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  114543. };
  114544. /**
  114545. * Checks wether the material is ready to be rendered for a given mesh.
  114546. * @param mesh The mesh to render
  114547. * @param subMesh The submesh to check against
  114548. * @param useInstances Specify wether or not the material is used with instances
  114549. * @returns true if all the dependencies are ready (Textures, Effects...)
  114550. */
  114551. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  114552. var _this = this;
  114553. if (useInstances === void 0) { useInstances = false; }
  114554. if (subMesh.effect && this.isFrozen) {
  114555. if (this._wasPreviouslyReady) {
  114556. return true;
  114557. }
  114558. }
  114559. if (!subMesh._materialDefines) {
  114560. subMesh._materialDefines = new BackgroundMaterialDefines();
  114561. }
  114562. var scene = this.getScene();
  114563. var defines = subMesh._materialDefines;
  114564. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  114565. if (defines._renderId === scene.getRenderId()) {
  114566. return true;
  114567. }
  114568. }
  114569. var engine = scene.getEngine();
  114570. // Lights
  114571. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  114572. defines._needNormals = true;
  114573. // Textures
  114574. if (defines._areTexturesDirty) {
  114575. defines._needUVs = false;
  114576. if (scene.texturesEnabled) {
  114577. if (scene.getEngine().getCaps().textureLOD) {
  114578. defines.TEXTURELODSUPPORT = true;
  114579. }
  114580. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  114581. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  114582. return false;
  114583. }
  114584. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  114585. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  114586. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  114587. defines.OPACITYFRESNEL = this._opacityFresnel;
  114588. }
  114589. else {
  114590. defines.DIFFUSE = false;
  114591. defines.DIFFUSEHASALPHA = false;
  114592. defines.GAMMADIFFUSE = false;
  114593. defines.OPACITYFRESNEL = false;
  114594. }
  114595. var reflectionTexture = this._reflectionTexture;
  114596. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  114597. if (!reflectionTexture.isReadyOrNotBlocking()) {
  114598. return false;
  114599. }
  114600. defines.REFLECTION = true;
  114601. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  114602. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  114603. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  114604. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  114605. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  114606. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  114607. defines.REFLECTIONBGR = this.switchToBGR;
  114608. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  114609. defines.INVERTCUBICMAP = true;
  114610. }
  114611. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  114612. switch (reflectionTexture.coordinatesMode) {
  114613. case BABYLON.Texture.EXPLICIT_MODE:
  114614. defines.REFLECTIONMAP_EXPLICIT = true;
  114615. break;
  114616. case BABYLON.Texture.PLANAR_MODE:
  114617. defines.REFLECTIONMAP_PLANAR = true;
  114618. break;
  114619. case BABYLON.Texture.PROJECTION_MODE:
  114620. defines.REFLECTIONMAP_PROJECTION = true;
  114621. break;
  114622. case BABYLON.Texture.SKYBOX_MODE:
  114623. defines.REFLECTIONMAP_SKYBOX = true;
  114624. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  114625. break;
  114626. case BABYLON.Texture.SPHERICAL_MODE:
  114627. defines.REFLECTIONMAP_SPHERICAL = true;
  114628. break;
  114629. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  114630. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  114631. break;
  114632. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  114633. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  114634. break;
  114635. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  114636. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  114637. break;
  114638. case BABYLON.Texture.CUBIC_MODE:
  114639. case BABYLON.Texture.INVCUBIC_MODE:
  114640. default:
  114641. defines.REFLECTIONMAP_CUBIC = true;
  114642. break;
  114643. }
  114644. if (this.reflectionFresnel) {
  114645. defines.REFLECTIONFRESNEL = true;
  114646. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  114647. this._reflectionControls.x = this.reflectionAmount;
  114648. this._reflectionControls.y = this.reflectionReflectance0;
  114649. this._reflectionControls.z = this.reflectionReflectance90;
  114650. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  114651. }
  114652. else {
  114653. defines.REFLECTIONFRESNEL = false;
  114654. defines.REFLECTIONFALLOFF = false;
  114655. }
  114656. }
  114657. else {
  114658. defines.REFLECTION = false;
  114659. defines.REFLECTIONFRESNEL = false;
  114660. defines.REFLECTIONFALLOFF = false;
  114661. defines.REFLECTIONBLUR = false;
  114662. defines.REFLECTIONMAP_3D = false;
  114663. defines.REFLECTIONMAP_SPHERICAL = false;
  114664. defines.REFLECTIONMAP_PLANAR = false;
  114665. defines.REFLECTIONMAP_CUBIC = false;
  114666. defines.REFLECTIONMAP_PROJECTION = false;
  114667. defines.REFLECTIONMAP_SKYBOX = false;
  114668. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  114669. defines.REFLECTIONMAP_EXPLICIT = false;
  114670. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  114671. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  114672. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  114673. defines.INVERTCUBICMAP = false;
  114674. defines.REFLECTIONMAP_OPPOSITEZ = false;
  114675. defines.LODINREFLECTIONALPHA = false;
  114676. defines.GAMMAREFLECTION = false;
  114677. defines.RGBDREFLECTION = false;
  114678. }
  114679. }
  114680. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  114681. defines.USERGBCOLOR = this._useRGBColor;
  114682. defines.NOISE = this._enableNoise;
  114683. }
  114684. if (defines._areLightsDirty) {
  114685. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  114686. }
  114687. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  114688. if (!this._imageProcessingConfiguration.isReady()) {
  114689. return false;
  114690. }
  114691. this._imageProcessingConfiguration.prepareDefines(defines);
  114692. }
  114693. // Misc.
  114694. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  114695. // Values that need to be evaluated on every frame
  114696. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  114697. // Attribs
  114698. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  114699. if (mesh) {
  114700. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  114701. mesh.createNormals(true);
  114702. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  114703. }
  114704. }
  114705. }
  114706. // Get correct effect
  114707. if (defines.isDirty) {
  114708. defines.markAsProcessed();
  114709. scene.resetCachedMaterial();
  114710. // Fallbacks
  114711. var fallbacks = new BABYLON.EffectFallbacks();
  114712. if (defines.FOG) {
  114713. fallbacks.addFallback(0, "FOG");
  114714. }
  114715. if (defines.POINTSIZE) {
  114716. fallbacks.addFallback(1, "POINTSIZE");
  114717. }
  114718. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  114719. if (defines.NUM_BONE_INFLUENCERS > 0) {
  114720. fallbacks.addCPUSkinningFallback(0, mesh);
  114721. }
  114722. //Attributes
  114723. var attribs = [BABYLON.VertexBuffer.PositionKind];
  114724. if (defines.NORMAL) {
  114725. attribs.push(BABYLON.VertexBuffer.NormalKind);
  114726. }
  114727. if (defines.UV1) {
  114728. attribs.push(BABYLON.VertexBuffer.UVKind);
  114729. }
  114730. if (defines.UV2) {
  114731. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  114732. }
  114733. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  114734. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  114735. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  114736. "vFogInfos", "vFogColor", "pointSize",
  114737. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "mBones",
  114738. "vPrimaryColor", "vPrimaryColorShadow",
  114739. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  114740. "shadowLevel", "alpha",
  114741. "vBackgroundCenter", "vReflectionControl",
  114742. "vDiffuseInfos", "diffuseMatrix",
  114743. ];
  114744. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  114745. var uniformBuffers = ["Material", "Scene"];
  114746. if (BABYLON.ImageProcessingConfiguration) {
  114747. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  114748. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  114749. }
  114750. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  114751. uniformsNames: uniforms,
  114752. uniformBuffersNames: uniformBuffers,
  114753. samplers: samplers,
  114754. defines: defines,
  114755. maxSimultaneousLights: this._maxSimultaneousLights
  114756. });
  114757. var onCompiled = function (effect) {
  114758. if (_this.onCompiled) {
  114759. _this.onCompiled(effect);
  114760. }
  114761. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  114762. };
  114763. var join = defines.toString();
  114764. subMesh.setEffect(scene.getEngine().createEffect("background", {
  114765. attributes: attribs,
  114766. uniformsNames: uniforms,
  114767. uniformBuffersNames: uniformBuffers,
  114768. samplers: samplers,
  114769. defines: join,
  114770. fallbacks: fallbacks,
  114771. onCompiled: onCompiled,
  114772. onError: this.onError,
  114773. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  114774. }, engine), defines);
  114775. this.buildUniformLayout();
  114776. }
  114777. if (!subMesh.effect || !subMesh.effect.isReady()) {
  114778. return false;
  114779. }
  114780. defines._renderId = scene.getRenderId();
  114781. this._wasPreviouslyReady = true;
  114782. return true;
  114783. };
  114784. /**
  114785. * Compute the primary color according to the chosen perceptual color.
  114786. */
  114787. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  114788. if (!this.__perceptualColor) {
  114789. return;
  114790. }
  114791. this._primaryColor.copyFrom(this.__perceptualColor);
  114792. // Revert gamma space.
  114793. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  114794. // Revert image processing configuration.
  114795. if (this._imageProcessingConfiguration) {
  114796. // Revert Exposure.
  114797. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  114798. }
  114799. this._computePrimaryColors();
  114800. };
  114801. /**
  114802. * Compute the highlights and shadow colors according to their chosen levels.
  114803. */
  114804. BackgroundMaterial.prototype._computePrimaryColors = function () {
  114805. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  114806. return;
  114807. }
  114808. // Find the highlight color based on the configuration.
  114809. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  114810. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  114811. // Find the shadow color based on the configuration.
  114812. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  114813. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  114814. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  114815. };
  114816. /**
  114817. * Build the uniform buffer used in the material.
  114818. */
  114819. BackgroundMaterial.prototype.buildUniformLayout = function () {
  114820. // Order is important !
  114821. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  114822. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  114823. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  114824. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  114825. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  114826. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  114827. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  114828. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  114829. this._uniformBuffer.addUniform("pointSize", 1);
  114830. this._uniformBuffer.addUniform("shadowLevel", 1);
  114831. this._uniformBuffer.addUniform("alpha", 1);
  114832. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  114833. this._uniformBuffer.addUniform("vReflectionControl", 4);
  114834. this._uniformBuffer.create();
  114835. };
  114836. /**
  114837. * Unbind the material.
  114838. */
  114839. BackgroundMaterial.prototype.unbind = function () {
  114840. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  114841. this._uniformBuffer.setTexture("diffuseSampler", null);
  114842. }
  114843. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  114844. this._uniformBuffer.setTexture("reflectionSampler", null);
  114845. }
  114846. _super.prototype.unbind.call(this);
  114847. };
  114848. /**
  114849. * Bind only the world matrix to the material.
  114850. * @param world The world matrix to bind.
  114851. */
  114852. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  114853. this._activeEffect.setMatrix("world", world);
  114854. };
  114855. /**
  114856. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  114857. * @param world The world matrix to bind.
  114858. * @param subMesh The submesh to bind for.
  114859. */
  114860. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  114861. var scene = this.getScene();
  114862. var defines = subMesh._materialDefines;
  114863. if (!defines) {
  114864. return;
  114865. }
  114866. var effect = subMesh.effect;
  114867. if (!effect) {
  114868. return;
  114869. }
  114870. this._activeEffect = effect;
  114871. // Matrices
  114872. this.bindOnlyWorldMatrix(world);
  114873. // Bones
  114874. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  114875. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  114876. if (mustRebind) {
  114877. this._uniformBuffer.bindToEffect(effect, "Material");
  114878. this.bindViewProjection(effect);
  114879. var reflectionTexture = this._reflectionTexture;
  114880. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  114881. // Texture uniforms
  114882. if (scene.texturesEnabled) {
  114883. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  114884. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  114885. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  114886. }
  114887. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  114888. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  114889. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  114890. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  114891. }
  114892. }
  114893. if (this.shadowLevel > 0) {
  114894. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  114895. }
  114896. this._uniformBuffer.updateFloat("alpha", this.alpha);
  114897. // Point size
  114898. if (this.pointsCloud) {
  114899. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  114900. }
  114901. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  114902. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  114903. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  114904. }
  114905. else {
  114906. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  114907. }
  114908. }
  114909. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  114910. // Textures
  114911. if (scene.texturesEnabled) {
  114912. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  114913. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  114914. }
  114915. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  114916. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  114917. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  114918. }
  114919. else if (!defines.REFLECTIONBLUR) {
  114920. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  114921. }
  114922. else {
  114923. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  114924. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  114925. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  114926. }
  114927. if (defines.REFLECTIONFRESNEL) {
  114928. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  114929. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  114930. }
  114931. }
  114932. }
  114933. // Clip plane
  114934. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  114935. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  114936. }
  114937. if (mustRebind || !this.isFrozen) {
  114938. if (scene.lightsEnabled) {
  114939. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  114940. }
  114941. // View
  114942. this.bindView(effect);
  114943. // Fog
  114944. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect, true);
  114945. // image processing
  114946. if (this._imageProcessingConfiguration) {
  114947. this._imageProcessingConfiguration.bind(this._activeEffect);
  114948. }
  114949. }
  114950. this._uniformBuffer.update();
  114951. this._afterBind(mesh, this._activeEffect);
  114952. };
  114953. /**
  114954. * Dispose the material.
  114955. * @param forceDisposeEffect Force disposal of the associated effect.
  114956. * @param forceDisposeTextures Force disposal of the associated textures.
  114957. */
  114958. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  114959. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  114960. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  114961. if (forceDisposeTextures) {
  114962. if (this.diffuseTexture) {
  114963. this.diffuseTexture.dispose();
  114964. }
  114965. if (this.reflectionTexture) {
  114966. this.reflectionTexture.dispose();
  114967. }
  114968. }
  114969. this._renderTargets.dispose();
  114970. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  114971. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  114972. }
  114973. _super.prototype.dispose.call(this, forceDisposeEffect);
  114974. };
  114975. /**
  114976. * Clones the material.
  114977. * @param name The cloned name.
  114978. * @returns The cloned material.
  114979. */
  114980. BackgroundMaterial.prototype.clone = function (name) {
  114981. var _this = this;
  114982. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  114983. };
  114984. /**
  114985. * Serializes the current material to its JSON representation.
  114986. * @returns The JSON representation.
  114987. */
  114988. BackgroundMaterial.prototype.serialize = function () {
  114989. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  114990. serializationObject.customType = "BABYLON.BackgroundMaterial";
  114991. return serializationObject;
  114992. };
  114993. /**
  114994. * Gets the class name of the material
  114995. * @returns "BackgroundMaterial"
  114996. */
  114997. BackgroundMaterial.prototype.getClassName = function () {
  114998. return "BackgroundMaterial";
  114999. };
  115000. /**
  115001. * Parse a JSON input to create back a background material.
  115002. * @param source The JSON data to parse
  115003. * @param scene The scene to create the parsed material in
  115004. * @param rootUrl The root url of the assets the material depends upon
  115005. * @returns the instantiated BackgroundMaterial.
  115006. */
  115007. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  115008. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  115009. };
  115010. /**
  115011. * Standard reflectance value at parallel view angle.
  115012. */
  115013. BackgroundMaterial.StandardReflectance0 = 0.05;
  115014. /**
  115015. * Standard reflectance value at grazing angle.
  115016. */
  115017. BackgroundMaterial.StandardReflectance90 = 0.5;
  115018. __decorate([
  115019. BABYLON.serializeAsColor3()
  115020. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  115021. __decorate([
  115022. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  115023. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  115024. __decorate([
  115025. BABYLON.serializeAsColor3()
  115026. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  115027. __decorate([
  115028. BABYLON.serialize()
  115029. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  115030. __decorate([
  115031. BABYLON.serialize()
  115032. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  115033. __decorate([
  115034. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  115035. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  115036. __decorate([
  115037. BABYLON.serializeAsTexture()
  115038. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  115039. __decorate([
  115040. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115041. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  115042. __decorate([
  115043. BABYLON.serialize()
  115044. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  115045. __decorate([
  115046. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115047. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  115048. __decorate([
  115049. BABYLON.serializeAsTexture()
  115050. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  115051. __decorate([
  115052. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115053. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  115054. __decorate([
  115055. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115056. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  115057. __decorate([
  115058. BABYLON.serialize()
  115059. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  115060. __decorate([
  115061. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115062. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  115063. __decorate([
  115064. BABYLON.serializeAsVector3()
  115065. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  115066. __decorate([
  115067. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115068. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  115069. __decorate([
  115070. BABYLON.serialize()
  115071. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  115072. __decorate([
  115073. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115074. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  115075. __decorate([
  115076. BABYLON.serialize()
  115077. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  115078. __decorate([
  115079. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115080. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  115081. __decorate([
  115082. BABYLON.serialize()
  115083. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  115084. __decorate([
  115085. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115086. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  115087. __decorate([
  115088. BABYLON.serialize()
  115089. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  115090. __decorate([
  115091. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115092. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  115093. __decorate([
  115094. BABYLON.serialize()
  115095. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  115096. __decorate([
  115097. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115098. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  115099. __decorate([
  115100. BABYLON.serialize()
  115101. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  115102. __decorate([
  115103. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115104. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  115105. __decorate([
  115106. BABYLON.serialize()
  115107. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  115108. __decorate([
  115109. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115110. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  115111. __decorate([
  115112. BABYLON.serialize()
  115113. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  115114. __decorate([
  115115. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115116. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  115117. __decorate([
  115118. BABYLON.serialize()
  115119. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  115120. __decorate([
  115121. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115122. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  115123. __decorate([
  115124. BABYLON.serializeAsImageProcessingConfiguration()
  115125. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  115126. return BackgroundMaterial;
  115127. }(BABYLON.PushMaterial));
  115128. BABYLON.BackgroundMaterial = BackgroundMaterial;
  115129. })(BABYLON || (BABYLON = {}));
  115130. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  115131. var __assign = (this && this.__assign) || function () {
  115132. __assign = Object.assign || function(t) {
  115133. for (var s, i = 1, n = arguments.length; i < n; i++) {
  115134. s = arguments[i];
  115135. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  115136. t[p] = s[p];
  115137. }
  115138. return t;
  115139. };
  115140. return __assign.apply(this, arguments);
  115141. };
  115142. var BABYLON;
  115143. (function (BABYLON) {
  115144. /**
  115145. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  115146. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  115147. * It also helps with the default setup of your imageProcessing configuration.
  115148. */
  115149. var EnvironmentHelper = /** @class */ (function () {
  115150. /**
  115151. * constructor
  115152. * @param options
  115153. * @param scene The scene to add the material to
  115154. */
  115155. function EnvironmentHelper(options, scene) {
  115156. var _this = this;
  115157. this._errorHandler = function (message, exception) {
  115158. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  115159. };
  115160. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  115161. this._scene = scene;
  115162. this.onErrorObservable = new BABYLON.Observable();
  115163. this._setupBackground();
  115164. this._setupImageProcessing();
  115165. }
  115166. /**
  115167. * Creates the default options for the helper.
  115168. */
  115169. EnvironmentHelper._getDefaultOptions = function () {
  115170. return {
  115171. createGround: true,
  115172. groundSize: 15,
  115173. groundTexture: this._groundTextureCDNUrl,
  115174. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  115175. groundOpacity: 0.9,
  115176. enableGroundShadow: true,
  115177. groundShadowLevel: 0.5,
  115178. enableGroundMirror: false,
  115179. groundMirrorSizeRatio: 0.3,
  115180. groundMirrorBlurKernel: 64,
  115181. groundMirrorAmount: 1,
  115182. groundMirrorFresnelWeight: 1,
  115183. groundMirrorFallOffDistance: 0,
  115184. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  115185. groundYBias: 0.00001,
  115186. createSkybox: true,
  115187. skyboxSize: 20,
  115188. skyboxTexture: this._skyboxTextureCDNUrl,
  115189. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  115190. backgroundYRotation: 0,
  115191. sizeAuto: true,
  115192. rootPosition: BABYLON.Vector3.Zero(),
  115193. setupImageProcessing: true,
  115194. environmentTexture: this._environmentTextureCDNUrl,
  115195. cameraExposure: 0.8,
  115196. cameraContrast: 1.2,
  115197. toneMappingEnabled: true,
  115198. };
  115199. };
  115200. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  115201. /**
  115202. * Gets the root mesh created by the helper.
  115203. */
  115204. get: function () {
  115205. return this._rootMesh;
  115206. },
  115207. enumerable: true,
  115208. configurable: true
  115209. });
  115210. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  115211. /**
  115212. * Gets the skybox created by the helper.
  115213. */
  115214. get: function () {
  115215. return this._skybox;
  115216. },
  115217. enumerable: true,
  115218. configurable: true
  115219. });
  115220. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  115221. /**
  115222. * Gets the skybox texture created by the helper.
  115223. */
  115224. get: function () {
  115225. return this._skyboxTexture;
  115226. },
  115227. enumerable: true,
  115228. configurable: true
  115229. });
  115230. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  115231. /**
  115232. * Gets the skybox material created by the helper.
  115233. */
  115234. get: function () {
  115235. return this._skyboxMaterial;
  115236. },
  115237. enumerable: true,
  115238. configurable: true
  115239. });
  115240. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  115241. /**
  115242. * Gets the ground mesh created by the helper.
  115243. */
  115244. get: function () {
  115245. return this._ground;
  115246. },
  115247. enumerable: true,
  115248. configurable: true
  115249. });
  115250. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  115251. /**
  115252. * Gets the ground texture created by the helper.
  115253. */
  115254. get: function () {
  115255. return this._groundTexture;
  115256. },
  115257. enumerable: true,
  115258. configurable: true
  115259. });
  115260. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  115261. /**
  115262. * Gets the ground mirror created by the helper.
  115263. */
  115264. get: function () {
  115265. return this._groundMirror;
  115266. },
  115267. enumerable: true,
  115268. configurable: true
  115269. });
  115270. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  115271. /**
  115272. * Gets the ground mirror render list to helps pushing the meshes
  115273. * you wish in the ground reflection.
  115274. */
  115275. get: function () {
  115276. if (this._groundMirror) {
  115277. return this._groundMirror.renderList;
  115278. }
  115279. return null;
  115280. },
  115281. enumerable: true,
  115282. configurable: true
  115283. });
  115284. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  115285. /**
  115286. * Gets the ground material created by the helper.
  115287. */
  115288. get: function () {
  115289. return this._groundMaterial;
  115290. },
  115291. enumerable: true,
  115292. configurable: true
  115293. });
  115294. /**
  115295. * Updates the background according to the new options
  115296. * @param options
  115297. */
  115298. EnvironmentHelper.prototype.updateOptions = function (options) {
  115299. var newOptions = __assign({}, this._options, options);
  115300. if (this._ground && !newOptions.createGround) {
  115301. this._ground.dispose();
  115302. this._ground = null;
  115303. }
  115304. if (this._groundMaterial && !newOptions.createGround) {
  115305. this._groundMaterial.dispose();
  115306. this._groundMaterial = null;
  115307. }
  115308. if (this._groundTexture) {
  115309. if (this._options.groundTexture != newOptions.groundTexture) {
  115310. this._groundTexture.dispose();
  115311. this._groundTexture = null;
  115312. }
  115313. }
  115314. if (this._skybox && !newOptions.createSkybox) {
  115315. this._skybox.dispose();
  115316. this._skybox = null;
  115317. }
  115318. if (this._skyboxMaterial && !newOptions.createSkybox) {
  115319. this._skyboxMaterial.dispose();
  115320. this._skyboxMaterial = null;
  115321. }
  115322. if (this._skyboxTexture) {
  115323. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  115324. this._skyboxTexture.dispose();
  115325. this._skyboxTexture = null;
  115326. }
  115327. }
  115328. if (this._groundMirror && !newOptions.enableGroundMirror) {
  115329. this._groundMirror.dispose();
  115330. this._groundMirror = null;
  115331. }
  115332. if (this._scene.environmentTexture) {
  115333. if (this._options.environmentTexture != newOptions.environmentTexture) {
  115334. this._scene.environmentTexture.dispose();
  115335. }
  115336. }
  115337. this._options = newOptions;
  115338. this._setupBackground();
  115339. this._setupImageProcessing();
  115340. };
  115341. /**
  115342. * Sets the primary color of all the available elements.
  115343. * @param color the main color to affect to the ground and the background
  115344. */
  115345. EnvironmentHelper.prototype.setMainColor = function (color) {
  115346. if (this.groundMaterial) {
  115347. this.groundMaterial.primaryColor = color;
  115348. }
  115349. if (this.skyboxMaterial) {
  115350. this.skyboxMaterial.primaryColor = color;
  115351. }
  115352. if (this.groundMirror) {
  115353. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  115354. }
  115355. };
  115356. /**
  115357. * Setup the image processing according to the specified options.
  115358. */
  115359. EnvironmentHelper.prototype._setupImageProcessing = function () {
  115360. if (this._options.setupImageProcessing) {
  115361. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  115362. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  115363. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  115364. this._setupEnvironmentTexture();
  115365. }
  115366. };
  115367. /**
  115368. * Setup the environment texture according to the specified options.
  115369. */
  115370. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  115371. if (this._scene.environmentTexture) {
  115372. return;
  115373. }
  115374. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  115375. this._scene.environmentTexture = this._options.environmentTexture;
  115376. return;
  115377. }
  115378. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  115379. this._scene.environmentTexture = environmentTexture;
  115380. };
  115381. /**
  115382. * Setup the background according to the specified options.
  115383. */
  115384. EnvironmentHelper.prototype._setupBackground = function () {
  115385. if (!this._rootMesh) {
  115386. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  115387. }
  115388. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  115389. var sceneSize = this._getSceneSize();
  115390. if (this._options.createGround) {
  115391. this._setupGround(sceneSize);
  115392. this._setupGroundMaterial();
  115393. this._setupGroundDiffuseTexture();
  115394. if (this._options.enableGroundMirror) {
  115395. this._setupGroundMirrorTexture(sceneSize);
  115396. }
  115397. this._setupMirrorInGroundMaterial();
  115398. }
  115399. if (this._options.createSkybox) {
  115400. this._setupSkybox(sceneSize);
  115401. this._setupSkyboxMaterial();
  115402. this._setupSkyboxReflectionTexture();
  115403. }
  115404. this._rootMesh.position.x = sceneSize.rootPosition.x;
  115405. this._rootMesh.position.z = sceneSize.rootPosition.z;
  115406. this._rootMesh.position.y = sceneSize.rootPosition.y;
  115407. };
  115408. /**
  115409. * Get the scene sizes according to the setup.
  115410. */
  115411. EnvironmentHelper.prototype._getSceneSize = function () {
  115412. var _this = this;
  115413. var groundSize = this._options.groundSize;
  115414. var skyboxSize = this._options.skyboxSize;
  115415. var rootPosition = this._options.rootPosition;
  115416. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  115417. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  115418. }
  115419. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  115420. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  115421. });
  115422. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  115423. if (this._options.sizeAuto) {
  115424. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  115425. this._scene.activeCamera.upperRadiusLimit) {
  115426. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  115427. skyboxSize = groundSize;
  115428. }
  115429. var sceneDiagonalLenght = sceneDiagonal.length();
  115430. if (sceneDiagonalLenght > groundSize) {
  115431. groundSize = sceneDiagonalLenght * 2;
  115432. skyboxSize = groundSize;
  115433. }
  115434. // 10 % bigger.
  115435. groundSize *= 1.1;
  115436. skyboxSize *= 1.5;
  115437. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  115438. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  115439. }
  115440. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  115441. };
  115442. /**
  115443. * Setup the ground according to the specified options.
  115444. */
  115445. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  115446. var _this = this;
  115447. if (!this._ground || this._ground.isDisposed()) {
  115448. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  115449. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  115450. this._ground.parent = this._rootMesh;
  115451. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  115452. }
  115453. this._ground.receiveShadows = this._options.enableGroundShadow;
  115454. };
  115455. /**
  115456. * Setup the ground material according to the specified options.
  115457. */
  115458. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  115459. if (!this._groundMaterial) {
  115460. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  115461. }
  115462. this._groundMaterial.alpha = this._options.groundOpacity;
  115463. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  115464. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  115465. this._groundMaterial.primaryColor = this._options.groundColor;
  115466. this._groundMaterial.useRGBColor = false;
  115467. this._groundMaterial.enableNoise = true;
  115468. if (this._ground) {
  115469. this._ground.material = this._groundMaterial;
  115470. }
  115471. };
  115472. /**
  115473. * Setup the ground diffuse texture according to the specified options.
  115474. */
  115475. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  115476. if (!this._groundMaterial) {
  115477. return;
  115478. }
  115479. if (this._groundTexture) {
  115480. return;
  115481. }
  115482. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  115483. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  115484. return;
  115485. }
  115486. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  115487. diffuseTexture.gammaSpace = false;
  115488. diffuseTexture.hasAlpha = true;
  115489. this._groundMaterial.diffuseTexture = diffuseTexture;
  115490. };
  115491. /**
  115492. * Setup the ground mirror texture according to the specified options.
  115493. */
  115494. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  115495. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  115496. if (!this._groundMirror) {
  115497. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  115498. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  115499. this._groundMirror.anisotropicFilteringLevel = 1;
  115500. this._groundMirror.wrapU = wrapping;
  115501. this._groundMirror.wrapV = wrapping;
  115502. this._groundMirror.gammaSpace = false;
  115503. if (this._groundMirror.renderList) {
  115504. for (var i = 0; i < this._scene.meshes.length; i++) {
  115505. var mesh = this._scene.meshes[i];
  115506. if (mesh !== this._ground &&
  115507. mesh !== this._skybox &&
  115508. mesh !== this._rootMesh) {
  115509. this._groundMirror.renderList.push(mesh);
  115510. }
  115511. }
  115512. }
  115513. }
  115514. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  115515. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  115516. };
  115517. /**
  115518. * Setup the ground to receive the mirror texture.
  115519. */
  115520. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  115521. if (this._groundMaterial) {
  115522. this._groundMaterial.reflectionTexture = this._groundMirror;
  115523. this._groundMaterial.reflectionFresnel = true;
  115524. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  115525. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  115526. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  115527. }
  115528. };
  115529. /**
  115530. * Setup the skybox according to the specified options.
  115531. */
  115532. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  115533. var _this = this;
  115534. if (!this._skybox || this._skybox.isDisposed()) {
  115535. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  115536. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  115537. }
  115538. this._skybox.parent = this._rootMesh;
  115539. };
  115540. /**
  115541. * Setup the skybox material according to the specified options.
  115542. */
  115543. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  115544. if (!this._skybox) {
  115545. return;
  115546. }
  115547. if (!this._skyboxMaterial) {
  115548. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  115549. }
  115550. this._skyboxMaterial.useRGBColor = false;
  115551. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  115552. this._skyboxMaterial.enableNoise = true;
  115553. this._skybox.material = this._skyboxMaterial;
  115554. };
  115555. /**
  115556. * Setup the skybox reflection texture according to the specified options.
  115557. */
  115558. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  115559. if (!this._skyboxMaterial) {
  115560. return;
  115561. }
  115562. if (this._skyboxTexture) {
  115563. return;
  115564. }
  115565. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  115566. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  115567. return;
  115568. }
  115569. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  115570. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  115571. this._skyboxTexture.gammaSpace = false;
  115572. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  115573. };
  115574. /**
  115575. * Dispose all the elements created by the Helper.
  115576. */
  115577. EnvironmentHelper.prototype.dispose = function () {
  115578. if (this._groundMaterial) {
  115579. this._groundMaterial.dispose(true, true);
  115580. }
  115581. if (this._skyboxMaterial) {
  115582. this._skyboxMaterial.dispose(true, true);
  115583. }
  115584. this._rootMesh.dispose(false);
  115585. };
  115586. /**
  115587. * Default ground texture URL.
  115588. */
  115589. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  115590. /**
  115591. * Default skybox texture URL.
  115592. */
  115593. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  115594. /**
  115595. * Default environment texture URL.
  115596. */
  115597. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
  115598. return EnvironmentHelper;
  115599. }());
  115600. BABYLON.EnvironmentHelper = EnvironmentHelper;
  115601. })(BABYLON || (BABYLON = {}));
  115602. //# sourceMappingURL=babylon.environmentHelper.js.map
  115603. var BABYLON;
  115604. (function (BABYLON) {
  115605. /** Internal class used to store shapes for emitters */
  115606. var ParticleSystemSetEmitterCreationOptions = /** @class */ (function () {
  115607. function ParticleSystemSetEmitterCreationOptions() {
  115608. }
  115609. return ParticleSystemSetEmitterCreationOptions;
  115610. }());
  115611. /**
  115612. * Represents a set of particle systems working together to create a specific effect
  115613. */
  115614. var ParticleSystemSet = /** @class */ (function () {
  115615. function ParticleSystemSet() {
  115616. /**
  115617. * Gets the particle system list
  115618. */
  115619. this.systems = new Array();
  115620. }
  115621. Object.defineProperty(ParticleSystemSet.prototype, "emitterNode", {
  115622. /**
  115623. * Gets the emitter node used with this set
  115624. */
  115625. get: function () {
  115626. return this._emitterNode;
  115627. },
  115628. enumerable: true,
  115629. configurable: true
  115630. });
  115631. /**
  115632. * Creates a new emitter mesh as a sphere
  115633. * @param options defines the options used to create the sphere
  115634. * @param renderingGroupId defines the renderingGroupId to use for the sphere
  115635. * @param scene defines the hosting scene
  115636. */
  115637. ParticleSystemSet.prototype.setEmitterAsSphere = function (options, renderingGroupId, scene) {
  115638. if (this._emitterNode) {
  115639. this._emitterNode.dispose();
  115640. }
  115641. this._emitterCreationOptions = {
  115642. kind: "Sphere",
  115643. options: options,
  115644. renderingGroupId: renderingGroupId
  115645. };
  115646. var emitterMesh = BABYLON.MeshBuilder.CreateSphere("emitterSphere", { diameter: options.diameter, segments: options.segments }, scene);
  115647. emitterMesh.renderingGroupId = renderingGroupId;
  115648. var material = new BABYLON.StandardMaterial("emitterSphereMaterial", scene);
  115649. material.emissiveColor = options.color;
  115650. emitterMesh.material = material;
  115651. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  115652. var system = _a[_i];
  115653. system.emitter = emitterMesh;
  115654. }
  115655. this._emitterNode = emitterMesh;
  115656. };
  115657. /**
  115658. * Starts all particle systems of the set
  115659. * @param emitter defines an optional mesh to use as emitter for the particle systems
  115660. */
  115661. ParticleSystemSet.prototype.start = function (emitter) {
  115662. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  115663. var system = _a[_i];
  115664. if (emitter) {
  115665. system.emitter = emitter;
  115666. }
  115667. system.start();
  115668. }
  115669. };
  115670. /**
  115671. * Release all associated resources
  115672. */
  115673. ParticleSystemSet.prototype.dispose = function () {
  115674. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  115675. var system = _a[_i];
  115676. system.dispose();
  115677. }
  115678. this.systems = [];
  115679. if (this._emitterNode) {
  115680. this._emitterNode.dispose();
  115681. this._emitterNode = null;
  115682. }
  115683. };
  115684. /**
  115685. * Serialize the set into a JSON compatible object
  115686. * @returns a JSON compatible representation of the set
  115687. */
  115688. ParticleSystemSet.prototype.serialize = function () {
  115689. var result = {};
  115690. result.systems = [];
  115691. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  115692. var system = _a[_i];
  115693. result.systems.push(system.serialize());
  115694. }
  115695. if (this._emitterNode) {
  115696. result.emitter = this._emitterCreationOptions;
  115697. }
  115698. return result;
  115699. };
  115700. /**
  115701. * Parse a new ParticleSystemSet from a serialized source
  115702. * @param data defines a JSON compatible representation of the set
  115703. * @param scene defines the hosting scene
  115704. * @param gpu defines if we want GPU particles or CPU particles
  115705. * @returns a new ParticleSystemSet
  115706. */
  115707. ParticleSystemSet.Parse = function (data, scene, gpu) {
  115708. if (gpu === void 0) { gpu = false; }
  115709. var result = new ParticleSystemSet();
  115710. var rootUrl = BABYLON.ParticleHelper.BaseAssetsUrl + "/textures/";
  115711. scene = scene || BABYLON.Engine.LastCreatedScene;
  115712. for (var _i = 0, _a = data.systems; _i < _a.length; _i++) {
  115713. var system = _a[_i];
  115714. result.systems.push(gpu ? BABYLON.GPUParticleSystem.Parse(system, scene, rootUrl, true) : BABYLON.ParticleSystem.Parse(system, scene, rootUrl, true));
  115715. }
  115716. if (data.emitter) {
  115717. var options = data.emitter.options;
  115718. switch (data.emitter.kind) {
  115719. case "Sphere":
  115720. result.setEmitterAsSphere({
  115721. diameter: options.diameter,
  115722. segments: options.segments,
  115723. color: BABYLON.Color3.FromArray(options.color)
  115724. }, data.emitter.renderingGroupId, scene);
  115725. break;
  115726. }
  115727. }
  115728. return result;
  115729. };
  115730. return ParticleSystemSet;
  115731. }());
  115732. BABYLON.ParticleSystemSet = ParticleSystemSet;
  115733. })(BABYLON || (BABYLON = {}));
  115734. //# sourceMappingURL=babylon.particleSystemSet.js.map
  115735. var BABYLON;
  115736. (function (BABYLON) {
  115737. /**
  115738. * This class is made for on one-liner static method to help creating particle system set.
  115739. */
  115740. var ParticleHelper = /** @class */ (function () {
  115741. function ParticleHelper() {
  115742. }
  115743. /**
  115744. * Create a default particle system that you can tweak
  115745. * @param emitter defines the emitter to use
  115746. * @param capacity defines the system capacity (default is 500 particles)
  115747. * @param scene defines the hosting scene
  115748. * @param useGPU defines if a GPUParticleSystem must be created (default is false)
  115749. * @returns the new Particle system
  115750. */
  115751. ParticleHelper.CreateDefault = function (emitter, capacity, scene, useGPU) {
  115752. if (capacity === void 0) { capacity = 500; }
  115753. if (useGPU === void 0) { useGPU = false; }
  115754. var system;
  115755. if (useGPU) {
  115756. system = new BABYLON.GPUParticleSystem("default system", { capacity: capacity }, scene);
  115757. }
  115758. else {
  115759. system = new BABYLON.ParticleSystem("default system", capacity, scene);
  115760. }
  115761. system.emitter = emitter;
  115762. system.particleTexture = new BABYLON.Texture("https://www.babylonjs.com/assets/Flare.png", system.getScene());
  115763. system.createConeEmitter(0.1, Math.PI / 4);
  115764. // Particle color
  115765. system.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  115766. system.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  115767. system.colorDead = new BABYLON.Color4(1.0, 1.0, 1.0, 0.0);
  115768. // Particle Size
  115769. system.minSize = 0.1;
  115770. system.maxSize = 0.1;
  115771. // Emission speed
  115772. system.minEmitPower = 2;
  115773. system.maxEmitPower = 2;
  115774. // Update speed
  115775. system.updateSpeed = 1 / 60;
  115776. system.emitRate = 30;
  115777. return system;
  115778. };
  115779. /**
  115780. * This is the main static method (one-liner) of this helper to create different particle systems
  115781. * @param type This string represents the type to the particle system to create
  115782. * @param scene The scene where the particle system should live
  115783. * @param gpu If the system will use gpu
  115784. * @returns the ParticleSystemSet created
  115785. */
  115786. ParticleHelper.CreateAsync = function (type, scene, gpu) {
  115787. if (gpu === void 0) { gpu = false; }
  115788. if (!scene) {
  115789. scene = BABYLON.Engine.LastCreatedScene;
  115790. ;
  115791. }
  115792. var token = {};
  115793. scene._addPendingData(token);
  115794. return new Promise(function (resolve, reject) {
  115795. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  115796. scene._removePendingData(token);
  115797. return reject("Particle system with GPU is not supported.");
  115798. }
  115799. BABYLON.Tools.LoadFile(ParticleHelper.BaseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  115800. scene._removePendingData(token);
  115801. var newData = JSON.parse(data.toString());
  115802. return resolve(BABYLON.ParticleSystemSet.Parse(newData, scene, gpu));
  115803. }, undefined, undefined, undefined, function (req, exception) {
  115804. scene._removePendingData(token);
  115805. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  115806. });
  115807. });
  115808. };
  115809. /**
  115810. * Static function used to export a particle system to a ParticleSystemSet variable.
  115811. * Please note that the emitter shape is not exported
  115812. * @param systems defines the particle systems to export
  115813. * @returns the created particle system set
  115814. */
  115815. ParticleHelper.ExportSet = function (systems) {
  115816. var set = new BABYLON.ParticleSystemSet();
  115817. for (var _i = 0, systems_1 = systems; _i < systems_1.length; _i++) {
  115818. var system = systems_1[_i];
  115819. set.systems.push(system);
  115820. }
  115821. return set;
  115822. };
  115823. /**
  115824. * Gets or sets base Assets URL
  115825. */
  115826. ParticleHelper.BaseAssetsUrl = "https://assets.babylonjs.com/particles";
  115827. return ParticleHelper;
  115828. }());
  115829. BABYLON.ParticleHelper = ParticleHelper;
  115830. })(BABYLON || (BABYLON = {}));
  115831. //# sourceMappingURL=babylon.particleHelper.js.map
  115832. var BABYLON;
  115833. (function (BABYLON) {
  115834. /**
  115835. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  115836. * As a subclass of TransformNode, this allow parenting to the camera or multiple videos with different locations in the scene.
  115837. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  115838. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  115839. */
  115840. var VideoDome = /** @class */ (function (_super) {
  115841. __extends(VideoDome, _super);
  115842. /**
  115843. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  115844. * @param name Element's name, child elements will append suffixes for their own names.
  115845. * @param urlsOrVideo defines the url(s) or the video element to use
  115846. * @param options An object containing optional or exposed sub element properties
  115847. */
  115848. function VideoDome(name, urlsOrVideo, options, scene) {
  115849. var _this = _super.call(this, name, scene) || this;
  115850. _this._useDirectMapping = false;
  115851. // set defaults and manage values
  115852. name = name || "videoDome";
  115853. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  115854. options.clickToPlay = Boolean(options.clickToPlay);
  115855. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  115856. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  115857. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  115858. if (options.useDirectMapping === undefined) {
  115859. _this._useDirectMapping = true;
  115860. }
  115861. else {
  115862. _this._useDirectMapping = options.useDirectMapping;
  115863. }
  115864. _this._setReady(false);
  115865. // create
  115866. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster };
  115867. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  115868. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, _this._useDirectMapping, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  115869. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  115870. texture.onLoadObservable.addOnce(function () {
  115871. _this._setReady(true);
  115872. });
  115873. // configure material
  115874. material.useEquirectangularFOV = true;
  115875. material.fovMultiplier = 1.0;
  115876. material.opacityFresnel = false;
  115877. if (_this._useDirectMapping) {
  115878. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  115879. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  115880. material.diffuseTexture = texture;
  115881. }
  115882. else {
  115883. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  115884. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  115885. material.reflectionTexture = texture;
  115886. }
  115887. // configure mesh
  115888. _this._mesh.material = material;
  115889. _this._mesh.parent = _this;
  115890. // optional configuration
  115891. if (options.clickToPlay) {
  115892. scene.onPointerUp = function () {
  115893. _this._videoTexture.video.play();
  115894. };
  115895. }
  115896. return _this;
  115897. }
  115898. Object.defineProperty(VideoDome.prototype, "videoTexture", {
  115899. /**
  115900. * Gets the video texture being displayed on the sphere
  115901. */
  115902. get: function () {
  115903. return this._videoTexture;
  115904. },
  115905. enumerable: true,
  115906. configurable: true
  115907. });
  115908. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  115909. /**
  115910. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  115911. * Also see the options.resolution property.
  115912. */
  115913. get: function () {
  115914. return this._material.fovMultiplier;
  115915. },
  115916. set: function (value) {
  115917. this._material.fovMultiplier = value;
  115918. },
  115919. enumerable: true,
  115920. configurable: true
  115921. });
  115922. /**
  115923. * Releases resources associated with this node.
  115924. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  115925. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  115926. */
  115927. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  115928. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  115929. this._videoTexture.dispose();
  115930. this._mesh.dispose();
  115931. this._material.dispose();
  115932. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  115933. };
  115934. return VideoDome;
  115935. }(BABYLON.TransformNode));
  115936. BABYLON.VideoDome = VideoDome;
  115937. })(BABYLON || (BABYLON = {}));
  115938. //# sourceMappingURL=babylon.videoDome.js.map
  115939. var BABYLON;
  115940. (function (BABYLON) {
  115941. /**
  115942. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  115943. * As a subclass of TransformNode, this allow parenting to the camera with different locations in the scene.
  115944. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  115945. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  115946. */
  115947. var PhotoDome = /** @class */ (function (_super) {
  115948. __extends(PhotoDome, _super);
  115949. /**
  115950. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  115951. * @param name Element's name, child elements will append suffixes for their own names.
  115952. * @param urlsOfPhoto defines the url of the photo to display
  115953. * @param options defines an object containing optional or exposed sub element properties
  115954. * @param onError defines a callback called when an error occured while loading the texture
  115955. */
  115956. function PhotoDome(name, urlOfPhoto, options, scene, onError) {
  115957. if (onError === void 0) { onError = null; }
  115958. var _this = _super.call(this, name, scene) || this;
  115959. _this._useDirectMapping = false;
  115960. /**
  115961. * Observable raised when an error occured while loading the 360 image
  115962. */
  115963. _this.onLoadErrorObservable = new BABYLON.Observable();
  115964. // set defaults and manage values
  115965. name = name || "photoDome";
  115966. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  115967. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  115968. if (options.useDirectMapping === undefined) {
  115969. _this._useDirectMapping = true;
  115970. }
  115971. else {
  115972. _this._useDirectMapping = options.useDirectMapping;
  115973. }
  115974. _this._setReady(false);
  115975. // create
  115976. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  115977. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  115978. // configure material
  115979. material.opacityFresnel = false;
  115980. material.useEquirectangularFOV = true;
  115981. material.fovMultiplier = 1.0;
  115982. _this.photoTexture = new BABYLON.Texture(urlOfPhoto, scene, true, !_this._useDirectMapping, undefined, undefined, function (message, exception) {
  115983. _this.onLoadErrorObservable.notifyObservers(message || "Unknown error occured");
  115984. if (onError) {
  115985. onError(message, exception);
  115986. }
  115987. });
  115988. _this.photoTexture.onLoadObservable.addOnce(function () {
  115989. _this._setReady(true);
  115990. });
  115991. // configure mesh
  115992. _this._mesh.material = material;
  115993. _this._mesh.parent = _this;
  115994. return _this;
  115995. }
  115996. Object.defineProperty(PhotoDome.prototype, "photoTexture", {
  115997. /**
  115998. * Gets or sets the texture being displayed on the sphere
  115999. */
  116000. get: function () {
  116001. return this._photoTexture;
  116002. },
  116003. set: function (value) {
  116004. if (this._photoTexture === value) {
  116005. return;
  116006. }
  116007. this._photoTexture = value;
  116008. if (this._useDirectMapping) {
  116009. this._photoTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  116010. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  116011. this._material.diffuseTexture = this._photoTexture;
  116012. }
  116013. else {
  116014. this._photoTexture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  116015. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  116016. this._material.reflectionTexture = this._photoTexture;
  116017. }
  116018. },
  116019. enumerable: true,
  116020. configurable: true
  116021. });
  116022. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  116023. /**
  116024. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  116025. * Also see the options.resolution property.
  116026. */
  116027. get: function () {
  116028. return this._material.fovMultiplier;
  116029. },
  116030. set: function (value) {
  116031. this._material.fovMultiplier = value;
  116032. },
  116033. enumerable: true,
  116034. configurable: true
  116035. });
  116036. /**
  116037. * Releases resources associated with this node.
  116038. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  116039. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  116040. */
  116041. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  116042. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  116043. this._photoTexture.dispose();
  116044. this._mesh.dispose();
  116045. this._material.dispose();
  116046. this.onLoadErrorObservable.clear();
  116047. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  116048. };
  116049. return PhotoDome;
  116050. }(BABYLON.TransformNode));
  116051. BABYLON.PhotoDome = PhotoDome;
  116052. })(BABYLON || (BABYLON = {}));
  116053. //# sourceMappingURL=babylon.photoDome.js.map
  116054. var BABYLON;
  116055. (function (BABYLON) {
  116056. /** @hidden */
  116057. var _OcclusionDataStorage = /** @class */ (function () {
  116058. function _OcclusionDataStorage() {
  116059. /** @hidden */
  116060. this.occlusionInternalRetryCounter = 0;
  116061. /** @hidden */
  116062. this.isOcclusionQueryInProgress = false;
  116063. /** @hidden */
  116064. this.isOccluded = false;
  116065. /** @hidden */
  116066. this.occlusionRetryCount = -1;
  116067. /** @hidden */
  116068. this.occlusionType = BABYLON.AbstractMesh.OCCLUSION_TYPE_NONE;
  116069. /** @hidden */
  116070. this.occlusionQueryAlgorithmType = BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  116071. }
  116072. return _OcclusionDataStorage;
  116073. }());
  116074. BABYLON.Engine.prototype.createQuery = function () {
  116075. return this._gl.createQuery();
  116076. };
  116077. BABYLON.Engine.prototype.deleteQuery = function (query) {
  116078. this._gl.deleteQuery(query);
  116079. return this;
  116080. };
  116081. BABYLON.Engine.prototype.isQueryResultAvailable = function (query) {
  116082. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  116083. };
  116084. BABYLON.Engine.prototype.getQueryResult = function (query) {
  116085. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  116086. };
  116087. BABYLON.Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  116088. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  116089. this._gl.beginQuery(glAlgorithm, query);
  116090. return this;
  116091. };
  116092. BABYLON.Engine.prototype.endOcclusionQuery = function (algorithmType) {
  116093. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  116094. this._gl.endQuery(glAlgorithm);
  116095. return this;
  116096. };
  116097. BABYLON.Engine.prototype._createTimeQuery = function () {
  116098. var timerQuery = this.getCaps().timerQuery;
  116099. if (timerQuery.createQueryEXT) {
  116100. return timerQuery.createQueryEXT();
  116101. }
  116102. return this.createQuery();
  116103. };
  116104. BABYLON.Engine.prototype._deleteTimeQuery = function (query) {
  116105. var timerQuery = this.getCaps().timerQuery;
  116106. if (timerQuery.deleteQueryEXT) {
  116107. timerQuery.deleteQueryEXT(query);
  116108. return;
  116109. }
  116110. this.deleteQuery(query);
  116111. };
  116112. BABYLON.Engine.prototype._getTimeQueryResult = function (query) {
  116113. var timerQuery = this.getCaps().timerQuery;
  116114. if (timerQuery.getQueryObjectEXT) {
  116115. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  116116. }
  116117. return this.getQueryResult(query);
  116118. };
  116119. BABYLON.Engine.prototype._getTimeQueryAvailability = function (query) {
  116120. var timerQuery = this.getCaps().timerQuery;
  116121. if (timerQuery.getQueryObjectEXT) {
  116122. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  116123. }
  116124. return this.isQueryResultAvailable(query);
  116125. };
  116126. BABYLON.Engine.prototype.startTimeQuery = function () {
  116127. var caps = this.getCaps();
  116128. var timerQuery = caps.timerQuery;
  116129. if (!timerQuery) {
  116130. return null;
  116131. }
  116132. var token = new BABYLON._TimeToken();
  116133. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  116134. if (caps.canUseTimestampForTimerQuery) {
  116135. token._startTimeQuery = this._createTimeQuery();
  116136. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  116137. }
  116138. else {
  116139. if (this._currentNonTimestampToken) {
  116140. return this._currentNonTimestampToken;
  116141. }
  116142. token._timeElapsedQuery = this._createTimeQuery();
  116143. if (timerQuery.beginQueryEXT) {
  116144. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  116145. }
  116146. else {
  116147. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  116148. }
  116149. this._currentNonTimestampToken = token;
  116150. }
  116151. return token;
  116152. };
  116153. BABYLON.Engine.prototype.endTimeQuery = function (token) {
  116154. var caps = this.getCaps();
  116155. var timerQuery = caps.timerQuery;
  116156. if (!timerQuery || !token) {
  116157. return -1;
  116158. }
  116159. if (caps.canUseTimestampForTimerQuery) {
  116160. if (!token._startTimeQuery) {
  116161. return -1;
  116162. }
  116163. if (!token._endTimeQuery) {
  116164. token._endTimeQuery = this._createTimeQuery();
  116165. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  116166. }
  116167. }
  116168. else if (!token._timeElapsedQueryEnded) {
  116169. if (!token._timeElapsedQuery) {
  116170. return -1;
  116171. }
  116172. if (timerQuery.endQueryEXT) {
  116173. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  116174. }
  116175. else {
  116176. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  116177. }
  116178. token._timeElapsedQueryEnded = true;
  116179. }
  116180. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  116181. var available = false;
  116182. if (token._endTimeQuery) {
  116183. available = this._getTimeQueryAvailability(token._endTimeQuery);
  116184. }
  116185. else if (token._timeElapsedQuery) {
  116186. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  116187. }
  116188. if (available && !disjoint) {
  116189. var result = 0;
  116190. if (caps.canUseTimestampForTimerQuery) {
  116191. if (!token._startTimeQuery || !token._endTimeQuery) {
  116192. return -1;
  116193. }
  116194. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  116195. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  116196. result = timeEnd - timeStart;
  116197. this._deleteTimeQuery(token._startTimeQuery);
  116198. this._deleteTimeQuery(token._endTimeQuery);
  116199. token._startTimeQuery = null;
  116200. token._endTimeQuery = null;
  116201. }
  116202. else {
  116203. if (!token._timeElapsedQuery) {
  116204. return -1;
  116205. }
  116206. result = this._getTimeQueryResult(token._timeElapsedQuery);
  116207. this._deleteTimeQuery(token._timeElapsedQuery);
  116208. token._timeElapsedQuery = null;
  116209. token._timeElapsedQueryEnded = false;
  116210. this._currentNonTimestampToken = null;
  116211. }
  116212. return result;
  116213. }
  116214. return -1;
  116215. };
  116216. BABYLON.Engine.prototype._getGlAlgorithmType = function (algorithmType) {
  116217. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  116218. };
  116219. Object.defineProperty(BABYLON.AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  116220. get: function () {
  116221. return this._occlusionDataStorage.isOcclusionQueryInProgress;
  116222. },
  116223. enumerable: false,
  116224. configurable: true
  116225. });
  116226. Object.defineProperty(BABYLON.AbstractMesh.prototype, "_occlusionDataStorage", {
  116227. get: function () {
  116228. if (!this.__occlusionDataStorage) {
  116229. this.__occlusionDataStorage = new _OcclusionDataStorage();
  116230. }
  116231. return this.__occlusionDataStorage;
  116232. },
  116233. enumerable: false,
  116234. configurable: true
  116235. });
  116236. Object.defineProperty(BABYLON.AbstractMesh.prototype, "isOccluded", {
  116237. get: function () {
  116238. return this._occlusionDataStorage.isOccluded;
  116239. },
  116240. set: function (value) {
  116241. this._occlusionDataStorage.isOccluded = value;
  116242. },
  116243. enumerable: true,
  116244. configurable: true
  116245. });
  116246. Object.defineProperty(BABYLON.AbstractMesh.prototype, "occlusionQueryAlgorithmType", {
  116247. get: function () {
  116248. return this._occlusionDataStorage.occlusionQueryAlgorithmType;
  116249. },
  116250. set: function (value) {
  116251. this._occlusionDataStorage.occlusionQueryAlgorithmType = value;
  116252. },
  116253. enumerable: true,
  116254. configurable: true
  116255. });
  116256. Object.defineProperty(BABYLON.AbstractMesh.prototype, "occlusionType", {
  116257. get: function () {
  116258. return this._occlusionDataStorage.occlusionType;
  116259. },
  116260. set: function (value) {
  116261. this._occlusionDataStorage.occlusionType = value;
  116262. },
  116263. enumerable: true,
  116264. configurable: true
  116265. });
  116266. Object.defineProperty(BABYLON.AbstractMesh.prototype, "occlusionRetryCount", {
  116267. get: function () {
  116268. return this._occlusionDataStorage.occlusionRetryCount;
  116269. },
  116270. set: function (value) {
  116271. this._occlusionDataStorage.occlusionRetryCount = value;
  116272. },
  116273. enumerable: true,
  116274. configurable: true
  116275. });
  116276. // We also need to update AbstractMesh as there is a portion of the code there
  116277. BABYLON.AbstractMesh.prototype._checkOcclusionQuery = function () {
  116278. var dataStorage = this._occlusionDataStorage;
  116279. if (dataStorage.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_NONE) {
  116280. dataStorage.isOccluded = false;
  116281. return false;
  116282. }
  116283. var engine = this.getEngine();
  116284. if (engine.webGLVersion < 2) {
  116285. dataStorage.isOccluded = false;
  116286. return false;
  116287. }
  116288. if (!engine.isQueryResultAvailable) { // Occlusion query where not referenced
  116289. dataStorage.isOccluded = false;
  116290. return false;
  116291. }
  116292. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  116293. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  116294. if (isOcclusionQueryAvailable) {
  116295. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  116296. dataStorage.isOcclusionQueryInProgress = false;
  116297. dataStorage.occlusionInternalRetryCounter = 0;
  116298. dataStorage.isOccluded = occlusionQueryResult === 1 ? false : true;
  116299. }
  116300. else {
  116301. dataStorage.occlusionInternalRetryCounter++;
  116302. if (dataStorage.occlusionRetryCount !== -1 && dataStorage.occlusionInternalRetryCounter > dataStorage.occlusionRetryCount) {
  116303. dataStorage.isOcclusionQueryInProgress = false;
  116304. dataStorage.occlusionInternalRetryCounter = 0;
  116305. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  116306. // if strict continue the last state of the object.
  116307. dataStorage.isOccluded = dataStorage.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : dataStorage.isOccluded;
  116308. }
  116309. else {
  116310. return false;
  116311. }
  116312. }
  116313. }
  116314. var scene = this.getScene();
  116315. if (scene.getBoundingBoxRenderer) {
  116316. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  116317. if (!this._occlusionQuery) {
  116318. this._occlusionQuery = engine.createQuery();
  116319. }
  116320. engine.beginOcclusionQuery(dataStorage.occlusionQueryAlgorithmType, this._occlusionQuery);
  116321. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  116322. engine.endOcclusionQuery(dataStorage.occlusionQueryAlgorithmType);
  116323. this._occlusionDataStorage.isOcclusionQueryInProgress = true;
  116324. }
  116325. return dataStorage.isOccluded;
  116326. };
  116327. })(BABYLON || (BABYLON = {}));
  116328. //# sourceMappingURL=babylon.engine.occlusionQuery.js.map
  116329. var BABYLON;
  116330. (function (BABYLON) {
  116331. /**
  116332. * Class used to generate noise procedural textures
  116333. */
  116334. var NoiseProceduralTexture = /** @class */ (function (_super) {
  116335. __extends(NoiseProceduralTexture, _super);
  116336. /**
  116337. * Creates a new NoiseProceduralTexture
  116338. * @param name defines the name fo the texture
  116339. * @param size defines the size of the texture (default is 256)
  116340. * @param scene defines the hosting scene
  116341. * @param fallbackTexture defines the texture to use if the NoiseProceduralTexture can't be created
  116342. * @param generateMipMaps defines if mipmaps must be generated (true by default)
  116343. */
  116344. function NoiseProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  116345. if (size === void 0) { size = 256; }
  116346. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  116347. var _this = _super.call(this, name, size, "noise", scene, fallbackTexture, generateMipMaps) || this;
  116348. _this._time = 0;
  116349. /** Gets or sets a value between 0 and 1 indicating the overall brightness of the texture (default is 0.2) */
  116350. _this.brightness = 0.2;
  116351. /** Defines the number of octaves to process */
  116352. _this.octaves = 3;
  116353. /** Defines the level of persistence (0.8 by default) */
  116354. _this.persistence = 0.8;
  116355. /** Gets or sets animation speed factor (default is 1) */
  116356. _this.animationSpeedFactor = 1;
  116357. _this._updateShaderUniforms();
  116358. return _this;
  116359. }
  116360. NoiseProceduralTexture.prototype._updateShaderUniforms = function () {
  116361. var scene = this.getScene();
  116362. if (!scene) {
  116363. return;
  116364. }
  116365. this._time += scene.getAnimationRatio() * this.animationSpeedFactor * 0.01;
  116366. this.setFloat("brightness", this.brightness);
  116367. this.setFloat("persistence", this.persistence);
  116368. this.setFloat("timeScale", this._time);
  116369. };
  116370. NoiseProceduralTexture.prototype._getDefines = function () {
  116371. return "#define OCTAVES " + (this.octaves | 0);
  116372. };
  116373. /** Generate the current state of the procedural texture */
  116374. NoiseProceduralTexture.prototype.render = function (useCameraPostProcess) {
  116375. this._updateShaderUniforms();
  116376. _super.prototype.render.call(this, useCameraPostProcess);
  116377. };
  116378. /**
  116379. * Serializes this noise procedural texture
  116380. * @returns a serialized noise procedural texture object
  116381. */
  116382. NoiseProceduralTexture.prototype.serialize = function () {
  116383. var serializationObject = {};
  116384. serializationObject.customType = "BABYLON.NoiseProceduralTexture";
  116385. serializationObject.brightness = this.brightness;
  116386. serializationObject.octaves = this.octaves;
  116387. serializationObject.persistence = this.persistence;
  116388. serializationObject.animationSpeedFactor = this.animationSpeedFactor;
  116389. serializationObject.size = this.getSize().width;
  116390. serializationObject.generateMipMaps = this._generateMipMaps;
  116391. return serializationObject;
  116392. };
  116393. /**
  116394. * Creates a NoiseProceduralTexture from parsed noise procedural texture data
  116395. * @param parsedTexture defines parsed texture data
  116396. * @param scene defines the current scene
  116397. * @param rootUrl defines the root URL containing noise procedural texture information
  116398. * @returns a parsed NoiseProceduralTexture
  116399. */
  116400. NoiseProceduralTexture.Parse = function (parsedTexture, scene, rootUrl) {
  116401. var texture = new NoiseProceduralTexture(parsedTexture.name, parsedTexture.size, scene, undefined, parsedTexture.generateMipMaps);
  116402. texture.brightness = parsedTexture.brightness;
  116403. texture.octaves = parsedTexture.octaves;
  116404. texture.persistence = parsedTexture.persistence;
  116405. texture.animationSpeedFactor = parsedTexture.animationSpeedFactor;
  116406. return texture;
  116407. };
  116408. return NoiseProceduralTexture;
  116409. }(BABYLON.ProceduralTexture));
  116410. BABYLON.NoiseProceduralTexture = NoiseProceduralTexture;
  116411. })(BABYLON || (BABYLON = {}));
  116412. //# sourceMappingURL=babylon.noiseProceduralTexture.js.map
  116413. var __assign = (this && this.__assign) || function () {
  116414. __assign = Object.assign || function(t) {
  116415. for (var s, i = 1, n = arguments.length; i < n; i++) {
  116416. s = arguments[i];
  116417. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  116418. t[p] = s[p];
  116419. }
  116420. return t;
  116421. };
  116422. return __assign.apply(this, arguments);
  116423. };
  116424. var BABYLON;
  116425. (function (BABYLON) {
  116426. /**
  116427. * This can helps recording videos from BabylonJS.
  116428. * This is based on the available WebRTC functionalities of the browser.
  116429. *
  116430. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_video
  116431. */
  116432. var VideoRecorder = /** @class */ (function () {
  116433. /**
  116434. * Create a new VideoCapture object which can help converting what you see in Babylon to
  116435. * a video file.
  116436. * @param engine Defines the BabylonJS Engine you wish to record
  116437. * @param options Defines options that can be used to customized the capture
  116438. */
  116439. function VideoRecorder(engine, options) {
  116440. if (options === void 0) { options = null; }
  116441. if (!VideoRecorder.IsSupported(engine)) {
  116442. throw "Your browser does not support recording so far.";
  116443. }
  116444. var canvas = engine.getRenderingCanvas();
  116445. if (!canvas) {
  116446. throw "The babylon engine must have a canvas to be recorded";
  116447. }
  116448. this._canvas = canvas;
  116449. this._canvas.isRecording = false;
  116450. this._options = __assign({}, VideoRecorder._defaultOptions, options);
  116451. var stream = this._canvas.captureStream(this._options.fps);
  116452. this._mediaRecorder = new MediaRecorder(stream, { mimeType: this._options.mimeType });
  116453. this._mediaRecorder.ondataavailable = this._handleDataAvailable.bind(this);
  116454. this._mediaRecorder.onerror = this._handleError.bind(this);
  116455. this._mediaRecorder.onstop = this._handleStop.bind(this);
  116456. }
  116457. /**
  116458. * Returns wehther or not the VideoRecorder is available in your browser.
  116459. * @param engine Defines the Babylon Engine to check the support for
  116460. * @returns true if supported otherwise false
  116461. */
  116462. VideoRecorder.IsSupported = function (engine) {
  116463. var canvas = engine.getRenderingCanvas();
  116464. return (!!canvas && typeof canvas.captureStream === "function");
  116465. };
  116466. Object.defineProperty(VideoRecorder.prototype, "isRecording", {
  116467. /**
  116468. * True wether a recording is already in progress.
  116469. */
  116470. get: function () {
  116471. return !!this._canvas && this._canvas.isRecording;
  116472. },
  116473. enumerable: true,
  116474. configurable: true
  116475. });
  116476. /**
  116477. * Stops the current recording before the default capture timeout passed in the startRecording
  116478. * functions.
  116479. */
  116480. VideoRecorder.prototype.stopRecording = function () {
  116481. if (!this._canvas || !this._mediaRecorder) {
  116482. return;
  116483. }
  116484. if (!this.isRecording) {
  116485. return;
  116486. }
  116487. this._canvas.isRecording = false;
  116488. this._mediaRecorder.stop();
  116489. };
  116490. /**
  116491. * Starts recording the canvas for a max duration specified in parameters.
  116492. * @param fileName Defines the name of the file to be downloaded when the recording stop. If null no automatic download will start and you can rely on the promise to get the data back.
  116493. * @param maxDuration Defines the maximum recording time in seconds.
  116494. * It default to 7 seconds. A value of zero will not stop automatically, you would need to call stopRecording manually.
  116495. * @return a promise callback at the end of the recording with the video data in Blob.
  116496. */
  116497. VideoRecorder.prototype.startRecording = function (fileName, maxDuration) {
  116498. var _this = this;
  116499. if (fileName === void 0) { fileName = "babylonjs.webm"; }
  116500. if (maxDuration === void 0) { maxDuration = 7; }
  116501. if (!this._canvas || !this._mediaRecorder) {
  116502. throw "Recorder has already been disposed";
  116503. }
  116504. if (this.isRecording) {
  116505. throw "Recording already in progress";
  116506. }
  116507. if (maxDuration > 0) {
  116508. setTimeout(function () {
  116509. _this.stopRecording();
  116510. }, maxDuration * 1000);
  116511. }
  116512. this._fileName = fileName;
  116513. this._recordedChunks = [];
  116514. this._resolve = null;
  116515. this._reject = null;
  116516. this._canvas.isRecording = true;
  116517. this._mediaRecorder.start(this._options.recordChunckSize);
  116518. return new Promise(function (resolve, reject) {
  116519. _this._resolve = resolve;
  116520. _this._reject = reject;
  116521. });
  116522. };
  116523. /**
  116524. * Releases internal resources used during the recording.
  116525. */
  116526. VideoRecorder.prototype.dispose = function () {
  116527. this._canvas = null;
  116528. this._mediaRecorder = null;
  116529. this._recordedChunks = [];
  116530. this._fileName = null;
  116531. this._resolve = null;
  116532. this._reject = null;
  116533. };
  116534. VideoRecorder.prototype._handleDataAvailable = function (event) {
  116535. if (event.data.size > 0) {
  116536. this._recordedChunks.push(event.data);
  116537. }
  116538. };
  116539. VideoRecorder.prototype._handleError = function (event) {
  116540. this.stopRecording();
  116541. if (this._reject) {
  116542. this._reject(event.error);
  116543. }
  116544. else {
  116545. throw new event.error;
  116546. }
  116547. };
  116548. VideoRecorder.prototype._handleStop = function () {
  116549. this.stopRecording();
  116550. var superBuffer = new Blob(this._recordedChunks);
  116551. if (this._resolve) {
  116552. this._resolve(superBuffer);
  116553. }
  116554. window.URL.createObjectURL(superBuffer);
  116555. if (this._fileName) {
  116556. BABYLON.Tools.Download(superBuffer, this._fileName);
  116557. }
  116558. };
  116559. VideoRecorder._defaultOptions = {
  116560. mimeType: "video/webm",
  116561. fps: 25,
  116562. recordChunckSize: 3000
  116563. };
  116564. return VideoRecorder;
  116565. }());
  116566. BABYLON.VideoRecorder = VideoRecorder;
  116567. })(BABYLON || (BABYLON = {}));
  116568. //# sourceMappingURL=babylon.videoRecorder.js.map
  116569. var BABYLON;
  116570. (function (BABYLON) {
  116571. BABYLON.Scene.prototype.createDefaultLight = function (replace) {
  116572. if (replace === void 0) { replace = false; }
  116573. // Dispose existing light in replace mode.
  116574. if (replace) {
  116575. if (this.lights) {
  116576. for (var i = 0; i < this.lights.length; i++) {
  116577. this.lights[i].dispose();
  116578. }
  116579. }
  116580. }
  116581. // Light
  116582. if (this.lights.length === 0) {
  116583. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  116584. }
  116585. };
  116586. BABYLON.Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  116587. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  116588. if (replace === void 0) { replace = false; }
  116589. if (attachCameraControls === void 0) { attachCameraControls = false; }
  116590. // Dispose existing camera in replace mode.
  116591. if (replace) {
  116592. if (this.activeCamera) {
  116593. this.activeCamera.dispose();
  116594. this.activeCamera = null;
  116595. }
  116596. }
  116597. // Camera
  116598. if (!this.activeCamera) {
  116599. var worldExtends = this.getWorldExtends();
  116600. var worldSize = worldExtends.max.subtract(worldExtends.min);
  116601. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  116602. var camera;
  116603. var radius = worldSize.length() * 1.5;
  116604. // empty scene scenario!
  116605. if (!isFinite(radius)) {
  116606. radius = 1;
  116607. worldCenter.copyFromFloats(0, 0, 0);
  116608. }
  116609. if (createArcRotateCamera) {
  116610. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  116611. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  116612. arcRotateCamera.wheelPrecision = 100 / radius;
  116613. camera = arcRotateCamera;
  116614. }
  116615. else {
  116616. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  116617. freeCamera.setTarget(worldCenter);
  116618. camera = freeCamera;
  116619. }
  116620. camera.minZ = radius * 0.01;
  116621. camera.maxZ = radius * 1000;
  116622. camera.speed = radius * 0.2;
  116623. this.activeCamera = camera;
  116624. var canvas = this.getEngine().getRenderingCanvas();
  116625. if (attachCameraControls && canvas) {
  116626. camera.attachControl(canvas);
  116627. }
  116628. }
  116629. };
  116630. BABYLON.Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  116631. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  116632. if (replace === void 0) { replace = false; }
  116633. if (attachCameraControls === void 0) { attachCameraControls = false; }
  116634. this.createDefaultLight(replace);
  116635. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  116636. };
  116637. BABYLON.Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  116638. if (pbr === void 0) { pbr = false; }
  116639. if (scale === void 0) { scale = 1000; }
  116640. if (blur === void 0) { blur = 0; }
  116641. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  116642. if (!environmentTexture) {
  116643. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  116644. return null;
  116645. }
  116646. if (setGlobalEnvTexture) {
  116647. if (environmentTexture) {
  116648. this.environmentTexture = environmentTexture;
  116649. }
  116650. }
  116651. // Skybox
  116652. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  116653. if (pbr) {
  116654. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  116655. hdrSkyboxMaterial.backFaceCulling = false;
  116656. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  116657. if (hdrSkyboxMaterial.reflectionTexture) {
  116658. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  116659. }
  116660. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  116661. hdrSkyboxMaterial.disableLighting = true;
  116662. hdrSkyboxMaterial.twoSidedLighting = true;
  116663. hdrSkybox.infiniteDistance = true;
  116664. hdrSkybox.material = hdrSkyboxMaterial;
  116665. }
  116666. else {
  116667. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  116668. skyboxMaterial.backFaceCulling = false;
  116669. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  116670. if (skyboxMaterial.reflectionTexture) {
  116671. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  116672. }
  116673. skyboxMaterial.disableLighting = true;
  116674. hdrSkybox.infiniteDistance = true;
  116675. hdrSkybox.material = skyboxMaterial;
  116676. }
  116677. return hdrSkybox;
  116678. };
  116679. BABYLON.Scene.prototype.createDefaultEnvironment = function (options) {
  116680. if (BABYLON.EnvironmentHelper) {
  116681. return new BABYLON.EnvironmentHelper(options, this);
  116682. }
  116683. return null;
  116684. };
  116685. BABYLON.Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  116686. if (webVROptions === void 0) { webVROptions = {}; }
  116687. return new BABYLON.VRExperienceHelper(this, webVROptions);
  116688. };
  116689. })(BABYLON || (BABYLON = {}));
  116690. //# sourceMappingURL=babylon.sceneHelpers.js.map
  116691. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\n#ifdef REFLECTIONMAP_SKYBOX_TRANSFORMED\nvPositionUVW=(reflectionMatrix*vec4(position,1.0)).xyz;\n#else\nvPositionUVW=position;\n#endif\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n#ifdef ALPHATEST\nuniform float alphaCutOff;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<alphaCutOff)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0) {\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb;\n#endif\n#ifdef IS_REFRACTION_LINEAR\nrefractionColor=toGammaSpace(refractionColor);\n#endif\nrefractionColor*=vRefractionInfos.x;\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb;\n#endif\n#ifdef IS_REFLECTION_LINEAR\nreflectionColor=toGammaSpace(reflectionColor);\n#endif\nreflectionColor*=vReflectionInfos.x;\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\n#ifdef REFLECTIONMAP_SKYBOX_TRANSFORMED\nvPositionUVW=(reflectionMatrix*vec4(positionUpdated,1.0)).xyz;\n#else\nvPositionUVW=positionUpdated;\n#endif\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#ifdef SPECULARAA\nvec3 nDfdx=dFdx(normalW.xyz);\nvec3 nDfdy=dFdy(normalW.xyz);\nfloat slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));\n\nfloat geometricRoughnessFactor=pow(clamp(slopeSquare ,0.,1.),0.333);\n\nfloat geometricAlphaGFactor=sqrt(slopeSquare);\n#else\nfloat geometricRoughnessFactor=0.;\n#endif\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#ifdef SPECULARAA\n\n\nalphaG+=(0.75*geometricAlphaGFactor);\n#endif\n\n#ifdef REFRACTION\nvec4 environmentRefraction=vec4(0.,0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD);\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec4 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords);\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords),\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords),\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction.rgb=fromRGBD(environmentRefraction);\n#endif\n#ifdef RGBDREFRACTION\nenvironmentRefraction.rgb=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction.rgb*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec4 environmentRadiance=vec4(0.,0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef RGBDREFLECTION\nenvironmentRadiance.rgb=fromRGBD(environmentRadiance);\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance.rgb=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance.rgb*=vReflectionInfos.x;\nenvironmentRadiance.rgb*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb;\n#ifdef GAMMALIGHTMAP\nlightmapColor=toLinearSpace(lightmapColor);\n#endif\nlightmapColor*=vLightmapInfos.y;\n#endif\nlightingInfo info;\npointLightingInfo pointInfo;\nspotLightingInfo spotInfo;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(-viewDirectionW,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction.rgb*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance.rgb;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction.rgb;\nfinalRefraction*=refractance;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n#endif\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n#ifdef AMBIENT\nvec3 ambientOcclusionForDirectDiffuse=mix(vec3(1.),ambientOcclusionColor,vAmbientInfos.w);\n#else\nvec3 ambientOcclusionForDirectDiffuse=ambientOcclusionColor;\n#endif\n\n\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionForDirectDiffuse*vLightingIntensity.x +\n#ifndef UNLIT\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","rgbdEncodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);\n}","rgbdDecodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute float angle;\nattribute vec2 size;\n#ifdef ANIMATESHEET \nattribute float cellIndex;\n#endif\n#ifndef BILLBOARD \nattribute vec3 direction;\n#endif\n#ifdef BILLBOARDSTRETCHED\nattribute vec3 direction; \n#endif\n#ifdef RAMPGRADIENT\nattribute vec4 remapData;\n#endif\nattribute vec2 offset;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n#ifdef ANIMATESHEET \nuniform vec3 particlesInfos; \n#endif\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef RAMPGRADIENT\nvarying vec4 remapRanges;\n#endif\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nuniform mat4 invView;\n#endif\n#include<clipPlaneVertexDeclaration>\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner; \n}\n#ifdef BILLBOARDSTRETCHED\nvec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {\nvec3 normalizedToCamera=normalize(toCamera);\nvec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));\nvec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));\nvec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);\nvec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z);\nvec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner; \n}\n#endif\nvoid main(void) { \nvec2 cornerPos;\ncornerPos=(vec2(offset.x-0.5,offset.y-0.5)-translationPivot)*size+translationPivot;\n#ifdef BILLBOARD \n\nvec3 rotatedCorner;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner);\nvec3 viewPos=(view*vec4(worldPos,1.0)).xyz; \n#elif defined(BILLBOARDSTRETCHED)\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 toCamera=position-eyePosition; \nvec3 worldPos=rotateAlign(toCamera,rotatedCorner);\nvec3 viewPos=(view*vec4(worldPos,1.0)).xyz; \n#else\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 viewPos=(view*vec4(position,1.0)).xyz+rotatedCorner; \n#endif\n#ifdef RAMPGRADIENT\nremapRanges=remapData;\n#endif\n\ngl_Position=projection*vec4(viewPos,1.0); \n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=normalize(direction);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\ngl_Position=projection*view*vec4(worldPos,1.0); \n#endif \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nvec4 worldPos=invView*vec4(viewPos,1.0);\n#endif\n#include<clipPlaneVertex>\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#include<clipPlaneFragmentDeclaration>\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n#ifdef RAMPGRADIENT\nvarying vec4 remapRanges;\nuniform sampler2D rampSampler;\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec4 textureColor=texture2D(diffuseSampler,vUV);\nvec4 baseColor=(textureColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n#ifdef RAMPGRADIENT\nfloat alpha=baseColor.a;\nfloat remappedColorIndex=clamp((alpha-remapRanges.x)/remapRanges.y,0.0,1.0);\nvec4 rampColor=texture2D(rampSampler,vec2(1.0-remappedColorIndex,0.));\nbaseColor.rgb*=rampColor.rgb;\n\nfloat finalAlpha=baseColor.a;\nbaseColor.a=clamp((alpha*rampColor.a-remapRanges.z)/remapRanges.w,0.0,1.0);\n#endif\n#ifdef BLENDMULTIPLYMODE\nfloat sourceAlpha=vColor.a*textureColor.a;\nbaseColor.rgb=baseColor.rgb*sourceAlpha+vec3(1.0)*(1.0-sourceAlpha);\n#endif\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\nbaseColor.rgb=toLinearSpace(baseColor.rgb);\n#else\n#ifdef IMAGEPROCESSING\nbaseColor.rgb=toLinearSpace(baseColor.rgb);\nbaseColor=applyImageProcessing(baseColor);\n#endif\n#endif\ngl_FragColor=baseColor;\n}","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","gpuRenderParticlesVertexShader":"#version 300 es\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n\nin vec3 position;\nin float age;\nin float life;\nin vec3 size;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\n#ifdef BILLBOARDSTRETCHED\nin vec3 direction;\n#endif\nin float angle;\n#ifdef ANIMATESHEET\nin float cellIndex;\n#endif\nin vec2 offset;\nin vec2 uv;\nout vec2 vUV;\nout vec4 vColor;\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nuniform mat4 invView;\n#endif\n#include<clipPlaneVertexDeclaration2>\n#ifdef COLORGRADIENTS\nuniform sampler2D colorGradientSampler;\n#else\nuniform vec4 colorDead;\nin vec4 color;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 sheetInfos;\n#endif\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner;\n}\n#ifdef BILLBOARDSTRETCHED\nvec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {\nvec3 normalizedToCamera=normalize(toCamera);\nvec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));\nvec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));\nvec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);\nvec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z);\nvec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner; \n}\n#endif\nvoid main() {\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/sheetInfos.z);\nfloat columnOffset=cellIndex-rowOffset*sheetInfos.z;\nvec2 uvScale=sheetInfos.xy;\nvec2 uvOffset=vec2(uv.x ,1.0-uv.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else \nvUV=uv;\n#endif\nfloat ratio=age/life;\n#ifdef COLORGRADIENTS\nvColor=texture(colorGradientSampler,vec2(ratio,0));\n#else\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n#endif\nvec2 cornerPos=(offset-translationPivot)*size.yz*size.x+translationPivot;\n#ifdef BILLBOARD\nvec4 rotatedCorner;\nrotatedCorner.w=0.;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner.xyz);\nvec4 viewPosition=(view*vec4(worldPos,1.0)); \n#elif defined(BILLBOARDSTRETCHED)\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 toCamera=position-eyePosition; \nvec3 worldPos=rotateAlign(toCamera,rotatedCorner.xyz);\nvec4 viewPosition=(view*vec4(worldPos,1.0)); \n#else\n\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nvec4 viewPosition=view*vec4(position,1.0)+rotatedCorner;\n#endif\n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=0.;\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nvec3 yaxis=normalize(initialDirection);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\n\nvec4 viewPosition=view*vec4(worldPos,1.0); \n#endif\ngl_Position=projection*viewPosition;\n\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nvec4 worldPos=invView*viewPosition;\n#endif \n#include<clipPlaneVertex>\n}","gpuRenderParticlesPixelShader":"#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#include<clipPlaneFragmentDeclaration2> \n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main() {\n#include<clipPlaneFragment> \nvec4 textureColor=texture(textureSampler,vUV);\noutFragColor=textureColor*vColor;\n#ifdef BLENDMULTIPLYMODE\nfloat alpha=vColor.a*textureColor.a;\noutFragColor.rgb=outFragColor.rgb*alpha+vec3(1.0)*(1.0-alpha); \n#endif \n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\noutFragColor.rgb=toLinearSpace(outFragColor.rgb);\n#else\n#ifdef IMAGEPROCESSING\noutFragColor.rgb=toLinearSpace(outFragColor.rgb);\noutFragColor=applyImageProcessing(outFragColor);\n#endif\n#endif\n}\n","gpuUpdateParticlesVertexShader":"#version 300 es\n#define PI 3.14159\nuniform float currentCount;\nuniform float timeDelta;\nuniform float stopFactor;\nuniform mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 scaleRange;\n#ifndef COLORGRADIENTS\nuniform vec4 color1;\nuniform vec4 color2;\n#endif\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\nuniform sampler2D randomSampler2;\nuniform vec4 angleRange;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef POINTEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#endif\n#ifdef HEMISPHERICEMITTER\nuniform float radius;\nuniform float radiusRange;\nuniform float directionRandomizer;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\nuniform float radiusRange;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CYLINDEREMITTER\nuniform float radius;\nuniform float height;\nuniform float radiusRange;\n#ifdef DIRECTEDCYLINDEREMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform vec2 radius;\nuniform float coneAngle;\nuniform vec2 height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin vec4 seed;\nin vec3 size;\n#ifndef COLORGRADIENTS\nin vec4 color;\n#endif\nin vec3 direction;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nin float angle;\n#else\nin vec2 angle;\n#endif\n#ifdef ANIMATESHEET\nin float cellIndex;\n#ifdef ANIMATESHEETRANDOMSTART\nin float cellStartOffset;\n#endif\n#endif\n#ifdef NOISE\nin vec3 noiseCoordinates1;\nin vec3 noiseCoordinates2;\n#endif\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout vec4 outSeed;\nout vec3 outSize;\n#ifndef COLORGRADIENTS\nout vec4 outColor;\n#endif\nout vec3 outDirection;\n#ifndef BILLBOARD\nout vec3 outInitialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nout float outAngle;\n#else\nout vec2 outAngle;\n#endif\n#ifdef ANIMATESHEET\nout float outCellIndex;\n#ifdef ANIMATESHEETRANDOMSTART\nout float outCellStartOffset;\n#endif\n#endif\n#ifdef NOISE\nout vec3 outNoiseCoordinates1;\nout vec3 outNoiseCoordinates2;\n#endif\n#ifdef SIZEGRADIENTS\nuniform sampler2D sizeGradientSampler;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nuniform sampler2D angularSpeedGradientSampler;\n#endif \n#ifdef VELOCITYGRADIENTS\nuniform sampler2D velocityGradientSampler;\n#endif\n#ifdef LIMITVELOCITYGRADIENTS\nuniform sampler2D limitVelocityGradientSampler;\nuniform float limitVelocityDamping;\n#endif\n#ifdef DRAGGRADIENTS\nuniform sampler2D dragGradientSampler;\n#endif\n#ifdef NOISE\nuniform vec3 noiseStrength;\nuniform sampler2D noiseSampler;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 cellInfos;\n#endif\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler2,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;\n}\nvec4 getRandomVec4(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));\n}\nvoid main() {\nfloat newAge=age+timeDelta; \n\nif (newAge>=life && stopFactor != 0.) {\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(seed.x);\n\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\noutAge=mod(newAge,outLife);\n\noutSeed=seed;\n\n#ifdef SIZEGRADIENTS \noutSize.x=texture(sizeGradientSampler,vec2(0,0)).r;\n#else\noutSize.x=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n#endif\noutSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;\noutSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a; \n#ifndef COLORGRADIENTS\n\noutColor=color1+(color2-color1)*randoms.b;\n#endif\n\n#ifndef ANGULARSPEEDGRADIENTS \noutAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;\noutAngle.x=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#else\noutAngle=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#endif \n\n#ifdef POINTEMITTER\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nposition=vec3(0,0,0);\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(BOXEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3; \n#elif defined(HEMISPHERICEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=acos(2.0*randoms2.y-1.0);\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,abs(randY),randZ);\ndirection=position+directionRandomizer*randoms3; \n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=acos(2.0*randoms2.y-1.0);\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,randY,randZ);\n#ifdef DIRECTEDSPHEREEMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\ndirection=position+directionRandomizer*randoms3;\n#endif\n#elif defined(CYLINDEREMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat yPos=(randoms2.x-0.5)*height;\nfloat angle=randoms2.y*PI*2.;\nfloat inverseRadiusRangeSquared=((1.-radiusRange)*(1.-radiusRange));\nfloat positionRadius=radius*sqrt(inverseRadiusRangeSquared+(randoms2.z*(1.-inverseRadiusRangeSquared)));\nfloat xPos=positionRadius*cos(angle);\nfloat zPos=positionRadius*sin(angle);\nposition=vec3(xPos,yPos,zPos);\n#ifdef DIRECTEDCYLINDEREMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\nangle=angle+((randoms3.x-0.5)*PI);\ndirection=vec3(cos(angle),randoms3.y-0.5,sin(angle));\ndirection=normalize(direction);\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nfloat s=2.0*PI*randoms2.x;\n#ifdef CONEEMITTERSPAWNPOINT\nfloat h=0.00001;\n#else\nfloat h=randoms2.y*height.y;\n\nh=1.-h*h; \n#endif\nfloat lRadius=radius.x-radius.x*randoms2.z*radius.y;\nlRadius=lRadius*h;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height.x;\nposition=vec3(randX,randY,randZ); \n\nif (abs(cos(coneAngle)) == 1.0) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(seed.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed.w)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\noutPosition=(emitterWM*vec4(position,1.)).xyz;\nvec3 initial=(emitterWM*vec4(direction,0.)).xyz;\noutDirection=initial*power;\n#ifndef BILLBOARD \noutInitialDirection=initial;\n#endif\n#ifdef ANIMATESHEET \noutCellIndex=cellInfos.x;\n#ifdef ANIMATESHEETRANDOMSTART\noutCellStartOffset=randoms.a*outLife;\n#endif \n#endif\n#ifdef NOISE\noutNoiseCoordinates1=noiseCoordinates1;\noutNoiseCoordinates2=noiseCoordinates2;\n#endif\n} else {\nfloat directionScale=timeDelta;\noutAge=newAge;\nfloat ageGradient=newAge/life;\n#ifdef VELOCITYGRADIENTS\ndirectionScale*=texture(velocityGradientSampler,vec2(ageGradient,0)).r;\n#endif\n#ifdef DRAGGRADIENTS\ndirectionScale*=1.0-texture(dragGradientSampler,vec2(ageGradient,0)).r;\n#endif\noutPosition=position+direction*directionScale;\noutLife=life;\noutSeed=seed;\n#ifndef COLORGRADIENTS \noutColor=color;\n#endif\n#ifdef SIZEGRADIENTS\noutSize.x=texture(sizeGradientSampler,vec2(ageGradient,0)).r;\noutSize.yz=size.yz;\n#else\noutSize=size;\n#endif \n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif\nvec3 updatedDirection=direction+gravity*timeDelta;\n#ifdef LIMITVELOCITYGRADIENTS\nfloat limitVelocity=texture(limitVelocityGradientSampler,vec2(ageGradient,0)).r;\nfloat currentVelocity=length(updatedDirection);\nif (currentVelocity>limitVelocity) {\nupdatedDirection=updatedDirection*limitVelocityDamping;\n}\n#endif\noutDirection=updatedDirection;\n#ifdef NOISE\nvec3 localPosition=outPosition-emitterWM[3].xyz;\nfloat fetchedR=texture(noiseSampler,vec2(noiseCoordinates1.x,noiseCoordinates1.y)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedG=texture(noiseSampler,vec2(noiseCoordinates1.z,noiseCoordinates2.x)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedB=texture(noiseSampler,vec2(noiseCoordinates2.y,noiseCoordinates2.z)*vec2(0.5)+vec2(0.5)).r;\nvec3 force=vec3(2.*fetchedR-1.,2.*fetchedG-1.,2.*fetchedB-1.)*noiseStrength;\noutDirection=outDirection+force*timeDelta;\noutNoiseCoordinates1=noiseCoordinates1;\noutNoiseCoordinates2=noiseCoordinates2;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nfloat angularSpeed=texture(angularSpeedGradientSampler,vec2(ageGradient,0)).r;\noutAngle=angle+angularSpeed*timeDelta;\n#else\noutAngle=vec2(angle.x+angle.y*timeDelta,angle.y);\n#endif\n#ifdef ANIMATESHEET \nfloat offsetAge=outAge;\nfloat dist=cellInfos.y-cellInfos.x;\n#ifdef ANIMATESHEETRANDOMSTART\noutCellStartOffset=cellStartOffset;\noffsetAge+=cellStartOffset;\n#endif \nfloat ratio=clamp(mod(offsetAge*cellInfos.z,life)/life,0.,1.0);\noutCellIndex=float(int(cellInfos.x+ratio*dist));\n#endif\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\n","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\nuniform vec3 lightData;\n#endif\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\n#include<helperFunctions>\nuniform mat4 viewProjection;\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvec3 worldNor=normalize(normalWorld*normal);\n#ifdef DIRECTIONINLIGHTDATA\nvec3 worldLightDir=normalize(-lightData.xyz);\n#else\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\nvec3 worldLightDir=normalize(directionToLight);\n#endif\nfloat ndl=dot(worldNor,worldLightDir);\nfloat sinNL=sqrt(1.0-ndl*ndl);\nfloat normalBias=biasAndScale.y*sinNL;\nworldPos.xyz-=worldNor*normalBias;\n#endif\n\ngl_Position=viewProjection*worldPos;\n#ifdef DEPTHTEXTURE\n\ngl_Position.z+=biasAndScale.x*gl_Position.w;\n#endif\n\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.z*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nfloat scales[16]=float[16](\n0.1,\n0.11406250000000001,\n0.131640625,\n0.15625,\n0.187890625,\n0.2265625,\n0.272265625,\n0.325,\n0.384765625,\n0.4515625,\n0.525390625,\n0.60625,\n0.694140625,\n0.7890625,\n0.891015625,\n1.0\n);\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\n\nfloat dotProduct=dot(rvec,normal);\nrvec=1.0-abs(dotProduct)>1e-2 ? rvec : vec3(-rvec.y,0.0,rvec.x);\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=scales[(i+int(random.x*16.0)) % 16]*tbn*sampleSphere[(i+int(random.y*16.0)) % 16];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\ndifference=depthSign*samplePosition.z-sampleDepth;\nfloat rangeCheck=1.0-smoothstep(correctedRadius*0.5,correctedRadius,difference);\nocclusion+=(difference>=0.0 ? 1.0 : 0.0)*rangeCheck;\n}\nocclusion=occlusion*(1.0-smoothstep(maxZ*0.75,maxZ,depth));\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nuniform vec4 viewport;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,viewport.xy+vUV*viewport.zw);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\n#ifndef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\n#endif\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\n#ifdef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\n}\nelse\n{\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}\n#else\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n#endif\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\noriginal.a=clamp(texture2D(textureSampler,ref_coords_r).a+texture2D(textureSampler,ref_coords_g).a+texture2D(textureSampler,ref_coords_b).a,0.,1.);\ngl_FragColor=original;\n}","grainPixelShader":"#include<helperFunctions>\n\nuniform sampler2D textureSampler; \n\nuniform float intensity;\nuniform float animatedSeed;\n\nvarying vec2 vUV;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec2 seed=vUV*(animatedSeed);\nfloat grain=dither(seed,intensity);\n\nfloat lum=getLuminance(gl_FragColor.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\ngl_FragColor.rgb+=grain*grainAmount;\ngl_FragColor.rgb=max(gl_FragColor.rgb,0.0);\n}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\nfloat sampleCoC(const in vec2 offset) {\nfloat coc=texture2D(circleOfConfusionSampler,offset).r; \nreturn coc; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT; \nfloat factor=0.0;\n\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\nuniform sampler2D circleOfConfusionSampler;\nuniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\n#if BLUR_LEVEL == 0\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nif(coc<0.5){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nif(coc<0.33){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);\n}\n#endif\n}\n","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nvoid main(void)\n{\nfloat depth=texture2D(depthSampler,vUV).r;\nfloat pixelDistance=(cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,depth,coc,1.0);\n}\n","bloomMergePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D bloomBlur;\nvarying vec2 vUV;\nuniform float bloomWeight;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec3 blurred=texture2D(bloomBlur,vUV).rgb;\ngl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); \n}\n","extractHighlightsPixelShader":"#include<helperFunctions>\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float threshold;\nuniform float exposure;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat luma=getLuminance(gl_FragColor.rgb*exposure);\ngl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(positionUpdated,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\n#ifdef REFLECTIONMAP_SKYBOX_TRANSFORMED\nvPositionUVW=(reflectionMatrix*vec4(position,1.0)).xyz;\n#else\nvPositionUVW=position;\n#endif\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec4 reflectionColor=vec4(1.,1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample;\n#endif\n#ifdef RGBDREFLECTION\nreflectionColor.rgb=fromRGBD(reflectionColor);\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor.rgb=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor.rgb=reflectionColor.bgr;\n#endif\n\nreflectionColor.rgb*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor.rgb*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nvec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase);\n#else\nvec3 mainColor=vPrimaryColor.rgb;\n#endif\nvec3 finalColor=colorBase*mainColor;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor.rgb,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\ngl_FragColor=color;\n}\n","noisePixelShader":"\n\nuniform float brightness;\nuniform float persistence;\nuniform float timeScale;\n\nvarying vec2 vUV;\n\nvec2 hash22(vec2 p)\n{\np=p*mat2(127.1,311.7,269.5,183.3);\np=-1.0+2.0*fract(sin(p)*43758.5453123);\nreturn sin(p*6.283+timeScale);\n}\nfloat interpolationNoise(vec2 p)\n{\nvec2 pi=floor(p);\nvec2 pf=p-pi;\nvec2 w=pf*pf*(3.-2.*pf);\nfloat f00=dot(hash22(pi+vec2(.0,.0)),pf-vec2(.0,.0));\nfloat f01=dot(hash22(pi+vec2(.0,1.)),pf-vec2(.0,1.));\nfloat f10=dot(hash22(pi+vec2(1.0,0.)),pf-vec2(1.0,0.));\nfloat f11=dot(hash22(pi+vec2(1.0,1.)),pf-vec2(1.0,1.));\nfloat xm1=mix(f00,f10,w.x);\nfloat xm2=mix(f01,f11,w.x);\nfloat ym=mix(xm1,xm2,w.y); \nreturn ym;\n}\nfloat perlinNoise2D(float x,float y)\n{\nfloat sum=0.0;\nfloat frequency=0.0;\nfloat amplitude=0.0;\nfor(int i=0; i<OCTAVES; i++)\n{\nfrequency=pow(2.0,float(i));\namplitude=pow(persistence,float(i));\nsum=sum+interpolationNoise(vec2(x*frequency,y*frequency))*amplitude;\n}\nreturn sum;\n}\n\nvoid main(void)\n{\nfloat x=abs(vUV.x);\nfloat y=abs(vUV.y);\nfloat noise=brightness+(1.0-brightness)*perlinNoise2D(x,y);\ngl_FragColor=vec4(noise,noise,noise,1.0);\n}\n"};
  116692. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nuniform vec4 vClipPlane2;\nvarying float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nuniform vec4 vClipPlane3;\nvarying float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nuniform vec4 vClipPlane4;\nvarying float fClipDistance4;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n#ifdef CLIPPLANE2\nfClipDistance2=dot(worldPos,vClipPlane2);\n#endif\n#ifdef CLIPPLANE3\nfClipDistance3=dot(worldPos,vClipPlane3);\n#endif\n#ifdef CLIPPLANE4\nfClipDistance4=dot(worldPos,vClipPlane4);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nfloat dither(vec2 seed,float varianceAmount) {\nfloat rand=getRand(seed);\nfloat dither=mix(-varianceAmount/255.0,varianceAmount/255.0,rand);\nreturn dither;\n}\n\nconst float rgbdMaxRange=255.0;\nvec4 toRGBD(vec3 color) {\nfloat maxRGB=max(0.0000001,max(color.r,max(color.g,color.b)));\nfloat D=max(rgbdMaxRange/maxRGB,1.);\nD=clamp(floor(D)/255.0,0.,1.);\n\nvec3 rgb=color.rgb*D;\n\nrgb=toGammaSpace(rgb);\nreturn vec4(rgb,D); \n}\nvec3 fromRGBD(vec4 rgbd) {\n\nrgbd.rgb=toLinearSpace(rgbd.rgb);\n\nreturn rgbd.rgb/rgbd.a;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\nuniform vec4 vLightFalloff{X};\n#elif defined(POINTLIGHT{X})\nuniform vec4 vLightFalloff{X};\n#elif defined(HEMILIGHT{X})\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn textureColor;\n}","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\nvec4 vLightFalloff;\n#elif defined(POINTLIGHT{X})\nvec4 vLightFalloff;\n#elif defined(HEMILIGHT{X})\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X}; \n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef REFLECTION\nuniform mat4 reflectionMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPoissonSamplingCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#ifdef WEBGL2\n\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat shadow=texture2D(shadowSampler,uvDepth);\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\n\n\nvec2 uvw0=3.-2.*st;\nvec2 uvw1=1.+2.*st;\nvec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;\nvec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow=shadow/16.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\nvec2 uvw0=4.-3.*st;\nvec2 uvw1=vec2(7.);\nvec2 uvw2=1.+3.*st;\nvec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;\nvec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z));\nshadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z));\nshadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z));\nshadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z));\nshadow=shadow/144.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nconst vec3 PoissonSamplers32[64]=vec3[64](\nvec3(0.06407013,0.05409927,0.),\nvec3(0.7366577,0.5789394,0.),\nvec3(-0.6270542,-0.5320278,0.),\nvec3(-0.4096107,0.8411095,0.),\nvec3(0.6849564,-0.4990818,0.),\nvec3(-0.874181,-0.04579735,0.),\nvec3(0.9989998,0.0009880066,0.),\nvec3(-0.004920578,-0.9151649,0.),\nvec3(0.1805763,0.9747483,0.),\nvec3(-0.2138451,0.2635818,0.),\nvec3(0.109845,0.3884785,0.),\nvec3(0.06876755,-0.3581074,0.),\nvec3(0.374073,-0.7661266,0.),\nvec3(0.3079132,-0.1216763,0.),\nvec3(-0.3794335,-0.8271583,0.),\nvec3(-0.203878,-0.07715034,0.),\nvec3(0.5912697,0.1469799,0.),\nvec3(-0.88069,0.3031784,0.),\nvec3(0.5040108,0.8283722,0.),\nvec3(-0.5844124,0.5494877,0.),\nvec3(0.6017799,-0.1726654,0.),\nvec3(-0.5554981,0.1559997,0.),\nvec3(-0.3016369,-0.3900928,0.),\nvec3(-0.5550632,-0.1723762,0.),\nvec3(0.925029,0.2995041,0.),\nvec3(-0.2473137,0.5538505,0.),\nvec3(0.9183037,-0.2862392,0.),\nvec3(0.2469421,0.6718712,0.),\nvec3(0.3916397,-0.4328209,0.),\nvec3(-0.03576927,-0.6220032,0.),\nvec3(-0.04661255,0.7995201,0.),\nvec3(0.4402924,0.3640312,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.)\n);\nconst vec3 PoissonSamplers64[64]=vec3[64](\nvec3(-0.613392,0.617481,0.),\nvec3(0.170019,-0.040254,0.),\nvec3(-0.299417,0.791925,0.),\nvec3(0.645680,0.493210,0.),\nvec3(-0.651784,0.717887,0.),\nvec3(0.421003,0.027070,0.),\nvec3(-0.817194,-0.271096,0.),\nvec3(-0.705374,-0.668203,0.),\nvec3(0.977050,-0.108615,0.),\nvec3(0.063326,0.142369,0.),\nvec3(0.203528,0.214331,0.),\nvec3(-0.667531,0.326090,0.),\nvec3(-0.098422,-0.295755,0.),\nvec3(-0.885922,0.215369,0.),\nvec3(0.566637,0.605213,0.),\nvec3(0.039766,-0.396100,0.),\nvec3(0.751946,0.453352,0.),\nvec3(0.078707,-0.715323,0.),\nvec3(-0.075838,-0.529344,0.),\nvec3(0.724479,-0.580798,0.),\nvec3(0.222999,-0.215125,0.),\nvec3(-0.467574,-0.405438,0.),\nvec3(-0.248268,-0.814753,0.),\nvec3(0.354411,-0.887570,0.),\nvec3(0.175817,0.382366,0.),\nvec3(0.487472,-0.063082,0.),\nvec3(-0.084078,0.898312,0.),\nvec3(0.488876,-0.783441,0.),\nvec3(0.470016,0.217933,0.),\nvec3(-0.696890,-0.549791,0.),\nvec3(-0.149693,0.605762,0.),\nvec3(0.034211,0.979980,0.),\nvec3(0.503098,-0.308878,0.),\nvec3(-0.016205,-0.872921,0.),\nvec3(0.385784,-0.393902,0.),\nvec3(-0.146886,-0.859249,0.),\nvec3(0.643361,0.164098,0.),\nvec3(0.634388,-0.049471,0.),\nvec3(-0.688894,0.007843,0.),\nvec3(0.464034,-0.188818,0.),\nvec3(-0.440840,0.137486,0.),\nvec3(0.364483,0.511704,0.),\nvec3(0.034028,0.325968,0.),\nvec3(0.099094,-0.308023,0.),\nvec3(0.693960,-0.366253,0.),\nvec3(0.678884,-0.204688,0.),\nvec3(0.001801,0.780328,0.),\nvec3(0.145177,-0.898984,0.),\nvec3(0.062655,-0.611866,0.),\nvec3(0.315226,-0.604297,0.),\nvec3(-0.780145,0.486251,0.),\nvec3(-0.371868,0.882138,0.),\nvec3(0.200476,0.494430,0.),\nvec3(-0.494552,-0.711051,0.),\nvec3(0.612476,0.705252,0.),\nvec3(-0.578845,-0.768792,0.),\nvec3(-0.772454,-0.090976,0.),\nvec3(0.504440,0.372295,0.),\nvec3(0.155736,0.065157,0.),\nvec3(0.391522,0.849605,0.),\nvec3(-0.620106,-0.328104,0.),\nvec3(0.789239,-0.419965,0.),\nvec3(-0.545396,0.538133,0.),\nvec3(-0.178564,-0.596057,0.)\n);\n\n\n\n\n\nfloat computeShadowWithPCSS(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat blockerDepth=0.0;\nfloat sumBlockerDepth=0.0;\nfloat numBlocker=0.0;\nfor (int i=0; i<searchTapCount; i ++) {\nblockerDepth=texture(depthSampler,uvDepth.xy+(lightSizeUV*shadowMapSizeInverse*PoissonSamplers32[i].xy)).r;\nif (blockerDepth<depthMetric) {\nsumBlockerDepth+=blockerDepth;\nnumBlocker++;\n}\n}\nif (numBlocker<1.0) {\nreturn 1.0;\n}\nfloat avgBlockerDepth=sumBlockerDepth/numBlocker;\n\nfloat AAOffset=shadowMapSizeInverse*10.;\n\n\nfloat penumbraRatio=((depthMetric-avgBlockerDepth)+AAOffset);\nfloat filterRadius=penumbraRatio*lightSizeUV*shadowMapSizeInverse;\nfloat random=getRand(vPositionFromLight.xy);\nfloat rotationAngle=random*3.1415926;\nvec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));\nfloat shadow=0.;\nfor (int i=0; i<pcfTapCount; i++) {\nvec3 offset=poissonSamplers[i];\n\noffset=vec3(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.);\nshadow+=texture2D(shadowSampler,uvDepth+offset*filterRadius);\n}\nshadow/=float(pcfTapCount);\n\nshadow=mix(shadow,1.,depthMetric-avgBlockerDepth);\n\nshadow=mix(darkness,1.,shadow);\n\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithPCSS16(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS32(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS64(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);\n}\n#endif\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\n\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\n\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\n\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\n\nvec3 intersectPositionWS=vertexPos+origVec*distance;\n\nreturn intersectPositionWS-cubePos;\n}\n#endif\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=normalize(vDirectionW);\nfloat lon=atan(direction.z,direction.x);\nfloat lat=acos(direction.y);\nvec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;\nfloat s=sphereCoords.x*0.5+0.5;\nfloat t=sphereCoords.y; \n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=normalize(reflect(cameraToVertex,worldNormal));\nfloat lon=atan(r.z,r.x);\nfloat lat=acos(r.y);\nvec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;\nfloat s=sphereCoords.x*0.5+0.5;\nfloat t=sphereCoords.y; \nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=normalize(worldPos.xyz-vEyePosition.xyz);\n\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,vReflectionSize,vReflectionPosition);\n#endif\ncoords=vec3(reflectionMatrix*vec4(coords,0));\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\n#ifdef TONEMAPPING_ACES\n\n\n\n\n\nconst mat3 ACESInputMat=mat3(\nvec3(0.59719,0.07600,0.02840),\nvec3(0.35458,0.90834,0.13383),\nvec3(0.04823,0.01566,0.83777)\n);\n\nconst mat3 ACESOutputMat=mat3(\nvec3( 1.60475,-0.10208,-0.00327),\nvec3(-0.53108,1.10813,-0.07276),\nvec3(-0.07367,-0.00605,1.07602)\n);\nvec3 RRTAndODTFit(vec3 v)\n{\nvec3 a=v*(v+0.0245786)-0.000090537;\nvec3 b=v*(0.983729*v+0.4329510)+0.238081;\nreturn a/b;\n}\nvec3 ACESFitted(vec3 color)\n{\ncolor=ACESInputMat*color;\n\ncolor=RRTAndODTFit(color);\ncolor=ACESOutputMat*color;\n\ncolor=clamp(color,0.0,1.0);\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\n#ifdef TONEMAPPING_ACES\nresult.rgb=ACESFitted(result.rgb);\n#else\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform mat4 normalMatrix;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nvarying float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nvarying float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nvarying float fClipDistance4;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif\n#ifdef CLIPPLANE2\nif (fClipDistance2>0.0)\n{\ndiscard;\n}\n#endif\n#ifdef CLIPPLANE3\nif (fClipDistance3>0.0)\n{\ndiscard;\n}\n#endif\n#ifdef CLIPPLANE4\nif (fClipDistance4>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0);\nnormalW=normalize(mat3(normalMatrix)*normalW); \n#else\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\nspotInfo=computeSpotLightingInfo(light{X}.vLightData);\n#ifdef LIGHT_FALLOFF_GLTF{X}\nspotInfo.attenuation=computeDistanceLightFalloff_GLTF(spotInfo.lightDistanceSquared,light{X}.vLightFalloff.y);\nspotInfo.attenuation*=computeDirectionalLightFalloff_GLTF(light{X}.vLightDirection.xyz,spotInfo.directionToLightCenterW,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w);\n#elif defined(LIGHT_FALLOFF_PHYSICAL{X})\nspotInfo.attenuation=computeDistanceLightFalloff_Physical(spotInfo.lightDistanceSquared);\nspotInfo.attenuation*=computeDirectionalLightFalloff_Physical(light{X}.vLightDirection.xyz,spotInfo.directionToLightCenterW,light{X}.vLightDirection.w);\n#elif defined(LIGHT_FALLOFF_STANDARD{X})\nspotInfo.attenuation=computeDistanceLightFalloff_Standard(spotInfo.lightOffset,light{X}.vLightFalloff.x);\nspotInfo.attenuation*=computeDirectionalLightFalloff_Standard(light{X}.vLightDirection.xyz,spotInfo.directionToLightCenterW,light{X}.vLightDirection.w,light{X}.vLightData.w);\n#else\nspotInfo.attenuation=computeDistanceLightFalloff(spotInfo.lightOffset,spotInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y);\nspotInfo.attenuation*=computeDirectionalLightFalloff(light{X}.vLightDirection.xyz,spotInfo.directionToLightCenterW,light{X}.vLightDirection.w,light{X}.vLightData.w,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w);\n#endif\ninfo=computeSpotLighting(spotInfo,viewDirectionW,normalW,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#elif defined(POINTLIGHT{X})\npointInfo=computePointLightingInfo(light{X}.vLightData);\n#ifdef LIGHT_FALLOFF_GLTF{X}\npointInfo.attenuation=computeDistanceLightFalloff_GLTF(pointInfo.lightDistanceSquared,light{X}.vLightFalloff.y);\n#elif defined(LIGHT_FALLOFF_PHYSICAL{X})\npointInfo.attenuation=computeDistanceLightFalloff_Physical(pointInfo.lightDistanceSquared);\n#elif defined(LIGHT_FALLOFF_STANDARD{X})\npointInfo.attenuation=computeDistanceLightFalloff_Standard(pointInfo.lightOffset,light{X}.vLightFalloff.x);\n#else\npointInfo.attenuation=computeDistanceLightFalloff(pointInfo.lightOffset,pointInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y);\n#endif\ninfo=computePointLighting(pointInfo,viewDirectionW,normalW,light{X}.vLightDiffuse.rgb,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#elif defined(HEMILIGHT{X})\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#elif defined(DIRLIGHT{X})\ninfo=computeDirectionalLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#elif defined(HEMILIGHT{X})\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#elif defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWESM{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPOISSON{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPoissonSamplingCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec4 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec4 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec4 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor)\n{\nroughness=max(roughness,geometricRoughnessFactor);\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#if defined(USEPHYSICALLIGHTFALLOFF) || defined(USEGLTFLIGHTFALLOFF)\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 view,vec3 normal) {\n\nvec3 reflection=reflect(view,normal);\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nstruct pointLightingInfo\n{\nvec3 lightOffset;\nfloat lightDistanceSquared;\nfloat attenuation;\n};\nstruct spotLightingInfo\n{\nvec3 lightOffset;\nfloat lightDistanceSquared;\nvec3 directionToLightCenterW;\nfloat attenuation;\n};\nfloat computeDistanceLightFalloff_Standard(vec3 lightOffset,float range)\n{\nreturn max(0.,1.0-length(lightOffset)/range);\n}\nfloat computeDistanceLightFalloff_Physical(float lightDistanceSquared)\n{\nreturn 1.0/((lightDistanceSquared+0.001));\n}\nfloat computeDistanceLightFalloff_GLTF(float lightDistanceSquared,float inverseSquaredRange)\n{\nconst float minDistanceSquared=0.01*0.01;\nfloat lightDistanceFalloff=1.0/(max(lightDistanceSquared,minDistanceSquared));\nfloat factor=lightDistanceSquared*inverseSquaredRange;\nfloat attenuation=clamp(1.0-factor*factor,0.,1.);\nattenuation*=attenuation;\n\nlightDistanceFalloff*=attenuation;\nreturn lightDistanceFalloff;\n}\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range,float inverseSquaredRange)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nreturn computeDistanceLightFalloff_Physical(lightDistanceSquared);\n#elif defined(USEGLTFLIGHTFALLOFF)\nreturn computeDistanceLightFalloff_GLTF(lightDistanceSquared,inverseSquaredRange);\n#else\nreturn computeDistanceLightFalloff_Standard(lightOffset,range);\n#endif\n}\nfloat computeDirectionalLightFalloff_Standard(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\nreturn falloff;\n}\nfloat computeDirectionalLightFalloff_Physical(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle)\n{\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfloat falloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\nreturn falloff;\n}\nfloat computeDirectionalLightFalloff_GLTF(vec3 lightDirection,vec3 directionToLightCenterW,float lightAngleScale,float lightAngleOffset)\n{\n\n\n\nfloat cd=dot(-lightDirection,directionToLightCenterW);\nfloat falloff=clamp(cd*lightAngleScale+lightAngleOffset,0.,1.);\n\nfalloff*=falloff;\nreturn falloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent,float lightAngleScale,float lightAngleOffset)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\nreturn computeDirectionalLightFalloff_Physical(lightDirection,directionToLightCenterW,cosHalfAngle);\n#elif defined(USEGLTFLIGHTFALLOFF)\nreturn computeDirectionalLightFalloff_GLTF(lightDirection,directionToLightCenterW,lightAngleScale,lightAngleOffset);\n#else\nreturn computeDirectionalLightFalloff_Standard(lightDirection,directionToLightCenterW,cosHalfAngle,exponent);\n#endif\n}\npointLightingInfo computePointLightingInfo(vec4 lightData) {\npointLightingInfo result;\nresult.lightOffset=lightData.xyz-vPositionW;\nresult.lightDistanceSquared=dot(result.lightOffset,result.lightOffset);\nreturn result;\n}\nspotLightingInfo computeSpotLightingInfo(vec4 lightData) {\nspotLightingInfo result;\nresult.lightOffset=lightData.xyz-vPositionW;\nresult.directionToLightCenterW=normalize(result.lightOffset);\nresult.lightDistanceSquared=dot(result.lightOffset,result.lightOffset);\nreturn result;\n}\nlightingInfo computePointLighting(pointLightingInfo info,vec3 viewDirectionW,vec3 vNormal,vec3 diffuseColor,float lightRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nfloat lightDistance=sqrt(info.lightDistanceSquared);\nvec3 lightDirection=normalize(info.lightOffset);\n\nroughness=adjustRoughnessFromLightProperties(roughness,lightRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*info.attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*info.attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(spotLightingInfo info,vec3 viewDirectionW,vec3 vNormal,vec4 lightDirection,vec3 diffuseColor,float lightRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\n\nfloat lightDistance=sqrt(info.lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,lightRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+info.directionToLightCenterW);\nNdotL=clamp(dot(vNormal,info.directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*info.attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*info.attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeDirectionalLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float lightRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nfloat lightDistance=length(-lightData.xyz);\nvec3 lightDirection=normalize(-lightData.xyz);\n\nroughness=adjustRoughnessFromLightProperties(roughness,lightRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn toLinearSpace(textureColor);\n}","clipPlaneVertexDeclaration2":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nout float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nuniform vec4 vClipPlane2;\nout float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nuniform vec4 vClipPlane3;\nout float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nuniform vec4 vClipPlane4;\nout float fClipDistance4;\n#endif","clipPlaneFragmentDeclaration2":"#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nin float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nin float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nin float fClipDistance4;\n#endif","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","kernelBlurFragment":"#ifdef DOF\nfactor=sampleCoC(sampleCoord{X}); \ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif","kernelBlurFragment2":"#ifdef DOF\nfactor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nuniform vec4 vPrimaryColorShadow;\n#endif\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vPrimaryColorShadow;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};